Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change image resolution in objective-c

I need to change the resolution of the existing image in objective-c just like Apple's Preview application Tools->Adjust Size...->Resolution.

Please let me know the possible solutions.

like image 464
AmitSri Avatar asked Nov 08 '11 09:11

AmitSri


1 Answers

Here's a great sample I've used - http://weblog.scifihifi.com/2005/06/25/how-to-resize-an-nsimage/

From that sample, you can write resizedData to the file - and this will be a resized output in tiff format.

UPDATE:

here comes the NSImage category implementation, that allows to save NSImage instance with specified DPI:

@interface NSImage (DPIHelper)
- (void) saveAsImageType: (NSBitmapImageFileType) imageType withDPI: (CGFloat) dpiValue atPath: (NSString *) filePath;
@end

@implementation NSImage (DPIHelper)


- (void) saveAsImageType: (NSBitmapImageFileType) imageType withDPI: (CGFloat) dpiValue atPath: (NSString *) filePath
{
  NSBitmapImageRep *rep = [[self representations] objectAtIndex: 0];

  NSSize pointsSize = rep.size;
  NSSize pixelSize = NSMakeSize(rep.pixelsWide, rep.pixelsHigh);

  CGFloat currentDPI = ceilf((72.0f * pixelSize.width)/pointsSize.width);
  NSLog(@"current DPI %f", currentDPI);

  NSSize updatedPointsSize = pointsSize;

  updatedPointsSize.width = ceilf((72.0f * pixelSize.width)/dpiValue);
  updatedPointsSize.height = ceilf((72.0f * pixelSize.height)/dpiValue);

  [rep setSize:updatedPointsSize];

  NSData *data = [rep representationUsingType: imageType properties: nil];
  [data writeToFile: filePath atomically: NO];

}

@end

you can use it like this:

NSImage *theImage2 = [NSImage imageNamed:@"image.jpg"];
[theImage2 saveAsImageType:NSJPEGFileType withDPI: 36.0f atPath: @"/Users/<user-name>/image-updated.jpg"];
like image 169
Denis Avatar answered Sep 22 '22 08:09

Denis