简体   繁体   English

将NSImage写入文件

[英]Write NSImage to file

I have an NSImage from NSImage *myImage = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[outputView bounds]]; 我有一个NSImageNSImage *myImage = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[outputView bounds]]; and I need to save it to a file. 我需要将其保存到文件中 I havent been able to find anything about saving NSImage in any format. 我无法找到有关以任何格式保存NSImage的任何信息。 Has anyone done this? 有人这样做吗? Is it even possible? 可能吗?

Thanks 谢谢

The way you say you're making an NSImage doesn't make sense. 您说的制作NSImage的方式没有道理。 You show how to create an NSBitmapImageRep, not an NSImage. 您将展示如何创建NSBitmapImageRep而不是NSImage。

Before you save it to a file, you convert to NSData. 将其保存到文件之前,请转换为NSData。 There is an NSImage method to convert to TIFF data, and there is an NSBitmapImageRep method to convert to data in several formats. 有一个NSImage方法可以转换为TIFF数据,还有一个NSBitmapImageRep方法可以转换为多种格式的数据。

Having an NSBitmapImageRep (as JWWalker pointed out, that code doesn't create an NSImage instance), you can ask the image rep for a CGImage version of itself, and then create a CGImageDestination to write that image to a file. 拥有一个NSBitmapImageRep(如JWWalker所指出的那样,该代码不会创建NSImage实例),您可以向图像表示请求自身的CGImage版本,然后创建CGImageDestination将该图像写入文件。 This may be more efficient than obtaining a data object (which will hold the raster data in memory) and provides more options. 这可能比获得数据对象(将栅格数据保存在内存中)并提供更多选项更为有效。

If you're creating a snapshot of an actual view (as opposed to an image that you've locked focus on), then an alternative to creating a bitmap image rep would be to ask the view for PDF data of the desired rectangle . 如果要创建实际视图的快照(而不是锁定了焦点的图像),则创建位图图像表示的另一种方法是向视图请求所需矩形的PDF数据 This will be vector rather than raster (except where the view itself draws an image), which will scale more nicely to higher resolutions. 这将是矢量而不是栅格(除非视图本身绘制图像),栅格将更好地缩放至更高的分辨率。 You would then write that data to a file the same as you would any other data. 然后,您将与其他任何数据一样将数据写入文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM