Search code examples
iphoneiosuiimagedpi

convert any uploaded image in 72 DPI


In my application i m using upload image functionality and i want to convert uploaded image in 72 DPI if image is with more or less DPI.

can we do it with using cgimagecreate

Please suggest me.

Thanks.


Solution

  • We can get image with 72 DPI with below method, actually we need to just get new image from context as below.

    -(UIImage *)resizeImageFor72DPI:(UIImage*)image newSize:(CGSize)newSize
    {
    CGRect newRect= CGRectZero;
    
    if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]
        && [[UIScreen mainScreen] scale] == 2.0)
    {
        //For retina image
        newSize=CGSizeMake(newSize.width/2.0,newSize.height/2.0);
    }
    newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
    
    CGImageRef imageRef = image.CGImage;
    
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    // Set the quality level to use when rescaling
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
    
    CGContextConcatCTM(context, flipVertical);
    // Draw into the context; this scales the image
    CGContextDrawImage(context, newRect, imageRef);
    
    // Get the resized image from the context and a UIImage
    CGImageRef newImageRef = CGBitmapContextCreateImage(context);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    
    CGImageRelease(newImageRef);
    UIGraphicsEndImageContext();
    
    return newImage;
    }