gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:06:40 24 4
gpt4 key购买 nike

我正在制作一个应用程序,其主要功能是在表格 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com