PresentationCore.dll System.Windows.Media.Imaging BitmapSour
本文关键字:Imaging BitmapSour Media Windows dll System PresentationCore | 更新日期: 2023-09-27 18:06:14
当我传递从文件读取的BitmapSource时,此代码可以完美地输出名为output2.tif的文件。
FileInfo fi = new FileInfo(@"C:'Users'Chris'Downloads'PdfVerificationTests.can_use_image_approval_mode.approved.tiff");
FileStream stream = fi.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
TiffBitmapDecoder decoder = new TiffBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.None);
EncodeImageFromBitmapSource(decoder.Frames[0]);
private void EncodeImageFromBitmapSource(BitmapSource theSource)
{
//Taken from MSDN
//http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapencoder(v=vs.110).aspx
FileStream stream = new FileStream("output2.tif", FileMode.Create);
TiffBitmapEncoder encoder = new TiffBitmapEncoder();
TextBlock myTextBlock = new TextBlock();
myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
encoder.Frames.Add((BitmapFrame)theSource);
encoder.Save(stream);
}
此代码引发错误
private void EncodeImageFromArray(byte[] theSource)
{
//Taken from Stack Overflow. Purported way to create a BitmapSource from a byte array
//http://stackoverflow.com/questions/15274699/create-a-bitmapimage-from-a-byte-array/15290190?noredirect=1#comment36991252_15290190
byte[] buffer = new byte[120000]; //changed from "..."
Buffer.BlockCopy(theSource, 0, buffer, 0, 120000); //added to populate the array from the parameter
var width = 400; // for example 100 changed to 400
var height = 300; // for example 100 changed to 300 (400*300*1 = 120000)
var dpiX = 96d;
var dpiY = 96d;
System.Windows.Media.PixelFormat pixelFormat = System.Windows.Media.PixelFormats.Gray8; // grayscale bitmap ambiguous PixelFormat reference changed
var bytesPerPixel = (pixelFormat.BitsPerPixel + 7) / 8; // == 1 in this example
var stride = bytesPerPixel * width; // == width in this example
BitmapSource bitmap = BitmapSource.Create(width, height, dpiX, dpiY, pixelFormat, null, buffer, stride);
//At this point, bitmap should be a BitmapSource??
EncodeImageFromBitmapSource(bitmap);
}
第二个函数的结果是EncodeImageFromBitmapSource
:的encoder.Frames.Add
行出现运行时错误
System.InvalidCastException was unhandled
HResult=-2147467262
Message=Unable to cast object of type 'System.Windows.Media.Imaging.CachedBitmap' to type 'System.Windows.Media.Imaging.BitmapFrame'.
那么,什么时候BitmapSource
不是BitmapSource
呢?当它显然是用BitmapSource.create()
创建的。BitmapSource.create()
创建的底层对象的类型为CachedBitmap
,返回被强制转换为BitmapSource
。当我在encoder.Frames.Add()
函数中使用BitmapSource时,它会抛出一个错误。我错过了什么?
这是另一个问题,但为什么BitmapSource.create()
在两个示例之间的使用方式不同?
encoder.Frames.Add((BitmapFrame)theSource);
位图源类型似乎不能直接转换为位图帧类型。(BitmapFrame(源似乎将抛出异常。尝试
BitmapFrame.Create(theSource)
参考编号:http://msdn.microsoft.com/en-us/library/ms615993(v=vs.110(.aspx