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 高并发实战> 面试必备 + 大厂必备 ...
随机推荐
- BFS寻路的AS3实现
关于BFS的相关知识由于水平有限就不多说了,感兴趣的可以自己去wiki或者其他地方查阅资料. 这里大概说一下BFS寻路的思路,或者个人对BFS的理解: 大家知道Astar的一个显著特点是带有启发函数, ...
- c语言: Standard C 语言标准函数库
Standard C 语言标准函数库速查 (Cheat Sheet) http://ganquan.info/standard-c/ c语言标准头: <assert.h> 断言 <c ...
- 《C陷阱与缺陷》整理二
1.数组名作实參 在C语言中,我们没有办法将一个数组作为函数參数传递,假设我们使用数组名作为參数.这个时候数组名立马会被转换为指向该数组的第一个元素的指针. 关于这一点的理解能够向前深 ...
- 在Android手机上获取其它应用的包名及版本
转载请注明出处:http://blog.csdn.net/jason_src/article/details/37757661 获取Android手机上其它应用的包名及版本方法有非常多,能够通过AAP ...
- MSSQL - 因为数据库正在使用,所以无法获得对数据库的独占访问权。
关于“因为数据库正在使用,所以无法获得对数据库的独占访问权”的最终解决方案 今天在使用SQL Server2005对某个数据库进行还原操作的时候,出现了如上问题,“因为数据库正在使用,所以无法获得 ...
- PHP学习之-1.4 计算表达式
计算表达式 不同于HTML和CSS,在PHP中做计算,比如我们写 echo 12*3 计算结果是36.代码如下 <?php echo 12*3;?> 实例 <!DOCTYPE HTM ...
- 基于visual Studio2013解决面试题之0601二叉树深度
题目
- (5/9)*(f-32)与5*(f-32)/9
今天在Linux下用c语言写个小程序玩玩,主要就是根据华氏温度计算摄氏温度.公式是:摄氏度=(5/9)*(华氏度-32) 代码很简单~ #include<stdio.h> main() { ...
- Possible concurrency problem: Replicated version id X matches in-memory version for session ...
The message basically is saying that a replicated session is overriding an existing session in that ...
- mssql 返回表的创建语句
if OBJECT_ID('sp_create_table_sql','P') is not null drop proc sp_create_table_sql go create proc sp_ ...