1
0
Fork 0

Add support for ppm

This commit is contained in:
jvoisin 2019-09-01 09:28:46 -07:00
parent fc924239fe
commit 397a18b0cc
3 changed files with 61 additions and 2 deletions

View File

@ -1,6 +1,7 @@
import imghdr
import os
from typing import Set, Dict, Union
import re
from typing import Set, Dict, Union, Any
import cairo
@ -9,10 +10,11 @@ gi.require_version('GdkPixbuf', '2.0')
gi.require_version('Rsvg', '2.0')
from gi.repository import GdkPixbuf, GLib, Rsvg
from . import exiftool
from . import exiftool, abstract
# Make pyflakes happy
assert Set
assert Any
class SVGParser(exiftool.ExiftoolParser):
mimetypes = {'image/svg+xml', }
@ -138,3 +140,23 @@ class TiffParser(GdkPixbufAbstractParser):
'FilePermissions', 'FileSize', 'FileType',
'FileTypeExtension', 'ImageHeight', 'ImageSize',
'ImageWidth', 'MIMEType', 'Megapixels', 'SourceFile'}
class PPMParser(abstract.AbstractParser):
mimetypes = {'image/x-portable-pixmap'}
def get_meta(self) -> Dict[str, Union[str, dict]]:
meta = {} # type: Dict[str, Union[str, Dict[Any, Any]]]
with open(self.filename) as f:
for idx, line in enumerate(f):
if line.lstrip().startswith('#'):
meta[str(idx)] = line.lstrip().rstrip()
return meta
def remove_all(self) -> bool:
with open(self.filename) as fin:
with open(self.output_filename, 'w') as fout:
for line in fin:
if not line.lstrip().startswith('#'):
line = re.sub(r"\s+", "", line, flags=re.UNICODE)
fout.write(line)
return True

8
tests/data/dirty.ppm Normal file
View File

@ -0,0 +1,8 @@
P3
# A metadata
3 2 1
1 0 1 0 1 0 0 0 1
# And an other one
1 1 0 1 0 1 1 0 0
# and a final one here

View File

@ -113,6 +113,14 @@ class TestGetMeta(unittest.TestCase):
meta = p.get_meta()
self.assertEqual(meta['Comment'], 'Created with GIMP')
def test_ppm(self):
p = images.PPMParser('./tests/data/dirty.ppm')
meta = p.get_meta()
self.assertEqual(meta['1'], '# A metadata')
self.assertEqual(meta['4'], '# And an other one')
self.assertEqual(meta['6'], '# and a final one here')
def test_tiff(self):
p = images.TiffParser('./tests/data/dirty.tiff')
meta = p.get_meta()
@ -887,3 +895,24 @@ class TestCleaning(unittest.TestCase):
p = images.SVGParser('./tests/data/weird.svg')
self.assertEqual(p.get_meta()['Xmlns'], 'http://www.w3.org/1337/svg')
def test_ppm(self):
shutil.copy('./tests/data/dirty.ppm', './tests/data/clean.ppm')
p = images.PPMParser('./tests/data/clean.ppm')
meta = p.get_meta()
print(meta)
self.assertEqual(meta['1'], '# A metadata')
ret = p.remove_all()
self.assertTrue(ret)
p = images.PPMParser('./tests/data/clean.cleaned.ppm')
self.assertEqual(p.get_meta(), {})
self.assertTrue(p.remove_all())
os.remove('./tests/data/clean.ppm')
os.remove('./tests/data/clean.cleaned.ppm')
os.remove('./tests/data/clean.cleaned.cleaned.ppm')