iphone - 针对 iOS 的大图像压缩和调整大小

标签 iphone objective-c memory-management uiimage uiimagejpegrepresentation

我正在制作一个应用程序,其主要功能是在表格 View 中显示大图像,有些图像可以是 1000 像素宽,大小为 1MB 以上。

我发现较旧的设备 (3GS) 在处理这些问题时遇到严重问题,并会快速发出内存警告。

我无法绕过正在引入的图像,但我认为我可以使它们的尺寸和文件大小更小。所以我调查了

NSData *dataForJPEGFile = UIImageJPEGRepresentation(img, 0.6)

用于压缩,但我认为这对内存警告没有帮助

并调整大小:

UIImage *newImage;
UIImage *oldImage = [UIImage imageWithData:imageData] ;
UIGraphicsBeginImageContext(CGSizeMake(tempImage.size.width,tempImage.size.height)); 
[oldImage drawInRect:CGRectMake(0, 0,320.0f,heightScaled)];
newImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext();

还有https://github.com/AliSoftware/UIImage-Resize

基本上,我想拍摄一张图像并重新格式化,使其更小,尺寸和文件大小也更小,然后删除旧的图像。这是最好的方法吗? 缓存图像会有帮助吗?就像 https://github.com/rs/SDWebImage

最佳答案

您可以使用 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 .

关于iphone - 针对 iOS 的大图像压缩和调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6449572/

相关文章:

iphone - 一个 View Controller 可以处理多少个 subview 和 TableView

objective-c - 在 [tableview reloadData] 之前重新加载 UITableViewController 模型

c++ - cvrelease 会删除分配的内存吗?

c# - 确定变量使用的字节数

MySQL从左连接和右连接的结果插入导致内存问题

iphone - 在 iPhone 应用程序中嵌入 youtube 视频

iphone - 如何将 UIPanGestureRecognizer 添加到 UIScrollView subview

ios - 更改 UITableView 中所有单元格的 subview

objective-c - 字典值字典中的 iPhone NSArray

iphone - 如何控制 subview 的大小和布局?