Why PNG image got double size after taking screenshot of UIView?

343 Views Asked by At

I am able to take screenshot from UIView at iPhone 6 with below code: -

Here I have printed 2 logs. First gives me image size {375, 667} but after converting it to PNG format it gives me image size {750, 1334}.

I know that it's converting it for the retina display. Each point is represented by 2 pixels on the screen so the saved image is double the resolution.

But I need image size {375, 667} with PNG format.

- (UIImage *)imageWithView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, [UIScreen mainScreen].scale);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSLog(@"Image Size: %@", image);  // Image Size: <UIImage: 0x1700880c0>, {375, 667}

    NSData* imageData =  UIImagePNGRepresentation(image);
    UIImage* pngImage = [UIImage imageWithData:imageData];
    UIImageWriteToSavedPhotosAlbum(pngImage, nil, nil, nil);

    NSLog(@"PNG Image Size: %@", pngImage);  // PNG Image Size: <UIImage: 0x174087760>, {750, 1334}

    return image;
}


Big Image:- enter image description here

Small Image:-

enter image description here

2

There are 2 best solutions below

4
Imad Ali On

Change the scale to 1 instead of [UIScreen mainScreen].scale.

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 1);
3
Abdelahad Darwish On

just to not get a bad quality you can create an image with screen scale

but when you load you can use this

CGFloat screenScale = [UIScreen mainScreen].scale;
if (screenScale != img.scale) {
    img = [UIImage imageWithCGImage:img.CGImage scale:screenScale    orientation:img.imageOrientation];
}