2012-11-09 45 views
3

由於MonoMac沒有自己的類位圖,我需要將圖像從位圖轉換爲NSImage的最佳方法。 目前我的方法是:MonoMac:將位圖轉換爲NSImage的最佳方法

byte[] bytes = SomeFuncReturnsBytesofBitmap(); 
NSData imageData = NSData.FromArray(bytes); 
NSImage image = new NSImage(imageData); 
imageView.Image = image; 

回答

4

來源:http://lists.ximian.com/pipermail/mono-osx/2011-July/004436.html

public static NSImage ToNSImage(this Image img) { 
     System.IO.MemoryStream s = new System.IO.MemoryStream(); 
     img.Save(s, System.Drawing.Imaging.ImageFormat.Png); 
     byte[] b = s.ToArray(); 
     CGDataProvider dp = new CGDataProvider(b,0,(int)s.Length); 
     s.Flush(); 
     s.Close(); 
     CGImage img2 = CGImage.FromPNG(dp,null,false,CGColorRenderingIntent.Default); 
     return new NSImage(img2, new SizeF(img2.Width,img2.Height)); 
    } 

編輯:

,並從一個NSImage中轉換爲圖像

public static Image ToImage(this NSImage img) { 
     using (var imageData = img.AsTiff()) { 
      var imgRep = NSBitmapImageRep.ImageRepFromData(imageData) as NSBitmapImageRep; 
      var imageProps = new NSDictionary(); 
      var data = imgRep.RepresentationUsingTypeProperties(NSBitmapImageFileType.Png, imageProps); 
      return Image.FromStream(data.AsStream()); 
     } 
    } 
0

隨着NSImage.FromStream Herman的解決方案可簡化。我認爲這個問題發佈時不可用。

public static NSImage ToNSImage(this Image img) { 
    using (var s = new System.IO.MemoryStream()) { 
     img.Save(s, System.Drawing.Imaging.ImageFormat.Png); 
     s.Seek(0, System.IO.SeekOrigin.Begin); 
     return NSImage.FromStream(s); 
    } 
} 
相關問題