繁体   English   中英

从图像中获取元数据c#

[英]Getting metadata from an image c#

我正在尝试将图像导入我的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);
}

其中PhotoBitmapSourcefileName是照片的文件名。 但我的代码一直在撞击encoder.Save 。保持林。 出现以下错误:

PresentationCore.dll中发生未处理的“System.Runtime.InteropServices.COMException”类型异常

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

整个方法作为STA线程运行,因为我读到你必须使用STA线程访问BitmapMetadata类。 但仍然没有运气。 我究竟做错了什么?

不,你不必使用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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM