IOS 图片压缩

原文:http://blog.csdn.net/apple_app/article/details/38847357


最近做论坛功能,发帖的时候需要用到从相册中选取图片然后上传,由于每次上传图片的最大数量为9张,所以需要对图片进行压缩。开始时用了以前经常用的压缩的方法:

[objc]  view plain copy
  1. //压缩图片质量  
  2. +(UIImage *)reduceImage:(UIImage *)image percent:(float)percent  
  3. {  
  4.     NSData *imageData = UIImageJPEGRepresentation(image, percent);  
  5.     UIImage *newImage = [UIImage imageWithData:imageData];  
  6.     return newImage;  
  7. }  
  8. //压缩图片尺寸  
  9. + (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize  
  10. {  
  11.     // Create a graphics image context  
  12.     UIGraphicsBeginImageContext(newSize);  
  13.     // new size  
  14.     [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];  
  15.     // Get the new image from the context  
  16.     UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();  
  17.       
  18.     // End the context  
  19.     UIGraphicsEndImageContext();  
  20.     // Return the new image.  
  21.     return newImage;  
  22. }  

上面的方法比较常见,可是需要加载到内存中来处理图片,当图片数量多了的时候就会收到内存警告,程序崩溃。研究半天终于在一篇博客中找到了解决方法:

[objc]  view plain copy
  1. static size_t getAssetBytesCallback(voidvoid *info, voidvoid *buffer, off_t position, size_t count) {  
  2.     ALAssetRepresentation *rep = (__bridge id)info;  
  3.       
  4.     NSError *error = nil;  
  5.     size_t countRead = [rep getBytes:(uint8_t *)buffer fromOffset:position length:count error:&error];  
  6.       
  7.     if (countRead == 0 && error) {  
  8.         // We have no way of passing this info back to the caller, so we log it, at least.  
  9.         NDDebug(@"thumbnailForAsset:maxPixelSize: got an error reading an asset: %@", error);  
  10.     }  
  11.       
  12.     return countRead;  
  13. }  
  14.   
  15. static void releaseAssetCallback(voidvoid *info) {  
  16.     // The info here is an ALAssetRepresentation which we CFRetain in thumbnailForAsset:maxPixelSize:.  
  17.     // This release balances that retain.  
  18.     CFRelease(info);  
  19. }  
  20.   
  21. // Returns a UIImage for the given asset, with size length at most the passed size.  
  22. // The resulting UIImage will be already rotated to UIImageOrientationUp, so its CGImageRef  
  23. // can be used directly without additional rotation handling.  
  24. // This is done synchronously, so you should call this method on a background queue/thread.  
  25. - (UIImage *)thumbnailForAsset:(ALAsset *)asset maxPixelSize:(NSUInteger)size {  
  26.     NSParameterAssert(asset != nil);  
  27.     NSParameterAssert(size > 0);  
  28.       
  29.     ALAssetRepresentation *rep = [asset defaultRepresentation];  
  30.       
  31.     CGDataProviderDirectCallbacks callbacks = {  
  32.         .version = 0,  
  33.         .getBytePointer = NULL,  
  34.         .releaseBytePointer = NULL,  
  35.         .getBytesAtPosition = getAssetBytesCallback,  
  36.         .releaseInfo = releaseAssetCallback,  
  37.     };  
  38.       
  39.     CGDataProviderRef provider = CGDataProviderCreateDirect((voidvoid *)CFBridgingRetain(rep), [rep size], &callbacks);  
  40.     CGImageSourceRef source = CGImageSourceCreateWithDataProvider(provider, NULL);  
  41.       
  42.     CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(source, 0, (__bridge CFDictionaryRef) @{  
  43.                                                                                                       (NSString *)kCGImageSourceCreateThumbnailFromImageAlways : @YES,  
  44.                                                                                                       (NSString *)kCGImageSourceThumbnailMaxPixelSize : [NSNumber numberWithInt:size],  
  45.                                                                                                       (NSString *)kCGImageSourceCreateThumbnailWithTransform : @YES,  
  46.                                                                                                       });  
  47.     CFRelease(source);  
  48.     CFRelease(provider);  
  49.       
  50.     if (!imageRef) {  
  51.         return nil;  
  52.     }  
  53.       
  54.     UIImage *toReturn = [UIImage imageWithCGImage:imageRef];  
  55.       
  56.     CFRelease(imageRef);  
  57.       
  58.     return toReturn;  
  59. }  

采用上面的方法之后内存占用率很低!

原文地址:http://www.mindsea.com/2012/12/downscaling-huge-alassets-without-fear-of-sigkill/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS应用中集成Vue.js框架并处理图片压缩通常涉及到前端数据处理、图片资源管理以及后端服务器配合等几个方面。 ### iOS Vue项目中图片压缩的基本流程: #### 1. **前端图片加载与显示** 使用Vue.js进行前端开发,可以利用`axios`或`fetch`API来进行网络请求获取图片数据,并将图片展示到页面上。Vue.js框架本身并不直接负责图片压缩,而是用于构建交互式的用户界面。 #### 2. **图片压缩策略** - **懒加载**:只加载当前视图可见的图片,其他图片可以延迟加载甚至异步下载。通过配置Vue的`<img>`标签的`lazy="true"`属性实现基本的懒加载功能,进一步可以自定义懒加载的逻辑。 - **按需调整大小**:可以根据设备屏幕尺寸动态调整图片宽度,避免高分辨率设备显示过大的图片占用不必要的带宽和内存空间。 - **内容感知缩放**:对于高质量图片,可以采用更智能的方式如使用WebP或其他支持的内容感知缩放技术,基于图片内容自动选择合适的压缩比例和质量。 #### 3. **服务端图片优化** 对于服务器端的图片存储和分发,可以考虑将原始大图转换成多个版本,包括低分辨率的预览图和适配不同场景的图片。这可以通过服务器端的图片处理库实现,比如使用AWS S3自带的图像处理工具、Firebase Cloud Functions 或者搭建自己的图片处理微服务(例如使用Node.js和Sharp、Python和PIL等库)。 #### 4. **客户端缓存策略** 利用浏览器的缓存机制,对于经常访问的图片,通过设置适当的Cache-Control头信息,可以让浏览器缓存图片减少再次加载的间。同,可以使用CDN服务加速图片的全球分发,提高用户体验。 ### 实现步骤示例: 假设您正在使用Express作为后端服务器: ```javascript const express = require('express'); const multer = require('multer'); const sharp = require('sharp'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('image'), async (req, res) => { try { const imageBuffer = await sharp(req.file.path) .resize(800) // 自动保持纵横比 .jpeg({ quality: 50 }) // 设置JPEG的质量,从0(完全压缩)到100(无损) .toFile(`compressed/${req.file.filename}`); fs.unlinkSync(req.file.path); // 删除原文件 res.status(200).send({ success: true, message: 'Image compression successful', compressedImagePath: `/compressed/${req.file.filename}` }); } catch (error) { console.error(error); res.status(500).send({ error: 'Failed to compress the image' }); } }); app.listen(3000, () => console.log('Server is running on port 3000')); ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值