diff --git a/glymur/jp2box.py b/glymur/jp2box.py index 99a1dee..363611a 100644 --- a/glymur/jp2box.py +++ b/glymur/jp2box.py @@ -1537,8 +1537,24 @@ class XMLBox(Jp2kBox): xml : ElementTree.Element XML section. """ - def __init__(self, **kwargs): + def __init__(self, xml=None, filename=None, **kwargs): + """ + Parameters + ---------- + xml : ElementTree + An ElementTree object already existing in python. + filename : str + File from which to read XML. If filename is not None, then the xml + keyword argument must be None. + """ Jp2kBox.__init__(self, id='xml ', longname='XML') + if filename is not None and xml is not None: + msg = "Only one of either filename or xml should be provided." + raise IOError(msg) + if filename is not None: + self.xml = ET.parse(filename) + else: + self.xml = xml self.__dict__.update(**kwargs) def __str__(self): @@ -1553,7 +1569,11 @@ class XMLBox(Jp2kBox): def _write(self, f): """Write an XML box to file. """ - buffer = ET.tostring(self.xml, encoding='utf-8') + try: + buffer = ET.tostring(self.xml, encoding='utf-8') + except AttributeError: + buffer = ET.tostring(self.xml.getroot(), encoding='utf-8') + f.write(struct.pack('>I', len(buffer) + 8)) f.write(self.id.encode()) f.write(buffer) diff --git a/glymur/test/test_jp2box.py b/glymur/test/test_jp2box.py index bf34347..32e95a6 100644 --- a/glymur/test/test_jp2box.py +++ b/glymur/test/test_jp2box.py @@ -371,6 +371,60 @@ class TestJp2Boxes(unittest.TestCase): jp2 = Jp2k(tfile.name) self.assertEqual(jp2.box[3].id, 'xml ') + def test_xml_from_file(self): + raw_xml = b""" + + + 1 + 2008 + 141100 + + + + + 4 + 2011 + 59900 + + + + 68 + 2011 + 13600 + + + + """ + with tempfile.NamedTemporaryFile(suffix=".xml") as tfile: + tfile.write(raw_xml) + tfile.flush() + + j2k = Jp2k(self.raw_codestream) + c = j2k.get_codestream() + height = c.segment[1].Ysiz + width = c.segment[1].Xsiz + num_components = len(c.segment[1].XRsiz) + + jP = JPEG2000SignatureBox() + ftyp = FileTypeBox() + jp2h = JP2HeaderBox() + jp2c = ContiguousCodestreamBox() + ihdr = ImageHeaderBox(height=height, width=width, + num_components=num_components) + colr = ColourSpecificationBox(colorspace=glymur.core.SRGB) + jp2h.box = [ihdr, colr] + + xmlb = glymur.jp2box.XMLBox(filename=tfile.name) + boxes = [jP, ftyp, jp2h, xmlb, jp2c] + with tempfile.NamedTemporaryFile(suffix=".jp2") as tfile: + j2k.wrap(tfile.name, boxes=boxes) + jp2 = Jp2k(tfile.name) + + output_boxes = [box.id for box in jp2.box] + self.assertEqual(output_boxes, ['jP ', 'ftyp', 'jp2h', 'xml ', + 'jp2c']) + self.assertIsNotNone(jp2.box[3].xml) + if __name__ == "__main__": unittest.main()