gpt4 book ai didi

wpf - FileFormatException 与 BitmapSource.CopyPixels 引发的内部 COMException

转载 作者:行者123 更新时间:2023-12-04 06:17:25 29 4
gpt4 key购买 nike

我有以下代码:

BitmapSource bitmap = _bitmapSource;

if (_bitmapSource.Format != PixelFormats.Bgra32)
bitmap = new FormatConvertedBitmap(_bitmapSource, PixelFormats.Bgra32, null, 0);

int bytesPerPixel = (bitmap.Format.BitsPerPixel + 7) / 8;
int pixelWidth = bitmap.PixelWidth;
int pixelHeight = bitmap.PixelHeight;
int stride = bytesPerPixel * pixelWidth;
int pixelCount = pixelWidth * pixelHeight;
var pixelBytes = new byte[pixelCount * bytesPerPixel];

bitmap.CopyPixels(pixelBytes, stride, 0);

...

}

NUnit 测试执行此代码,该代码在到达 bitmap.CopyPixels 时抛出:
System.IO.FileFormatException : The image decoder cannot decode the image. The image might be corrupted.
----> System.Runtime.InteropServices.COMException : Exception from HRESULT: 0x88982F60

at System.Windows.Media.Imaging.BitmapSource.CriticalCopyPixels(Int32Rect sourceRect, IntPtr buffer, Int32 bufferSize, Int32 stride)
at System.Windows.Media.Imaging.BitmapSource.CriticalCopyPixels(Int32Rect sourceRect, Array pixels, Int32 stride, Int32 offset)
at System.Windows.Media.Imaging.BitmapSource.CopyPixels(Int32Rect sourceRect, Array pixels, Int32 stride, Int32 offset)
at System.Windows.Media.Imaging.BitmapSource.CopyPixels(Array pixels, Int32 stride, Int32 offset)

但是图像没有损坏(其他测试使用相同的文件没有问题)并且奇怪的是如果我在 bitmap.CopyPixels 设置断点并在调试器中中断然后继续,不会抛出异常。

任何人都可以阐明可能导致我错误的原因吗?

最佳答案

我已经解决了这个问题,很简单。
_bitmapSource之前是使用 FileStream 创建的,如下所示:

using(var f = new FileStream(imagePath,FileMode.Open,FileAccess.Read){
BitmapSource bitmap = BitmapFrame.Create(f);
}
CallToCodeInQuestion(bitmap);

BitmapFrame.Create 的文档中它说

The bitmapStream can be closed after the frame is created only when the OnLoad cache option is used. The default OnDemand cache option retains the stream until the frame is needed. Use the Create(Stream, BitmapCreateOptions, BitmapCacheOption) method to specify create and cache options.



所以我需要这样做:
using(var f = new FileStream(imagePath, FileMode.Open, FileAccess.Read){
BitmapSource bitmap = BitmapFrame.Create(
f,
BitmapCreateOptions.None,
BitmapCacheOptions.OnLoad);
}//FileStream has been closed.
CallToCodeInQuestion(bitmap);

我的 NUnit 测试现在通过了。

关于wpf - FileFormatException 与 BitmapSource.CopyPixels 引发的内部 COMException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7060817/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com