BitmapSource到BitmapImage

时间:2011-03-17 11:16:38

标签: c# .net wpf bitmapimage bitmapsource

我需要将Clipboard.GetImage()(a BitmapSource)的内容解析为BitmapImage。 有谁知道怎么做?

2 个答案:

答案 0 :(得分:32)

我找到了一个干净的解决方案:

BitmapSource bitmapSource = Clipboard.GetImage();

JpegBitmapEncoder encoder = new JpegBitmapEncoder();
MemoryStream memoryStream = new MemoryStream();
BitmapImage bImg = new BitmapImage();

encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
encoder.Save(memoryStream);

memoryStream.Position = 0;
bImg.BeginInit();
bImg.StreamSource = memoryStream;
bImg.EndInit();

memoryStream.Close();

return bImg;

答案 1 :(得分:2)

using System.IO; // namespace for  using MemoryStream

private static byte[] ReadImageMemory()
{
    BitmapSource bitmapSource = BitmapConversion.ToBitmapSource(Clipboard.GetImage());
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    MemoryStream memoryStream = new MemoryStream();
    encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
    encoder.Save(memoryStream);
    return memoryStream.GetBuffer();
}

// and calling by this example........
byte[] buffer = ReadImageMemory();