Search code examples
objective-ccocoaresolutionnsimage

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.


Solution

  • 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"];