Creating memory efficient thumbnails using an NSImageView (cocoa/OSX)

混江龙づ霸主 提交于 2019-12-07 20:01:45

问题


I am creating small NSImageViews (32x32 pixels) from large images often 512x512 or even 4096 x 2048 for an extreme test case. My problem is that with my extreme test case, my applicaiton memory footprint seems to go up by over 15MB when I display my thumbnail, this makes me think the NSImage is being stored in memory as a 4096x2048 instead of 32x32 and I was wondering if there is a way to avoid this. Here is the process I go through to create the NsImageView:

• First I create an NSImage using initByReferencingFile: (pointing to the 4096x2048 .png file)

• Next I initialize the NSImageView with a call to initWithFrame:

• Then I call setImage: to assign my NSImage to the NSImageView

• Finally I set the NSImageView to NSScaleProportionally

I clearly do nothing to force the NSImage to size down to 32x32 but I have had trouble finding a good way to handle this.


回答1:


You can simply create a new 32x32 NSImage from the original and then release the original image.

First, create the 32x32 image:

NSImage *smallImage = [[NSImage alloc]initWithSize:NSMakeSize(32, 32)];

Then, lock focus on the image and draw the original on to it:

NSSize originalSize = [originalImage size];
NSRect fromRect = NSMakeRect(0, 0, originalSize.width, originalSize.height);
[smallImage lockFocus];
[originalImage drawInRect:NSMakeRect(0, 0, 32, 32) fromRect:fromRect operation:NSCompositeCopy fraction:1.0f];
[smallImage unlockFocus];

Then you may do as you please with the smaller image:

[imageView setImage:smallImage];

Remember to release!

[originalImage release];
[smallImage release];


来源:https://stackoverflow.com/questions/7562231/creating-memory-efficient-thumbnails-using-an-nsimageview-cocoa-osx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!