2011-03-17 73 views

回答

29

我已經找到了一個乾淨的解決方案,它的工作原理:

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; 
+3

是否有必要使用'=新的MemoryStream bImg.StreamSource(memoryStream.ToArray());'的',而不是bImg.StreamSource = memoryStream;'並移除'memoryStream.Close(); ' – Elmo 2012-01-07 15:28:55

+2

您應該在最後添加bImg.Freeze()以允許多線程調用,否則會完美無缺。 – m1k4 2013-08-08 13:00:11

+1

@ Don'tForgettoUpvote:對我來說''bImg.StreamSource = new MemoryStream(memoryStream.ToArray());'是必要的,否則它會拋出異常。 – dotNET 2014-01-11 16:22:43

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();