MonoMac:将位图转换为NSImage的最佳方法

3

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

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

4

来源: http://lists.ximian.com/pipermail/mono-osx/2011年7月/004436.html

这是一封关于在Mac OS X上使用Mono框架的电子邮件。
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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接