做上传图片功能,特别是类似于微信,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. 关于android中postDelayed方法的讲解

    这是一种可以创建多线程消息的函数使用方法:1,首先创建一个Handler对象 Handler handler=new Handler(); 2,然后创建一个Runnable对象Runnable run ...

  2. Thinkpad W520 完美安装Ubuntu14.04LTS

    Thinkpad W520 完美安装Ubuntu14.04LTS Ubuntu已经升级到14.04LTS,这是个长期支持的版本号.自从上次安装12.04LTS之后一直没有升级. 于是从站点上下载Ubu ...

  3. Spring笔记 - Bean xml装配

    命名空间表 aop Provides elements for declaring aspects and for automatically proxying @AspectJannotated c ...

  4. Webfrom 生成流水号 组合查询 Repeater中单选与复选控件的使用 JS实战应用

                                             Default.aspx 网页界面 <%@ Page Language="C#" AutoE ...

  5. perl 类里的函数调用其他类的函数

    perl 类里的函数调用其他类的函数: package Horse; use base qw(Critter); sub new { my $invocant = shift; my $class = ...

  6. 基于visual Studio2013解决面试题之1009兄弟字符串

     题目

  7. [poj 1904]King's Quest[Tarjan强连通分量]

    题意:(当时没看懂...) N个王子和N个女孩, 每个王子喜欢若干女孩. 给出每个王子喜欢的女孩编号, 再给出一种王子和女孩的完美匹配. 求每个王子分别可以和那些女孩结婚可以满足最终每个王子都能找到一 ...

  8. JAVA学习笔记 -- 数据结构

    一.数据结构的接口 在Java中全部类的鼻祖是Object类,可是全部有关数据结构处理的鼻祖就是Collection和Iterator接口,也就是集合与遍历. 1.Collection接口 Colle ...

  9. 10个优秀的 HTML5 &amp; CSS3 下拉菜单制作教程

    下拉菜单是一个非经常见的效果.在站点设计中被广泛使用.通过使用下拉菜单.设计者不仅能够在站点设计中营造出色的视觉吸引力,但也能够为站点提供了一个有效的导航方案.使用 HTML5 和 CSS3 能够更e ...

  10. 【ASP.NET Web API教程】3.2 通过.NET客户端调用Web API(C#)

    原文:[ASP.NET Web API教程]3.2 通过.NET客户端调用Web API(C#) 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的 ...