PresentationCore.dll System.Windows.Media.Imaging BitmapSource.create()返回CachedBitmap

时间:2014-06-03 02:46:18

标签: c# wpf

当我传递从文件读取的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);
}

第二个函数的结果是encoder.Frames.Add EncodeImageFromBitmapSource行的运行时错误:

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()会返回两个不同的例子?

1 个答案:

答案 0 :(得分:1)

encoder.Frames.Add((BitmapFrame)theSource);

bitmapsource类似乎不能只转换为bitmapFrame类型 。(BitmapFrame)theSource 似乎会抛出异常。 试试

BitmapFrame.Create(theSource)

价:http://msdn.microsoft.com/en-us/library/ms615993(v=vs.110).aspx