2013-08-05 411 views
0

我正在开发一个控件,用户可以在其中设置图像,我希望这可以尽可能地方便用户 - 所以支持复制&粘贴,拖动&拖放。Image/ImageSource/Interop Image to bytearray

我有这部分使用IDataObjects工作,测试的FileDrop的fileformats,FileContents(例如从Outlook),和位图例如:

private void GetImageFromIDataObject(IDataObject myIDO) 
    { 
     string[] dataformats = myIDO.GetFormats(); 

     Boolean GotImage = false; 

     foreach (string df in dataformats) 
     { 
      if (df == DataFormats.FileDrop) 
      { 
       // code here 
      } 
      if (df == DataFormats.Bitmap) 
      { 
       // Source of my problem here... this gets & displays image but 
       // how do I then convert from here ? 
       ImageSource myIS = Utilities.MyImaging.ImageFromClipboardDib(); 
       ImgPerson.Source = myIS; 
      } 
     } 
    } 

的ImageFromClipboard代码是托马斯·莱维斯克在回答作为参考这太问题wpf InteropBitmap to bitmap

http://www.thomaslevesque.com/2009/02/05/wpf-paste-an-image-from-the-clipboard/

无论我如何获取图像到ImgPerson,这部分工作正常;图像很好地显示。

当用户按下保存时我需要将图像转换为bytearray并发送到WCF服务器,该服务器将保存到服务器 - 如在重建字节数组到图像并将其保存在文件夹中。

对于所有格式的拖动&拖放,复制&粘贴图像是某种形式的System.Windows.Media.Imaging.BitmapImage。

除了那些涉及使用托马斯代码的剪贴板变成System.Windows.Media.Imaging.BitmapFrameDecode。

如果我避免托马斯的代码和使用:

BitmapSource myBS = Clipboard.GetImage(); 
ImgPerson.Source = myBS; 

我得到一个System.Windows.Interop.InteropBitmap。

我不知道如何使用这些;让他们进入一个bytearray,所以我可以传递给WCF重建和保存到文件夹。

回答

0

我不能相信我没有看到这太问题,但这个基本上是一样的,我的问题:

WPF: System.Windows.Interop.InteropBitmap to System.Drawing.Bitmap

答案之中:

BitmapSource bmpSource = msg.ThumbnailSource as BitmapSource; 
MemoryStream ms = new MemoryStream(); 
BitmapEncoder encoder = new PngBitmapEncoder(); 
encoder.Frames.Add(BitmapFrame.Create(bmpSource)); 
encoder.Save(ms); 
ms.Seek(0, SeekOrigin.Begin); 


System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(ms); 

与Nitesh的答案类似,但关键性的是,它与一个内部操作位图一起工作。

0

尝试这段代码

public byte[] ImageToBytes(BitmapImage imgSource) 
    { 
     MemoryStream objMS = new MemoryStream();   
     PngBitmapEncoder encoder = new PngBitmapEncoder(); 
     encoder.Frames.Add(BitmapFrame.Create(imgSource)); 
     encoder.Save(objMS); 
     return objMS.GetBuffer(); 
    } 

您还可以使用JpegBitmapEncoderBmpBitmapEncoder根据您的要求。

byte[] arr = ImageToBytes(ImgPerson.Source as BitmapImage); 
+0

我以前试过BitmapImage myBI = ImgDriver.Source作为BitmapImage,这导致null;所以演员没有工作。我不能在明天之前测试你的答案,但是我怀疑这两个选项仍然会导致隐式演员无效? – andrew