Search code examples
iosobjective-cuigraphicscontext

Resizing a photograph using UIGraphics but final image is slightly blurry


I am trying to resize an image using UIGraphics. The image is one taken with the camera, and I am using this code:

 CGSize origImageSize = photograph.size;

    //this saves as 140*140 for retina
    CGRect newRect = CGRectMake(0, 0, 70, 70);

    //scaling ratio
    float ratio = MAX(newRect.size.width/origImageSize.width, newRect.size.height/origImageSize.height);


    UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);


    CGRect projectRect;
    projectRect.size.width= ratio*origImageSize.width;
    projectRect.size.height=ratio*origImageSize.height;
    //center the image
    projectRect.origin.x= ((newRect.size.width-projectRect.size.width)/2);
    projectRect.origin.y=((newRect.size.height-projectRect.size.height)/2);
    [photograph drawInRect:projectRect];

    //get the image from the image context
    UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();

For some reason the final photo isn't as sharp, it's slightly blurry. Am I doing anything wrong here? Any pointers would be really appreciated. thanks


Solution

  • I assume you calculate rectangle properly. Then make sure you use integral rectangle. Non-integral values may cause sub pixel rendering.

    Run your projectRect through CGRectIntegral to get integral rectangle, then use it to render your image.

    projectRect = CGRectIntegral(projectRect);