【问题标题】:Why PNG image got double size after taking screenshot of UIView?为什么在截取 UIView 后 PNG 图像会变成两倍大小?
【发布时间】:2017-08-21 04:45:22
【问题描述】:

我可以使用以下代码在 iPhone 6 上从UIView 截屏:-

这里我打印了 2 个日志。首先给我图像大小{375, 667},但在将其转换为PNG格式后,它给我图像大小{750, 1334}

我知道它正在将其转换为视网膜显示。每个点在屏幕上由 2 个像素表示,因此保存的图像是分辨率的两倍。

但我需要具有 PNG 格式的图像大小 {375, 667}

- (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;
}


大图:-

小图:-

【问题讨论】:

标签: ios objective-c uiview uiimagepngrepresentation


【解决方案1】:

为了不让画质变差,您可以创建具有屏幕比例的图像

但是当你加载时你可以使用这个

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

【讨论】:

  • 感谢@Abdelahad Darwish。它在 NSLog 中给了我图像大小:{375, 667},但是当我使用 UIImageWriteToSavedPhotosAlbum 保存它时,它再次在照片(相机胶卷)中给我图像尺寸 {750, 1334}。请帮忙。我需要图像尺寸:{375, 667} 格式的 PNG 格式,图像质量很好。
  • 查看您的代码,您可以使用此压缩图像` UIImage* pngImage = [UIImage imageWithData:imageData scale:1];`
  • 我试过 UIImage* pngImage = [UIImage imageWithData:imageData scale:1];但它在照片(相机胶卷)中给出了相同的图像尺寸 {750, 1334}。
【解决方案2】:

将比例更改为 1 而不是 [UIScreen mainScreen].scale

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 1);

【讨论】:

  • 我也对此进行了检查,它给了我 PNG 图像大小 {375, 667} 但问题是它会降低图像质量。图像变得模糊。我需要与 JPG 大小相同且质量相同的 PNG 图像。请帮忙。
  • 我附上了 2 张图片。 Big with [UIScreen mainScreen].scale 和 small 是 1。这里我在小图像中遇到质量问题。
  • 我该如何修复它?请帮忙,在此先感谢。
  • @AsifRaza 保持原样,试试这个,使用这个方法:stackoverflow.com/a/613380/1025063
猜你喜欢
  • 1970-01-01
  • 2015-05-17
  • 2019-11-23
  • 2021-01-16
  • 1970-01-01
  • 2015-08-31
  • 2019-02-06
  • 2012-07-02
  • 2020-10-01
相关资源
最近更新 更多