ios - 如何在 iOS 中压缩图像?

标签 ios objective-c amazon-s3 uiimage image-compression

我一直在在线查看每个堆栈溢出帖子和视频,但找不到可以正常工作的解决方案。现在,用户在上传到 AWS S3 存储桶之前选择了我要压缩的照片。上传完美,但由于某种原因,压缩图像比原始图像大!例如,如果用户选择了一张 9KB 的照片,当我上传到 S3 时,该照片是 28.5KB。我尝试了一张不同的照片,它是 48KB,在 S3 上“压缩”后是 378.9KB! (我正在使用最新的软件版本并使用模拟器进行编译)

我想在上传之前尽可能多地压缩原始图像。

这是我到目前为止所拥有的:

我如何“压缩”图像:

UIImage *compressedProductImage;
NSData *NSproductImage;
NSUInteger productImageSize;

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    self.productImage = info[UIImagePickerControllerOriginalImage];
    [self.productImageImageView setImage:self.productImage];
    [self dismissViewControllerAnimated:YES completion:nil];

    NSproductImage = UIImageJPEGRepresentation(self.productImage, 0.5f);
    productImageSize = [NSproductImage length];

    compressedProductImage = [UIImage imageWithData: NSproductImage];

我如何上传照片:
//Convert product UIImage
NSArray *productImagePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *productImageFilePath = [[productImagePaths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@".png"]];
[UIImagePNGRepresentation(compressedProductImage) writeToFile:productImageFilePath atomically:YES];
NSURL *productImageFileUrl = [NSURL fileURLWithPath:productImageFilePath];

uploadRequest.body = productImageFileUrl;//Needs to be a NSURL
uploadRequest.bucket = AWS_BUCKET_NAME;
uploadRequest.key = productImageKey;
uploadRequest.contentType = @"image/png";
uploadRequest.ACL = AWSS3BucketCannedACLPublicRead;

[[transferManager upload:uploadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task) {
    if (task.error != nil) {
        NSLog(@"%s %@","Error uploading (product image):", uploadRequest.key);
    }else{
        NSLog(@"Product image upload completed");
    }
    return nil;
}];

最佳答案

正如 rmaddy 指出的那样,您正在获取挑选的图像,将其转换为 JPEG,转换回 UIImage(失去 JPEG 压缩的任何好处),然后将其转换为提供适度压缩的 PNG,通常压缩率要低得多比用户照片库中的原始 JPEG。

你有几个选择。

  • 您可以从照片库中的 Assets 中检索原始 imageData,如 https://stackoverflow.com/a/32845656/1271826 所示,从而完全避免通过 UIImage 进行往返。因此,您可以保留原始图像的质量,保留与该图像相关的元数据,并享受原始 Assets 的体面压缩。
  • 您可以将拾取的图像作为 UIImage 并执行以下组合:
  • 在调用 UIImageJPEGRepresentation 之前减少图像的尺寸(参见 https://stackoverflow.com/a/10491692/1271826 示例算法);和/或
  • 使用质量小于1.0的UIImageJPEGRepresentation,数字越小,压缩越多,但图像质量损失越大。
  • 关于ios - 如何在 iOS 中压缩图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38923221/

    相关文章:

    ios - 以编程方式添加约束以相对于兄弟查看

    iphone - 保存从互联网下载的数据

    python s3 使用 boto,说 'attribute error: ' str' 对象没有属性 'connection'

    android - 证书和 keystore

    ios - 键入时如何更改 UIWebview 高度?

    amazon-web-services - 用于设置 S3 存储桶默认加密的 CloudFormation 模板

    amazon-s3 - 使用 boto3 创建带有自定义 header 的 s3 预签名 url (put)

    iphone - 如何将 NIB 文件的使用引入我现有的自定义 UIView?

    iphone - 我遇到了一个关于 float 的麻烦。帮帮我

    ios - NSURLSession 后台传输超时未触发