现在我正试图从jpg图像中获取图像类。我已经尝试使用BitmapSource链接在这里。
错误不是英文,但意思是"图像标题被破坏了"。所以,这是不可能解码的。"其他格式如gif、png、bmp没有问题。只有JPG格式面临这个问题。
& lt;序列>Zip Archive文件(jpg文件在此文件中)-> unzip library -> MemoryStream(jpg文件)-> BitmapSource
imageSource.BeginInit();
imageSource.StreamSource = memoryStream;
imageSource.EndInit();
此代码产生错误。
我认为原因是内存流有jpg的原始二进制文件,它不是位图格式。因此,BitmapSource不能将此内存流数据识别为位图图像。
我该如何解决这个问题?我的目标是输入:"ZIP文件(jpg格式)"->输出:图像类
谢谢!
& lt;我的代码>
using (MemoryStream _reader = new MemoryStream())
{
reader.WriteEntryTo(_reader); // <- input jpg_data to _reader
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = _reader;
bitmap.EndInit();
bitmap.Freeze();
Image tmpImg = new Image();
tmpImg.Source = bitmap;
}
写完后倒带。虽然显然只有JpegBitmapDecoder受到源流的Position
的影响,但您通常应该对所有类型的位图流执行此操作。
var bitmap = new BitmapImage();
using (var stream = new MemoryStream())
{
reader.WriteEntryTo(stream);
stream.Position = 0; // here
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
bitmap.Freeze();
}
var tmpImg = new Image { Source = bitmap };
如果你不关心你的图片的来源是BitmapImage
还是BitmapFrame
,你可以把你的代码简化成这样:
BitmapSource bitmap;
using (var stream = new MemoryStream())
{
reader.WriteEntryTo(stream);
stream.Position = 0;
bitmap = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
var tmpImg = new Image { Source = bitmap };