我正在构建一个应用程序,允许用户拍照或从 iPhone 上的库中选择一张并将其上传到 Parse 后端。
我面临的问题是关于文件的大小。
我读过 Facebook、Twitter、Instagram 和 Google 等大公司在分辨率和文件大小方面的做法,但我无法接近。
我确信他们拥有最好的代码和工具来做到这一点,但我很乐意使用 iOS 常规流程尽可能好地实现它。
这就是我现在正在做的事情:
- (UIImage *)normalResImageForAsset:(ALAsset*)asset
{
// Convert ALAsset to UIImage
UIImage *image = [self highResImageForAsset:asset];
// Determine output size
CGFloat maxSize = 1024.0f;
CGFloat width = image.size.width;
CGFloat height = image.size.height;
CGFloat newWidth = width;
CGFloat newHeight = height;
// If any side exceeds the maximun size, reduce the greater side to 1200px and proportionately the other one
if (width > maxSize || height > maxSize) {
if (width > height) {
newWidth = maxSize;
newHeight = (height*maxSize)/width;
} else {
newHeight = maxSize;
newWidth = (width*maxSize)/height;
}
}
// Resize the image
CGSize newSize = CGSizeMake(newWidth, newHeight);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Set maximun compression in order to decrease file size and enable faster uploads & downloads
NSData *imageData = UIImageJPEGRepresentation(newImage, 0.0f);
UIImage *processedImage = [UIImage imageWithData:imageData];
return processedImage;
}
我正在尝试使 1024px 成为允许的最大尺寸(两者都具有 ot 高度)以在那里开始一些限制,然后我正在应用最大压缩来减小尺寸。
这可以在没有真正损坏 JPEG 的情况下减少大约 50% 的图像大小,但仍然很多。特别是如果照片是用手机的相机拍摄并上传的。处理后的图像仍然很容易有 1MB 大小,这实在是太大了。
我猜我可能遗漏了一些有用的步骤或使用了错误的技术。
任何反馈将不胜感激。