本文介绍了使用元数据写入图像时,JpegBitmapEncoder.Save()引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建WPF桌面应用程序,以帮助我整理照片以发布到Facebook.这是我的代码,用于在添加了标题(EXIF + IPTC + XMP)的新位置创建照片副本:

I'm building a WPF desktop app to help me organize photos to post to Facebook. Here's my code for creating a copy of a photo at a new location with a caption (EXIF + IPTC + XMP) added:

    private void SaveImageAs(string currPath, string newPath, bool setCaption = false, string captionToSet = "")
    {
        System.IO.FileStream stream = new System.IO.FileStream(currPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        JpegBitmapDecoder decoder = new JpegBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None);
        BitmapFrame bitmapFrame = decoder.Frames[0];
        BitmapMetadata metadata = bitmapFrame.Metadata.Clone() as BitmapMetadata;
        stream.Close();

        if (setCaption)
        {
            // if we want to set the caption, do it in EXIF, IPTC, and XMP

            metadata.SetQuery("/app1/ifd/{uint=270}", captionToSet);
            metadata.SetQuery("/app13/irb/8bimiptc/iptc/Caption", captionToSet);
            metadata.SetQuery("/xmp/dc:description/x-default", captionToSet);
        }

        MemoryStream memstream = new MemoryStream();   // create temp storage in memory
        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bitmapFrame, bitmapFrame.Thumbnail, metadata, bitmapFrame.ColorContexts));
        encoder.Save(memstream);   // save in memory
        stream.Close();

        stream = new FileStream(newPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
        memstream.Seek(0, System.IO.SeekOrigin.Begin);    // go to stream start
        byte[] bytes = new byte[memstream.Length + 1];
        memstream.Read(bytes, 0, (int)memstream.Length);
        stream.Write(bytes, 0, bytes.Length);
        stream.Close();
        memstream.Close();
    }

运行该命令,我得到一个"COMException was unhanded"异常,突出显示了这一行:

Running that, I get a "COMException was unhandled" exception highlighting this line:

encoder.Save(memstream);

其他信息:句柄无效.(来自HRESULT的异常:0x80070006(E_HANDLE))

Additional information: The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))

我在此处看到了这可能是由于线程问题引起的,所以我没有从应用程序中直接调用SaveImageAs,而是添加了它,但无效:

I saw here that this could be due to a threading issue, so instead of directly calling SaveImageAs from the app, I added this, to no effect:

        private void _SaveImageAs(string currPath, string newPath, bool setCaption = false, string captionToSet = "")
    {
        Thread saveThread = new Thread(() => SaveImageAs(currPath, newPath, setCaption, captionToSet));
        saveThread.SetApartmentState(ApartmentState.STA);
        saveThread.IsBackground = false;
        saveThread.Start();
    }

我还尝试将MemoryStream换成FileStream,以创建本地临时文件-并没有任何改变:

I also tried swapping out the MemoryStream for a FileStream creating a local temp file-- that didn't change anything:

FileStream memstream = new FileStream(System.IO.Path.GetDirectoryName(newPath) + @"\" + "temp.jpg", System.IO.FileMode.OpenOrCreate);

有什么想法吗?

推荐答案

您的代码中有些错误.

  1. 必须将源流保持打开状态,直到将BitmapFrame写入目标流为止.

  1. The source stream has to be kept open until the BitmapFrame is written to the target stream.

来自BitmapDecoder的BitmapFrame的图像元数据是只读的.要修改元数据,您必须从原始的BitmapFrame中创建一个新的BitmapFrame.

Image metadata of a BitmapFrame from a BitmapDecoder is read-only. You have to create a new BitmapFrame from the original one when you want to modify metadata.

第三个查询似乎已损坏.异常显示找不到属性".

The third query seems to be broken. The exception says "Property cannot be found".

此代码对我有用:

public static void SaveImageAs(string sourcePath, string targetPath, string caption)
{
    using (var sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        var decoder = new JpegBitmapDecoder(sourceStream, BitmapCreateOptions.None, BitmapCacheOption.None);
        var frame = decoder.Frames[0];

        if (!string.IsNullOrWhiteSpace(caption))
        {
            frame = BitmapFrame.Create(frame);
            var metadata = (BitmapMetadata)frame.Metadata;

            metadata.SetQuery("/app1/ifd/{uint=270}", caption);
            metadata.SetQuery("/app13/irb/8bimiptc/iptc/Caption", caption);
            //metadata.SetQuery("/xmp/dc:description/x-default", caption);
        }

        var encoder = new JpegBitmapEncoder();
        encoder.Frames.Add(frame);

        using (var targetStream = new FileStream(targetPath, FileMode.Create))
        {
            encoder.Save(targetStream);
        }
    }
}

这篇关于使用元数据写入图像时,JpegBitmapEncoder.Save()引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 04:23