MonoMac:将Bitmap转换为NSImage的最佳方式

时间:2012-11-09 09:10:32

标签: bitmap nsimage monomac

由于Mono Mac没有自己的类Bitmap,我需要最好的方法将图像从Bitmap转换为UIImage。 目前我的方式是:

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

2 个答案:

答案 0 :(得分: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转换为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());
        }
    }

答案 1 :(得分: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);
    }
}