Read image XMP data in Python

落花浮王杯 提交于 2019-11-28 21:22:38
dirac3000

Well, I was looking for something similar, then I came across the PHP equivalent question and I translated the anwer to Python:

f = 'example.jpg'
fd = open(f)
d= fd.read()
xmp_start = d.find('<x:xmpmeta')
xmp_end = d.find('</x:xmpmeta')
xmp_str = d[xmp_start:xmp_end+12]
print(xmp_str)

you can then convert xmp_str and parse it with an XML API.

XMP metadata can be found in applist.

from PIL import Image
with Image.open(filename) as im:
    for segment, content in im.applist:
        marker, body = content.split('\x00', 1)
        if segment == 'APP1' and marker == 'http://ns.adobe.com/xap/1.0/':
            # parse the XML string with any method you like
            print body

I am also interested to know if there is a 'proper' easy way to do this.

In the mean time, I've implemented reading XMP packets using pure Python in PyAVM. The relevant code is here. Maybe this would be useful to you?

with open( imgFileName, "rb") as fin:
    img = fin.read()
imgAsString=str(img)
xmp_start = imgAsString.find('<x:xmpmeta')
xmp_end = imgAsString.find('</x:xmpmeta')
if xmp_start != xmp_end:
    xmpString = imgAsString[xmp_start:xmp_end+12]

xmpAsXML = BeautifulSoup( xmpString )
print(xmpAsXML.prettify())

Or you can use the Python XMP Toolkit

A search through the PIL source (1.1.7) tells me that it can recognize XMP information in Tiff files, but I cannot find any evidence of a documented or undocumented API for working with XMP information using PIL at the application level.

From the CHANGES file included in the source:

+ Support for preserving ICC profiles (by Florian Böch via Tim Hatch).

  Florian writes:

  It's a beta, so still needs some testing, but should allow you to:
  - retain embedded ICC profiles when saving from/to JPEG, PNG, TIFF.
     Existing code doesn't need to be changed.
  - access embedded profiles in JPEG, PNG, PSD, TIFF.

  It also includes patches for TIFF to retain IPTC, Photoshop and XMP
  metadata when saving as TIFF again, read/write TIFF resolution
  information correctly, and to correct inverted CMYK JPEG files.

So the support for XMP is limited to TIFF, and only allows XMP information to be retained when a TIFF image is loaded, possibly changed, and saved. The application cannot access or create XMP data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!