JpegBitmapEncoder.Save() throws exception when writing image with metadata to MemoryStream

China☆狼群 提交于 2019-12-06 11:14:57

In case someone will encounter same issue, here is the solution:

If you try to .Save() jpeg from main application thread, add [STAThread] before Main().

If not, call .SetApartmentState(ApartmentState.STA) for the thread calling JpegBitmapEncoder.Save()

WinXP and WinVista versions of windowscodecs.dll are not reenterable, so if you will use default MTA model (it is default since .NET framework 2.0) for threads calling JpegBitmapEncoder.Save() function, it can behave strangely and throw described exception. Win7 version of windowscodecs.dll does not have this issue.

I ran your code without modifications and it didn't throw an error. I even tried saving the modified data to disk and the image itself was uncorrupted.

string filename = "e:\\a.jpg";
        MemoryStream s;
        s = SetTagsInMemory(filename, "test title");
        FileStream fs = new FileStream("e:\\b.jpg", FileMode.CreateNew, FileAccess.ReadWrite);
        BinaryWriter sw = new BinaryWriter(fs);
        s.Seek(0, SeekOrigin.Begin);
        while (s.Position < s.Length)
       {
            byte[] data = new byte[4096];
            s.Read(data, 0, data.Length);
            sw.Write(data);
       }

        sw.Flush();
        sw.Close();
        fs.Close();

Other than what I added below s = SetTagsInMemory(...) to write to disk, the rest of your code is unmodifed.

Edit: oh and the metadeta definatly ended up in the new file, previous one didn't have any metadata from what I could see.

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