3

Since MonoMac doesnt have own class Bitmap, i need the best ways to convert image from Bitmap to NSImage. Current my way is:

byte[] bytes = SomeFuncReturnsBytesofBitmap();
NSData imageData = NSData.FromArray(bytes);
NSImage image = new NSImage(imageData);
imageView.Image = image;
Alexander
  • 431
  • 2
  • 5
  • 19

2 Answers2

4

From: 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));
    }

EDIT:

And to convert from an NSImage to Image

 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());
        }
    }
Herman Schoenfeld
  • 8,464
  • 4
  • 38
  • 49
0

With NSImage.FromStream Herman's solution can be simplified. I assume it wasn't available when the question was posted.

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);
    }
}
Paul B.
  • 2,394
  • 27
  • 47