我有一个1600x1600 1.2MB的图像,其大小调整为320x320缩小到404KB.我需要进一步减少字节大小而不减少图像宽高比.
目前我正在使用 - TIFFRepresentationUsingCompression:factor:NSImage方法NSTIFFCompressionJPEG和因素似乎不影响图像大小/质量.
我怎么解决?
马尔科
如果您需要压缩并且不介意丢失图像质量,请将文件另存为JPEG.为此,您需要NSBitmapImageRep从图像中获取一个,然后获得JPEG表示:
//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];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4223 次 |
| 最近记录: |