我是靠谱客的博主 矮小香水,最近开发中收集的这篇文章主要介绍iPhone中压缩图片,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

@interface UIImage (Compress)

 

- (UIImage *)compressedImage;

- (CGFloat)compressionQuality;

- (NSData *)compressedData;

- (NSData *)compressedData:(CGFloat)compressionQuality;

 

@end

 

 

#define MAX_IMAGEPIX 600.0

@implementation UIImage (Compress)

 

- (UIImage *)compressedImage {

CGSize imageSize = self.size;

    CGFloat width = imageSize.width;

    CGFloat height = imageSize.height;

if (width <= MAX_IMAGEPIX && height<= MAX_IMAGEPIX) {

// no need to compress.

return self;

}

if (width == 0 || height == 0) {

// void zero exception

return self;

}

    UIImage *newImage = nil;

CGFloat widthFactor = MAX_IMAGEPIX / width;

CGFloat heightFactor = MAX_IMAGEPIX / height;

CGFloat scaleFactor = 0.0;

if (widthFactor > heightFactor)

scaleFactor = heightFactor; // scale to fit height

else

scaleFactor = widthFactor; // scale to fit width

CGFloat scaledWidth  = width * scaleFactor;

CGFloat scaledHeight = height * scaleFactor;

CGSize targetSize = CGSizeMake(scaledWidth, scaledHeight);

 

    UIGraphicsBeginImageContext(targetSize); // this will crop

 

    CGRect thumbnailRect = CGRectZero;

    thumbnailRect.size.width  = scaledWidth;

    thumbnailRect.size.height = scaledHeight;

 

    [self drawInRect:thumbnailRect];

 

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    //pop the context to get back to the default

    UIGraphicsEndImageContext();

    return newImage;

}

 

- (NSData *)compressedData:(CGFloat)compressionQuality {

assert(compressionQuality<=1.0 && compressionQuality >=0);

return UIImageJPEGRepresentation(self, compressionQuality);

}

 

- (CGFloat)compressionQuality {

NSData *data = UIImageJPEGRepresentation(self, 1.0);

NSUInteger dataLength = [data length];

if(dataLength>50000.0) {

// 5K

return 1.0-50000.0/dataLength;

} else {

return 1.0;

}

}

 

- (NSData *)compressedData {

CGFloat quality = [self compressionQuality];

return [self compressedData:quality];

}

 

@end

最后

以上就是矮小香水为你收集整理的iPhone中压缩图片的全部内容,希望文章能够帮你解决iPhone中压缩图片所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(57)

评论列表共有 0 条评论

立即
投稿
返回
顶部