从图像中获取元数据c#

本文关键字:元数据 获取 图像 | 更新日期: 2023-09-27 18:05:16

我正在尝试将图像导入到我的WPF应用程序中,并在单击保存按钮后将图像及其元数据保存到不同的位置。

我现在有:

BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile;
BitmapMetadata importedMetaData = new BitmapMetadata("jpg");
using (Stream sourceStream = File.Open(fileName, FileMode.Open, FileAccess.Read))
{
    BitmapDecoder sourceDecoder = BitmapDecoder.Create(sourceStream, createOptions, BitmapCacheOption.None);
    // Check source is has valid frames 
    if (sourceDecoder.Frames[0] != null && sourceDecoder.Frames[0].Metadata != null)
    {
        sourceDecoder.Frames[0].Metadata.Freeze();
        // Get a clone copy of the metadata
        BitmapMetadata sourceMetadata = sourceDecoder.Frames[0].Metadata.Clone() as BitmapMetadata;
        importedMetaData = sourceMetadata;
    }
}
if (!Directory.Exists(Settings.LocalPhotoDirectory))
{
    Directory.CreateDirectory(Settings.LocalPhotoDirectory);
}
string photoPath = Path.Combine(Settings.LocalPhotoDirectory, this.BasicTags.ElementAt(8).Value.ToString());
if (!Directory.Exists(photoPath))
{
    Directory.CreateDirectory(photoPath);
}
string localfileName = Path.Combine(photoPath, PhotoId.ToString() + ".jpg");           
string fileName = Path.Combine(this.Settings.QueueFolder, PhotoId.ToString() + ".jpg");
using (FileStream stream = new FileStream(fileName, FileMode.Create))
{
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.QualityLevel = this.Settings.ImageQuality;
    encoder.Frames.Add(BitmapFrame.Create(Photo, null, importedMetaData, null));
    encoder.Save(stream);
}

,其中Photo是一个BitmapSource, fileName是照片的文件名。但是我的代码总是在encoder.Save lin处崩溃。出现以下错误:

类型为"System.Runtime.InteropServices"的未处理异常。COMException' occurred in PresentationCore.dll

附加信息:句柄无效。(Exception from HRESULT: 0x80070006 (E_HANDLE))

当我读到你必须使用STA线程访问BitmapMetadata类时,整个方法正在作为STA线程运行。但还是没有运气。我做错了什么?

从图像中获取元数据c#

不,你不使用BitmapCacheOption.OnLoad

你只需要不使用BitmapCacheOption.None.

  • 默认:将整个图像缓存到内存中。这是默认值。
  • :不创建内存存储。所有对图像的请求都由图像文件直接填充。
  • OnDemand:仅为请求的数据创建内存存储。第一个请求直接加载图像;随后的请求是
  • OnLoad:在加载时将整个图像缓存到内存中。所有对图像数据的请求都从内存存储中填充。

基本上你可以用

BitmapDecoder sourceDecoder = BitmapDecoder.Create(sourceStream, createOptions, BitmapCacheOption.Default);

关于BitmapCacheOption的更多信息

我找到问题了。问题出在

这行
BitmapDecoder sourceDecoder = BitmapDecoder.Create(sourceStream, createOptions, BitmapCacheOption.None);

如果你把它改成

BitmapDecoder sourceDecoder = BitmapDecoder.Create(sourceStream, createOptions, BitmapCacheOption.OnLoad);

不知道为什么?也许有人能解释一下?