UIImage常用封装
根据颜色返回图片,根据str返回颜色,压缩UIImage不大于300k
.h代码:
#import <Foundation/Foundation.h> @interface ImageService : NSObject /** 根据颜色返回图片 */ +(UIImage*) createImageWithColor:(UIColor*) color; /** 根据str返回颜色 */ + (UIColor *) colorWithHexString: (NSString *)color; //获取data不大于300k + (NSData *)compressOriginalImage:(UIImage *)image; @end
.m代码:
#import "ImageService.h" @implementation ImageService //color转image +(UIImage*) createImageWithColor:(UIColor*) color { CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage; } //str转color + (UIColor *) colorWithHexString: (NSString *)color { NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString]; // String should be 6 or 8 characters if ([cString length] < 6) { return [UIColor clearColor]; } // strip 0X if it appears if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2]; if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1]; if ([cString length] != 6) return [UIColor clearColor]; // Separate into r, g, b substrings NSRange range; range.location = 0; range.length = 2; //r NSString *rString = [cString substringWithRange:range]; //g range.location = 2; NSString *gString = [cString substringWithRange:range]; //b range.location = 4; NSString *bString = [cString substringWithRange:range]; // Scan values unsigned int r, g, b; [[NSScanner scannerWithString:rString] scanHexInt:&r]; [[NSScanner scannerWithString:gString] scanHexInt:&g]; [[NSScanner scannerWithString:bString] scanHexInt:&b]; return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f]; } + (NSData *)compressOriginalImage:(UIImage *)image{ NSData * data = UIImageJPEGRepresentation(image, 1.0); CGFloat dataKBytes = data.length/1000.0; CGFloat maxQuality = 0.9f; CGFloat lastData = dataKBytes; while (dataKBytes > 10 && maxQuality > 0.01f) { maxQuality = maxQuality - 0.01f; data = UIImageJPEGRepresentation(image, maxQuality); dataKBytes = data.length / 1000.0; if (lastData == dataKBytes) { break; }else{ lastData = dataKBytes; } } return data; } @end
头像压缩代码:
NSData * data = UIImageJPEGRepresentation(image, 1.0); CGFloat dataSizeM = data.length/1024.0/1024.0; if(dataSizeM>1.0){ data = UIImageJPEGRepresentation(image, 0.1); }else if(dataSizeM>0.8){ data = UIImageJPEGRepresentation(image, 0.8); }else if(dataSizeM>0.5){ data = UIImageJPEGRepresentation(image, 0.6); } return data;