我一直在在线查看每个堆栈溢出帖子和视频,但找不到可以正常工作的解决方案。现在,用户在上传到 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。
你有几个选择。
imageData
,如 https://stackoverflow.com/a/32845656/1271826 所示,从而完全避免通过 UIImage
进行往返。因此,您可以保留原始图像的质量,保留与该图像相关的元数据,并享受原始 Assets 的体面压缩。 UIImage
并执行以下组合:UIImageJPEGRepresentation
之前减少图像的尺寸(参见 https://stackoverflow.com/a/10491692/1271826 示例算法);和/或 UIImageJPEGRepresentation
,数字越小,压缩越多,但图像质量损失越大。 关于ios - 如何在 iOS 中压缩图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38923221/