做上传图片功能,特别是类似于微信,QQ里面,公布9张图片, 少不了碰到一个问题,就是图片压缩问题,当然我也遇到了.

我研究了这个问题,发现网上普遍的方法是例如以下

  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. // End the context
  18. UIGraphicsEndImageContext();
  19. // Return the new image.
  20. return newImage;
  21. }

上面的方法比較常见,但是须要载入到内存中来处理图片,当图片数量多了的时候就会收到内存警告,程序崩溃,

我測试过上面方法,上面方法真不好用,真的不推荐大家用.那么我推荐以下这种方法:

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

採用上面的方法之后内存占用率非常低。

上面这么长的东西,大家一定看的非常费劲,那么我直接上我源代码,给大家看看,照着我的源代码,写就好了.

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvenVveW91MTMxNA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">

static size_t getAssetBytesCallback(void *info, void *buffer, off_t position, size_t count)
{

ALAssetRepresentation *rep = (__bridge id)info;

NSError *error = nil;

size_t countRead = [rep getBytes:(uint8_t *)buffer fromOffset:position length:count error:&error];

if (countRead == 0 && error) {

// We have no way of passing this info back to the caller, so we log it, at least.

NSLog(@"thumbnailForAsset:maxPixelSize: got an error reading an asset: %@",
error);

}

return countRead;

}

static void releaseAssetCallback(void *info) {

// The info here is an ALAssetRepresentation which we CFRetain in thumbnailForAsset:maxPixelSize:.

// This release balances that retain.

CFRelease(info);

}

//压缩图片

- (UIImage *)thumbnailForAsset:(ALAsset *)asset maxPixelSize:(NSUInteger)size

{

NSParameterAssert(asset != nil);

NSParameterAssert(size > 0);

ALAssetRepresentation *rep = [asset defaultRepresentation];

CGDataProviderDirectCallbacks callbacks =

{

.version = 0,

.getBytePointer = NULL,

.releaseBytePointer = NULL,

.getBytesAtPosition = getAssetBytesCallback,

.releaseInfo = releaseAssetCallback,

};

CGDataProviderRef provider = CGDataProviderCreateDirect((void *)CFBridgingRetain(rep),
[rep size], &callbacks);

CGImageSourceRef source = CGImageSourceCreateWithDataProvider(provider, NULL);

CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(source, 0,
(__bridge CFDictionaryRef)

@{   (NSString *)kCGImageSourceCreateThumbnailFromImageAlways: @YES,

(NSString *)kCGImageSourceThumbnailMaxPixelSize :
[NSNumber numberWithInt:size],

(NSString *)kCGImageSourceCreateThumbnailWithTransform :@YES,

});

CFRelease(source);

CFRelease(provider);

if (!imageRef) {

return nil;

}

UIImage *toReturn = [UIImage imageWithCGImage:imageRef];

CFRelease(imageRef);

return toReturn;

}

把上面的代码拷贝到project里面,然后调用这种方法就好了,例如以下图:

好了,有问题,欢迎评论给我.....

本文部分内容參考自http://www.lyitnews.com/portal.php?mod=view&aid=1206,感谢他的分享....

