15
我需要解析Clipboard.GetImage()
(a BitmapSource
)的內容爲BitmapImage
。 有誰知道這是怎麼做到的?BitmapSource to BitmapImage
我需要解析Clipboard.GetImage()
(a BitmapSource
)的內容爲BitmapImage
。 有誰知道這是怎麼做到的?BitmapSource to BitmapImage
我已經找到了一個乾淨的解決方案,它的工作原理:
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;
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();
是否有必要使用'=新的MemoryStream bImg.StreamSource(memoryStream.ToArray());'的',而不是bImg.StreamSource = memoryStream;'並移除'memoryStream.Close(); ' – Elmo 2012-01-07 15:28:55
您應該在最後添加bImg.Freeze()以允許多線程調用,否則會完美無缺。 – m1k4 2013-08-08 13:00:11
@ Don'tForgettoUpvote:對我來說''bImg.StreamSource = new MemoryStream(memoryStream.ToArray());'是必要的,否則它會拋出異常。 – dotNET 2014-01-11 16:22:43