将元数据写入jpg和png

tho*_*asb 6 c# image

我需要为上传的图像添加元数据标签(描述).

我找到了这个答案:https://stackoverflow.com/a/1764913/6776适用于JPG文件,但不适用于PNG.

private string Tag = "test meta data";

private static Stream TagImage(Stream input, string type)
{
    bool isJpg = type.EndsWith("jpg", StringComparison.InvariantCultureIgnoreCase) || type.EndsWith("jpeg", StringComparison.InvariantCultureIgnoreCase);
    bool isPng = type.EndsWith("png", StringComparison.InvariantCultureIgnoreCase);

    BitmapDecoder decoder = null;

    if (isJpg)
    {
        decoder = new JpegBitmapDecoder(input, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
    }
    else if (isPng)
    {
        decoder = new PngBitmapDecoder(input, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
    }
    else
    {
        return input;
    }

    // modify the metadata
    BitmapFrame bitmapFrame = decoder.Frames[0];
    BitmapMetadata metaData = (BitmapMetadata)bitmapFrame.Metadata.Clone();
    metaData.Subject = Tag;
    metaData.Comment = Tag;
    metaData.Title = Tag;

    // get an encoder to create a new jpg file with the new metadata.      
    BitmapEncoder encoder = null;
    if (isJpg)
    {
        encoder = new JpegBitmapEncoder();
    }
    else if (isPng)
    {
        encoder = new PngBitmapEncoder();
    }

    encoder.Frames.Add(BitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metaData, bitmapFrame.ColorContexts));

    // Save the new image 
    Stream output = new MemoryStream();
    encoder.Save(output);

    output.Seek(0, SeekOrigin.Begin);

    return output;
}
Run Code Online (Sandbox Code Playgroud)

当我上传一个jpg时,它工作得很好,但是metaData.Subject = Tag在行上有一个png ,它会抛出一个System.NotSupportedException(这个编解码器不支持指定的属性).

更新

看来我必须使用基于图像格式的不同方法:

if (isJpg)
{
    metaData.SetQuery("/app1/ifd/exif:{uint=270}", Tag);
}
else
{
    metaData.SetQuery("/tEXt/{str=Description}", Tag);
}
Run Code Online (Sandbox Code Playgroud)

根据可用格式的查询,第一个应该适用于两种格式.第二个也不起作用(它在图像中创建元数据但不保存其值).

如果我尝试使用/app1/ifd/exifPNG 的第一个方法(),在第一encoder.Save行我得到一个不支持的异常,"没有适合的成像组件".

小智 -4

PNG 格式不支持元数据:(

XMP可以,这在带有 EXIF 元数据的 JPEG 和 PNG 之间进行转换时可能会有所帮助。