iOS 史上最全的图片压缩方法集合的更多相关文章

  1. 移动端IM开发者必读(二):史上最全移动弱网络优化方法总结

    1.前言 本文接上篇<移动端IM开发者必读(一):通俗易懂,理解移动网络的“弱”和“慢”>,关于移动网络的主要特性,在上篇中已进行过详细地阐述,本文将针对上篇中提到的特性,结合我们的实践经 ...

  2. 史上最全的MYSQL备份方法

    本人曾经 用过的备份方式有:mysqldump.mysqlhotcopy.BACKUP TABLE .SELECT INTOOUTFILE,又或者备份二进制日志(binlog),还可以是直接拷贝数据文 ...

  3. 了解iOS消息推送一文就够:史上最全iOS Push技术详解

    本文作者:陈裕发, 腾讯系统测试工程师,由腾讯WeTest整理发表. 1.引言 开发iOS系统中的Push推送,通常有以下3种情况: 1)在线Push:比如QQ.微信等IM界面处于前台时,聊天消息和指 ...

  4. 史上最全的CSS hack方式一览 jQuery 图片轮播的代码分离 JQuery中的动画 C#中Trim()、TrimStart()、TrimEnd()的用法 marquee 标签的使用详情 js鼠标事件 js添加遮罩层 页面上通过地址栏传值时出现乱码的两种解决方法 ref和out的区别在c#中 总结

    史上最全的CSS hack方式一览 2013年09月28日 15:57:08 阅读数:175473 做前端多年,虽然不是经常需要hack,但是我们经常会遇到各浏览器表现不一致的情况.基于此,某些情况我 ...

  5. GitHub上史上最全的Android开源项目分类汇总 (转)

    GitHub上史上最全的Android开源项目分类汇总 标签: github android 开源 | 发表时间:2014-11-23 23:00 | 作者:u013149325 分享到: 出处:ht ...

  6. 你想找的Python资料这里全都有!没有你找不到!史上最全资料合集

    你想找的Python资料这里全都有!没有你找不到!史上最全资料合集 2017年11月15日 13:48:53 技术小百科 阅读数:1931   GitHub 上有一个 Awesome - XXX 系列 ...

  7. 开源框架】Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发

    [原][开源框架]Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发,欢迎各位... 时间 2015-01-05 10:08:18 我是程序猿,我为自己代言 原文  http: ...

  8. Springcloud 配置 | 史上最全,一文全懂

    Springcloud 高并发 配置 (一文全懂) 疯狂创客圈 Java 高并发[ 亿级流量聊天室实战]实战系列之15 [博客园总入口 ] 前言 疯狂创客圈(笔者尼恩创建的高并发研习社群)Spring ...

  9. Linux面试题(史上最全、持续更新、吐血推荐)

    文章很长,建议收藏起来,慢慢读! 疯狂创客圈为小伙伴奉上以下珍贵的学习资源: 疯狂创客圈 经典图书 : <Netty Zookeeper Redis 高并发实战> 面试必备 + 大厂必备 ...

随机推荐

  1. jquery 中获取URL参数的方法

    今天写项目需要获取url后面的参数ref参数来判断是否开启计时器来刷新页面,之前一直都是用JS写的,今天在查资料的时候看到了一款JQ的插件 项目地址:https://github.com/allmar ...

  2. How to Create Dump File for Applications

    使用WinDBG这个工具,可以在应用程序异常终止或者无响应时获取它的尸体,以用来解剖研究. Creating Dump File      在Vista环境中抓取Dump文件很方便,在task man ...

  3. vi/vim高级命令集粹

    vi/vim高级命令集粹 (ctrl +v过来 留着以后看) 1.交换两个字符位置 xp 2.上下两行调换 ddp 3.把文件内容反转 :g/^/m0/ (未通过) 4.上下两行合并 J 5.删除所有 ...

  4. 编写一个void sort(int*x,int n)实现将x数组中的n个数据从大到小排序。n及数组元素在主函数中输入。将结果显示在屏幕上并输出到文件

    #include<stdio.h> void sort(int*x,int n) { int i,j,k,t; for(i=0;i<n-1;i++) { k=i; for(j=i+1 ...

  5. linux脚本:shell, 判断输入参数的个数(命令行)

    if [ $# != 3 ] ; thenecho "USAGE: $0 from to"echo " e.g.: $0 ~/oucaijun/from ~/oucaij ...

  6. SQL注入(一)普通型注入

    既然说了从头开始,先从注入开始吧,先来温习一下之前会的一些注入. PHP注入 0x01: 判断是否存在注入: '   报错 ' and 1=1   正确 ' and 1=2   错误 0x01: or ...

  7. ajax表单提交全路径

    //ajax提交form表单的方式 $(document).ready(function() { $('#shopping-submit').click(function() { alert(&quo ...

  8. res/drawable目录

    在Android Eclipse项目中res/目录下包含有drawable-ldpi/,drawable-mdpi/,drawable-hdpi/,drawable-xhdpi/目录,这几个目录的后缀 ...

  9. 九度OnlineJudge之1020:最小长方形

    题目描述:     给定一系列2维平面点的坐标(x, y),其中x和y均为整数,要求用一个最小的长方形框将所有点框在内.长方形框的边分别平行于x和y坐标轴,点落在边上也算是被框在内. 输入:      ...

  10. HTTP协议的请求和响应学习

    本篇作为学习servlet的前提,http协议是学习JavaWeb开发的基石,不深入了解http协议,就不能说掌握了JavaWeb开发. HTTP协议有两个版本:HTTP1.0和HTTP1.1,那么有 ...