2

我正在制作一个应用程序,它的主要功能是在桌面视图中显示大图像,其中一些可以是1000像素宽和1MB +大小。为iOS压缩和调整大图像

我发现较旧的设备(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一样?

回答

0

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

ps:不要使用+[UIImage imageNamed:]。它的缓存算法有一些缺陷,或者它没有释放你使用它加载的图像。

+0

问题是,图像来自所有不同服务器的RSS提要,我们没有图像。 – daidai

+0

为什么这是一个问题? – xissburg

+0

我想它不是,最好的方法来实现'在文件系统中的某种缓存'?你有任何文档/链接等? – daidai

2

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