Reading and Writing JPG Metadata with .NET 3

From IronPython Cookbook

From John Udell.

This example reads and writes tags (using XMP metadata) in JPG images.

You need .NET 3 installed to use this example.

It uses the JpegBitmapDecoder class from the System.Windows.Media.Imaging namespace.


import clr
clr.AddReference("PresentationCore")
from System.IO import FileStream, FileMode, FileAccess, FileShare
from System.Windows.Media.Imaging import (
    JpegBitmapDecoder, BitmapCreateOptions,
    BitmapCacheOption
)

def ReadFirstTag(jpg):
    f = FileStream(jpg, FileMode.Open)
    decoder = JpegBitmapDecoder(f, BitmapCreateOptions.PreservePixelFormat,
         BitmapCacheOption.Default)
    frame = decoder.Frames[0]
    metadata = frame.Metadata
    f.Close()
    return metadata.GetQuery("/xmp/dc:subject/{int=0}")


def WriteFirstTag(jpg, tag):
    f = FileStream(jpg,FileMode.Open, FileAccess.ReadWrite,
        FileShare.ReadWrite)
    decoder = JpegBitmapDecoder(f, BitmapCreateOptions.PreservePixelFormat,
        BitmapCacheOption.Default)
    frame = decoder.Frames[0]
    writer = frame.CreateInPlaceBitmapMetadataWriter()
    try:
        writer.SetQuery("/xmp/dc:subject/{int=0}",tag)
        writer.TrySave()
    except:
        print "cannot save metadata"
    f.Close()
    writer.GetQuery("/xmp/dc:subject/{int=0}")


print ReadFirstTag('yellowflower.jpg')
WriteFirstTag('yellowflower.jpg','iris')
print ReadFirstTag('yellowflower.jpg')

The output of this script is:

flower
iris

So the tag of the image has been changed.

Back to Contents.

TOOLBOX
LANGUAGES