我的应用程序正在从网络下载一组图像文件,并将它们保存到本地iPhone磁盘。其中一些图像的尺寸非常大(例如,宽度超过500像素)。由于iPhone甚至没有足够大的显示器来显示原始大小的图像,我计划将图像大小调整为更小的大小,以节省空间/性能。
此外,其中一些图像是JPEG格式,它们不会保存为通常的60%质量设置。
如何使用JPEG调整图片大小,以及如何更改iPhone图像的质量设置?
发布于 2009-03-05 02:20:23
本文提供了几个建议作为对this question的回答。我建议使用this post中描述的技术,并提供相关代码:
+ (UIImage*)imageWithImage:(UIImage*)image
scaledToSize:(CGSize)newSize;
{
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
就图像的存储而言,iPhone使用的最快的图像格式是PNG,因为它对该格式进行了优化。但是,如果您希望将这些图像存储为JPEG,您可以使用UIImage并执行以下操作:
NSData *dataForJPEGFile = UIImageJPEGRepresentation(theImage, 0.6);
这将创建一个NSData实例,其中包含60%质量设置的JPEG图像的原始字节。然后,可以将该NSData实例的内容写入磁盘或缓存在内存中。
发布于 2009-03-05 04:35:31
调整图像大小的最简单、最直接的方法是
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float imgRatio = actualWidth/actualHeight;
float maxRatio = 320.0/480.0;
if(imgRatio!=maxRatio){
if(imgRatio < maxRatio){
imgRatio = 480.0 / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = 480.0;
}
else{
imgRatio = 320.0 / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = 320.0;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
发布于 2014-09-01 19:03:23
上述方法适用于小图像,但当您尝试调整非常大的图像大小时,您将很快耗尽内存并使应用程序崩溃。一种更好的方法是使用CGImageSourceCreateThumbnailAtIndex
来调整图像的大小,而不需要先完全解码它。
如果您有要调整大小的图像的路径,可以使用以下命令:
- (void)resizeImageAtPath:(NSString *)imagePath {
// Create the image source (from path)
CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef) [NSURL fileURLWithPath:imagePath], NULL);
// To create image source from UIImage, use this
// NSData* pngData = UIImagePNGRepresentation(image);
// CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef)pngData, NULL);
// Create thumbnail options
CFDictionaryRef options = (__bridge CFDictionaryRef) @{
(id) kCGImageSourceCreateThumbnailWithTransform : @YES,
(id) kCGImageSourceCreateThumbnailFromImageAlways : @YES,
(id) kCGImageSourceThumbnailMaxPixelSize : @(640)
};
// Generate the thumbnail
CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options);
CFRelease(src);
// Write the thumbnail at path
CGImageWriteToFile(thumbnail, imagePath);
}
更多细节here。
https://stackoverflow.com/questions/612131
复制相似问题