How to get dpi/ppi of UIImage?

前端 未结 3 831
清酒与你
清酒与你 2021-01-06 01:56

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.

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-06 02:43

    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

提交回复
热议问题