iOS 史上最全的图片压缩方法集合
做上传图片功能,特别是类似于微信,QQ里面,公布9张图片, 少不了碰到一个问题,就是图片压缩问题,当然我也遇到了.
我研究了这个问题,发现网上普遍的方法是例如以下
- //压缩图片质量
- +(UIImage *)reduceImage:(UIImage *)image percent:(float)percent
- {
- NSData *imageData = UIImageJPEGRepresentation(image, percent);
- UIImage *newImage = [UIImage imageWithData:imageData];
- return newImage;
- }
- //压缩图片尺寸
- + (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
- {
- // Create a graphics image context
- UIGraphicsBeginImageContext(newSize);
- // new size
- [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
- // Get the new image from the context
- UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
- // End the context
- UIGraphicsEndImageContext();
- // Return the new image.
- return newImage;
- }
上面的方法比較常见,但是须要载入到内存中来处理图片,当图片数量多了的时候就会收到内存警告,程序崩溃,
我測试过上面方法,上面方法真不好用,真的不推荐大家用.那么我推荐以下这种方法:
- static size_t getAssetBytesCallback(voidvoid *info, voidvoid *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.
- NDDebug(@"thumbnailForAsset:maxPixelSize: got an error reading an asset: %@", error);
- }
- return countRead;
- }
- static void releaseAssetCallback(voidvoid *info) {
- // The info here is an ALAssetRepresentation which we CFRetain in thumbnailForAsset:maxPixelSize:.
- // This release balances that retain.
- CFRelease(info);
- }
- // Returns a UIImage for the given asset, with size length at most the passed size.
- // The resulting UIImage will be already rotated to UIImageOrientationUp, so its CGImageRef
- // can be used directly without additional rotation handling.
- // This is done synchronously, so you should call this method on a background queue/thread.
- - (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((voidvoid *)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;
- }
採用上面的方法之后内存占用率非常低。
上面这么长的东西,大家一定看的非常费劲,那么我直接上我源代码,给大家看看,照着我的源代码,写就好了.
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 史上最全的图片压缩方法集合的更多相关文章
- 移动端IM开发者必读(二):史上最全移动弱网络优化方法总结
1.前言 本文接上篇<移动端IM开发者必读(一):通俗易懂,理解移动网络的“弱”和“慢”>,关于移动网络的主要特性,在上篇中已进行过详细地阐述,本文将针对上篇中提到的特性,结合我们的实践经 ...
- 史上最全的MYSQL备份方法
本人曾经 用过的备份方式有:mysqldump.mysqlhotcopy.BACKUP TABLE .SELECT INTOOUTFILE,又或者备份二进制日志(binlog),还可以是直接拷贝数据文 ...
- 了解iOS消息推送一文就够:史上最全iOS Push技术详解
本文作者:陈裕发, 腾讯系统测试工程师,由腾讯WeTest整理发表. 1.引言 开发iOS系统中的Push推送,通常有以下3种情况: 1)在线Push:比如QQ.微信等IM界面处于前台时,聊天消息和指 ...
- 史上最全的CSS hack方式一览 jQuery 图片轮播的代码分离 JQuery中的动画 C#中Trim()、TrimStart()、TrimEnd()的用法 marquee 标签的使用详情 js鼠标事件 js添加遮罩层 页面上通过地址栏传值时出现乱码的两种解决方法 ref和out的区别在c#中 总结
史上最全的CSS hack方式一览 2013年09月28日 15:57:08 阅读数:175473 做前端多年,虽然不是经常需要hack,但是我们经常会遇到各浏览器表现不一致的情况.基于此,某些情况我 ...
- GitHub上史上最全的Android开源项目分类汇总 (转)
GitHub上史上最全的Android开源项目分类汇总 标签: github android 开源 | 发表时间:2014-11-23 23:00 | 作者:u013149325 分享到: 出处:ht ...
- 你想找的Python资料这里全都有!没有你找不到!史上最全资料合集
你想找的Python资料这里全都有!没有你找不到!史上最全资料合集 2017年11月15日 13:48:53 技术小百科 阅读数:1931 GitHub 上有一个 Awesome - XXX 系列 ...
- 开源框架】Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发
[原][开源框架]Android之史上最全最简单最有用的第三方开源库收集整理,有助于快速开发,欢迎各位... 时间 2015-01-05 10:08:18 我是程序猿,我为自己代言 原文 http: ...
- Springcloud 配置 | 史上最全,一文全懂
Springcloud 高并发 配置 (一文全懂) 疯狂创客圈 Java 高并发[ 亿级流量聊天室实战]实战系列之15 [博客园总入口 ] 前言 疯狂创客圈(笔者尼恩创建的高并发研习社群)Spring ...
- Linux面试题(史上最全、持续更新、吐血推荐)
文章很长,建议收藏起来,慢慢读! 疯狂创客圈为小伙伴奉上以下珍贵的学习资源: 疯狂创客圈 经典图书 : <Netty Zookeeper Redis 高并发实战> 面试必备 + 大厂必备 ...
随机推荐
- 关于android中postDelayed方法的讲解
这是一种可以创建多线程消息的函数使用方法:1,首先创建一个Handler对象 Handler handler=new Handler(); 2,然后创建一个Runnable对象Runnable run ...
- Thinkpad W520 完美安装Ubuntu14.04LTS
Thinkpad W520 完美安装Ubuntu14.04LTS Ubuntu已经升级到14.04LTS,这是个长期支持的版本号.自从上次安装12.04LTS之后一直没有升级. 于是从站点上下载Ubu ...
- Spring笔记 - Bean xml装配
命名空间表 aop Provides elements for declaring aspects and for automatically proxying @AspectJannotated c ...
- Webfrom 生成流水号 组合查询 Repeater中单选与复选控件的使用 JS实战应用
Default.aspx 网页界面 <%@ Page Language="C#" AutoE ...
- perl 类里的函数调用其他类的函数
perl 类里的函数调用其他类的函数: package Horse; use base qw(Critter); sub new { my $invocant = shift; my $class = ...
- 基于visual Studio2013解决面试题之1009兄弟字符串
题目
- [poj 1904]King's Quest[Tarjan强连通分量]
题意:(当时没看懂...) N个王子和N个女孩, 每个王子喜欢若干女孩. 给出每个王子喜欢的女孩编号, 再给出一种王子和女孩的完美匹配. 求每个王子分别可以和那些女孩结婚可以满足最终每个王子都能找到一 ...
- JAVA学习笔记 -- 数据结构
一.数据结构的接口 在Java中全部类的鼻祖是Object类,可是全部有关数据结构处理的鼻祖就是Collection和Iterator接口,也就是集合与遍历. 1.Collection接口 Colle ...
- 10个优秀的 HTML5 & CSS3 下拉菜单制作教程
下拉菜单是一个非经常见的效果.在站点设计中被广泛使用.通过使用下拉菜单.设计者不仅能够在站点设计中营造出色的视觉吸引力,但也能够为站点提供了一个有效的导航方案.使用 HTML5 和 CSS3 能够更e ...
- 【ASP.NET Web API教程】3.2 通过.NET客户端调用Web API(C#)
原文:[ASP.NET Web API教程]3.2 通过.NET客户端调用Web API(C#) 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的 ...