使用Cocoa减少图像字节大小 [英] Reduce image bytes size with Cocoa

查看:134
本文介绍了使用Cocoa减少图像字节大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个1600x1600 1.2MB图像,该图像的大小调整为320x320,缩小为404KB. 我需要走得更远,并减少字节的大小,而又不减少图像的长宽比.

I have a 1600x1600 1.2MB image which resized to 320x320 shrinks to 404KB. I need to go further and reduce the bytes size without reducing the image aspect size.

当前,我正在将-TIFFRepresentationUsingCompression:factor: NSImage方法与NSTIFFCompressionJPEG一起使用,并且该因子似乎并不影响图像的大小/质量.

Currently i'm using the -TIFFRepresentationUsingCompression:factor: NSImage method with NSTIFFCompressionJPEG and factor that doesn't seem to influence the image size/quality.

我该如何解决?

马可

推荐答案

如果您需要压缩并且不介意降低图像质量,请将该文件另存为JPEG.为此,您需要从图像中获取NSBitmapImageRep,然后获取JPEG表示形式:

If you need compression and you don't mind losing image quality then save the file as a JPEG. To do this, you need to get an NSBitmapImageRep from your image and then get a JPEG representation:

//yourImage is an NSImage object

NSBitmapImageRep* myBitmapImageRep;

if(useActualSize)
{
    //this will produce an image the full size of the NSImage's backing bitmap, which may not be what you want
    myBitmapImageRep = [NSBitmapImageRep imageRepWithData: [yourImage TIFFRepresentation]];
}
else
{
    //this will get a bitmap from the image at 1 point == 1 pixel, which is probably what you want
    NSSize imageSize = [yourImage size];
    [yourImage lockFocus];
    NSRect imageRect = NSMakeRect(0, 0, imageSize.width, imageSize.height);
    myBitmapImageRep = [[[NSBitmapImageRep alloc] initWithFocusedViewRect:imageRect] autorelease];
    [yourImage unlockFocus];
}

CGFloat imageCompression = 0.7; //between 0 and 1; 1 is maximum quality, 0 is maximum compression

// set up the options for creating a JPEG
NSDictionary* jpegOptions = [NSDictionary dictionaryWithObjectsAndKeys:
                [NSNumber numberWithDouble:imageCompression], NSImageCompressionFactor,
                [NSNumber numberWithBool:NO], NSImageProgressive,
                nil];

// get the JPEG encoded data
NSData* jpegData = [myBitmapImageRep representationUsingType:NSJPEGFileType properties:jpegOptions];
//write it to disk
[jpegData writeToFile:[NSHomeDirectory() stringByAppendingPathComponent:@"foo.jpg"] atomically:YES];

这篇关于使用Cocoa减少图像字节大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