方法一:
/**
* 调整图片尺寸和大小
*
* @param sourceImage 原始图片
* @param maxImageSize 新图片最大尺寸
* @param maxSize 新图片最大存储大小
*
* @return 新图片imageData
*/
- (NSData *)reSizeImageData:(UIImage *)sourceImage maxImageSize:(CGFloat)maxImageSize maxSizeWithKB:(CGFloat) maxSize
{
if (maxSize <= 0.0) maxSize = 1024.0;
if (maxImageSize <= 0.0) maxImageSize = 1024.0;
//先调整分辨率
CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
//比例压缩
CGFloat tempHeight = newSize.height / maxImageSize;
CGFloat tempWidth = newSize.width / maxImageSize;
if (tempWidth > 1.0 && tempWidth > tempHeight) {
newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
}
else if (tempHeight > 1.0 && tempWidth < tempHeight){
newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
}
//等比缩放
UIGraphicsBeginImageContext(newSize);
[sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//调整大小
NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
CGFloat sizeOriginKB = imageData.length / 1024.0;
//压缩质量
CGFloat resizeRate = 0.9;
while (sizeOriginKB > maxSize && resizeRate > 0.1) {
imageData = UIImageJPEGRepresentation(newImage,resizeRate);
sizeOriginKB = imageData.length / 1024.0;
resizeRate -= 0.1;
}
return imageData;
}
//使用
UIImage *image = [UIImage imageNamed:@"ss.jpg"];
NSData *data = [self reSizeImageData:image maxImageSize:800 maxSizeWithKB:150];
NSLog(@"%lu",data.length/1024);
方法二 使用分类
//UIImage+WLCompress.m文件
#import "UIImage+WLCompress.h"
@implementation UIImage (WLCompress)
-(NSData *)compressWithMaxLength:(NSUInteger)maxLength{
// Compress by quality
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(self, compression);
//NSLog(@"Before compressing quality, image size = %ld KB",data.length/1024);
if (data.length < maxLength) return data;
CGFloat max = 1;
CGFloat min = 0;
for (int i = 0; i < 6; ++i) {
compression = (max + min) / 2;
data = UIImageJPEGRepresentation(self, compression);
//NSLog(@"Compression = %.1f", compression);
//NSLog(@"In compressing quality loop, image size = %ld KB", data.length / 1024);
if (data.length < maxLength * 0.9) {
min = compression;
} else if (data.length > maxLength) {
max = compression;
} else {
break;
}
}
//NSLog(@"After compressing quality, image size = %ld KB", data.length / 1024);
if (data.length < maxLength) return data;
UIImage *resultImage = [UIImage imageWithData:data];
// Compress by size
NSUInteger lastDataLength = 0;
while (data.length > maxLength && data.length != lastDataLength) {
lastDataLength = data.length;
CGFloat ratio = (CGFloat)maxLength / data.length;
//NSLog(@"Ratio = %.1f", ratio);
CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
(NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
UIGraphicsBeginImageContext(size);
[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
data = UIImageJPEGRepresentation(resultImage, compression);
//NSLog(@"In compressing size loop, image size = %ld KB", data.length / 1024);
}
//NSLog(@"After compressing size loop, image size = %ld KB", data.length / 1024);
return data;
}
//在//UIImage+WLCompress.h文件
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIImage (WLCompress)
-(NSData *)compressWithMaxLength:(NSUInteger)maxLength;
@end
NS_ASSUME_NONNULL_END
//使用
//引入头文件
#import "UIImage+WLCompress.h"
NSData *secondData = [image compressWithMaxLength:25.0f*1024.0f ];
UIImage *secondImage = [UIImage imageWithData:secondData];
图片存储
- (void)saveImage:(UIImage *)image {
NSArray *paths
=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:
[NSString stringWithFormat:@"newss.png"]]; // 保存文件的名称
NSLog(@"%@",filePath);
BOOL result =[UIImagePNGRepresentation(image)writeToFile:filePath atomically:YES]; // 保存成功会返回YES
if (result == YES) {
NSLog(@"保存成功");
}
}
取出图片
- (void)getImage {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent:
[NSString stringWithFormat:@"newss.png"]];
// 保存文件的名称
UIImage *img = [UIImage imageWithContentsOfFile:filePath];
NSLog(@"=== %@", img);
}
图片存入手机相册
UIImageWriteToSavedPhotosAlbum(secondImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error == nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已存入手机相册" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[alert show];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"保存失败" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[alert show];
}
}
图片压缩有质量压缩和尺寸压缩
质量压缩
通过UIImage
和NSData
的相互转化,减小 JPEG 图片的质量来压缩图片。UIImageJPEGRepresentation::
第二个参数compression
取值 0.0~1.0
,值越小表示图片质量越低,图片文件自然越小。
尺寸压缩(比例压缩)
UIGraphicsBeginImageContext(size);
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
给定所需的图片尺寸 size,resultImage 即为原图 image 绘制为 size 大小的图片。
尺寸压缩可以小于图片指定大小,但是相对于质量压缩要模糊。
质量压缩,图片会尽可能保留图片的清晰度。
原文:https://www.jianshu.com/p/99c3e6a6c033
https://www.jianshu.com/p/1f89da12bfaa