调整大小并保存 NSImage?
我有一个 NSImageView,我从 NSOpenPanel 获取图像。效果很好。
现在,我怎样才能将 NSImage 的大小减半,并将其以相同的格式保存在与原始文件相同的目录中?
如果您能提供任何帮助,我将不胜感激,谢谢。
I have an NSImageView which I get an image for from an NSOpenPanel. That works great.
Now, how can I take that NSImage, half its size and save it as the same format in the same directory as the original as well?
If you can help at all with anything I'd appreciate it, thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
检查 Matt Gemmell 的 ImageCrop 示例项目:
http://mattgemmell.com/source/
很好的示例如何调整大小/裁剪图像。
最后,您可以使用类似的方法来保存结果(脏样本):
Check the ImageCrop sample project from Matt Gemmell:
http://mattgemmell.com/source/
Nice example how to resize / crop images.
Finally you can use something like this to save the result (dirty sample):
由于 NSImage 对象是不可变的,您必须:
肯定还有其他选择,但这是我想到的第一个选择。
Since NSImage objects are immutable you will have to:
There are definitely other options, but this is the first one that came to mind.
这是一个具体的实现
请记住,这是基于像素的,使用 HiDPI 必须考虑缩放,很容易获得:
Here is a specific implementation
Keep in mind that this is pixel based, with HiDPI the scaling must be taken into account, it is simple to obtain :
苹果有缩小和保存图像的源代码在这里找到
http://developer.apple.com/library/mac/ #samplecode/Reducer/Introduction/Intro.html
Apple has source code for downscaling and saving images found here
http://developer.apple.com/library/mac/#samplecode/Reducer/Introduction/Intro.html
这是一些比其他答案更广泛地使用 Core Graphics 的代码。它是根据Mark Thalman对此问题的回答中的提示制作的。
此代码根据目标图像宽度缩小
NSImage
。它有点令人讨厌,但作为一个额外的示例仍然很有用,用于记录如何在CGContext
中绘制NSImage
以及如何编写CGBitmapContext
的内容和 CGImage 到一个文件中。您可能需要添加额外的错误检查。我的用例不需要它。
Here is some code that makes a more extensive use of Core Graphics than other answers. It's made according to hints in Mark Thalman's answer to this question.
This code downscales an
NSImage
based on a target image width. It's somewhat nasty, but still useful as an extra sample for documenting how to draw anNSImage
in aCGContext
, and how to write contents ofCGBitmapContext
andCGImage
into a file.You may want to add extra error checking. I didn't need it for my use case.
调整图像大小
To resize image