iOS-图片限制
2018-07-18 本文已影响0人
不可雕的板蓝根
//先限制图片大小,一般用了节省流量iOS和安卓端统一宽度640或者720; 图片大小超过1M,就要循环压缩图片的质量,直到小于1M才去上传。
+ (NSData* )compressionImage:(UIImage* )image WithMaxWidth:(CGFloat )maxWidth limitSize:(NSInteger )limitSize{
if (maxWidth < 0) {
maxWidth = 1024;
}
//限制图片大小
CGSize newSize = CGSizeMake(image.size.width, image.size.height);
CGFloat scaleH = newSize.height / maxWidth;
CGFloat scaleW = newSize.width / maxWidth;
if (scaleW > 1.0 && scaleW > scaleH) {
newSize = CGSizeMake(ceil(image.size.width / scaleW), ceil(image.size.height / scaleW));
}else if(scaleH > 1.0 && scaleW < scaleH){
newSize = CGSizeMake(ceil(image.size.width / scaleH), ceil(image.size.height / scaleH));
}
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//压缩图片质量
CGFloat compression = .9f;
CGFloat minCompression = .1f;
NSData* imageData = UIImageJPEGRepresentation(newImage, compression);
while (imageData.length / 1000 >limitSize && compression > minCompression) {
imageData = nil;
compression -= .1;
imageData = UIImageJPEGRepresentation(newImage, compression);
}
return imageData;
}
+ (UIImage* )getCircleImage:(UIImage* )image withBorderColor:(UIColor* )borderColor withBorderWidth:(CGFloat )borderWidth{
// borderWidth 表示边框的宽度
CGFloat imageW = image.size.width + 2 * borderWidth;
CGFloat imageH = imageW;
CGSize imageSize = CGSizeMake(imageW, imageH);
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
CGContextRef context = UIGraphicsGetCurrentContext();
// borderColor表示边框的颜色
[borderColor set];
CGFloat bigRadius = imageW * 0.5;
CGFloat centerX = bigRadius;
CGFloat centerY = bigRadius;
CGContextAddArc(context, centerX, centerY, bigRadius, 0, M_PI * 2, 0);
CGContextFillPath(context);
CGFloat smallRadius = bigRadius - borderWidth;
CGContextAddArc(context, centerX, centerY, smallRadius, 0, M_PI * 2, 0);
CGContextClip(context);
[image drawInRect:CGRectMake(borderWidth, borderWidth, image.size.width, image.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}