How to get dpi/ppi of image in iOS? Maybe raw image file contains this information, so I can get ppi/dpi from NSData? Thank you.
Swift 5 solution: You can get the DPI information from the image metadata. imageData is of NSData type.
guard let imageSource = CGImageSourceCreateWithData(imageData, nil),
let metaData = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [String: Any],
let dpi = metaData["DPIWidth"] as? Int else {
return
}
print(dpi)
To extract DPI from an image stored in NSData, include Apple's ImageIO framework in your project and use the following:
#import <ImageIO/ImageIO.h>
// Set your NSData up
NSData *data = some image data
// Get the DPI of the image
CGImageSourceRef imageRef = CGImageSourceCreateWithData((__bridge CFDataRef)(data), NULL);
CFDictionaryRef imagePropertiesDict = CGImageSourceCopyPropertiesAtIndex(imageRef, 0, NULL);
NSString *dpiHeight = CFDictionaryGetValue(imagePropertiesDict, @"DPIHeight");
NSString *dpiWidth = CFDictionaryGetValue(imagePropertiesDict, @"DPIWidth");
Note that not all images contain DPI information. It may or may not be included in the image's metadata.
This answer is based upon Flar49's answer, which is correct, but enhanced to get the information directly from NSData. See http://iosdevelopertips.com/data-file-management/get-image-data-including-depth-color-model-dpi-and-more.html for more information.
Objective-C
Get image resolution:
CGFloat imageResolution = myImage.scale * 72.0f;
Create an image at 300dpi from a 'standard' UIImage ( 72 dpi ) :
UIImage *my300dpiImage = [UIImage imageWithCGImage:mySourceImage.CGImage scale:300.0f/72.0f orientation:UIImageOrientationUp] ;
Swift
Get resolution :
let imageResolution = myImage.scale * 72.0
Change image resolution :
// Just be sure source image is valid
if let source = mySourceImage, let cgSource = source.cgImage {
let my300dpiImage = UIImage(cgImage: cgSource, scale: 300.0 / 72.0, orientation: source.imageOrientation)
}
Note that I've added respect of the source image orientation in the swift example, and also note that changing a resolution from 72 to 300 dpi is leading to quality loss, since you don't have the picture details.
The big point is that resolution does not mean anything unless the image is rendered. Before that, you got the bits you got.. It's up to you to determine the final resolution, as seen by the viewer, by setting the destination rectangle size.
The resolution of the file, as fixed by the creator application, is not in the image data itself, but in the meta data. As explained in the previous answer, or at the address below:
How to get image metadata in ios