由于MonoMac没有自己的Bitmap类,我需要最好的方法将图像从Bitmap转换为NSImage。目前我的方法是:
byte[] bytes = SomeFuncReturnsBytesofBitmap();
NSData imageData = NSData.FromArray(bytes);
NSImage image = new NSImage(imageData);
imageView.Image = image;
来源: 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());
}
}
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);
}
}