2

我正在制作一个主要功能是在 tableview 中显示大图像的应用程序,有些可以是 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一样?

4

2 回答 2

3

您可以使用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);
}

更多细节在这里

于 2014-09-01T12:51:07.947 回答
0

表格视图图像应该调整大小,当然,它甚至使它看起来比小框架中的大图像更好。现在,如果存储是一个问题,并且您有一个服务器,您可以在需要时从其中下载大图像,您可以在文件系统中实现某种缓存。仅在其中存储最多 n MB 的图像,并且每当请求当前不在文件系统中的新图像时,删除最近最少使用的(或其他东西)并下载新图像。

ps:不要用+[UIImage imageNamed:]。它的缓存算法中有一些错误,或者它不会释放您使用它加载的图像。

于 2011-06-23T05:14:43.467 回答