views:

185

answers:

1

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.

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

How can i solve?

Marco

+3  A: 

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];
Rob Keniger
I don't mind image quality but isn't your code the same as -TIFFRepresentationUsingCompression:factor: method?
Marco
No. That method creates a TIFF file with internal JPEG compression. However, the docs state "JPEG compression in TIFF files is not supported, and factor is ignored." My code creates an actual JPEG file.
Rob Keniger
Thanks for picking up the missing `autorelease`, Peter, I copied that line from a category of mine in a GC project so in my case it's not necessary.
Rob Keniger