#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
1.图片转化为base64字符串
+ (NSString *)ImageTobase64:(UIImage *)image {
CGSize size = image.size;
size.height = HEIGHT;
UIImage *newImage = [self scaleFromImage:image scaledToSize:size];
NSData *data = [self reduceImage:newImage];
NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
//NSString *photoStr1 = [encodedImageStr stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];
return photoStr1;
}
2.压缩图片质量
+(NSData *)reduceImage:(UIImage *)image
{
NSData *imageData = UIImageJPEGRepresentation(image, 0.3);
return imageData;
}
3.压缩图片尺寸
+ (UIImage*)scaleFromImage:(UIImage*)image scaledToSize:(CGSize)newSize
{
CGSize imageSize = image.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
if (width <= newSize.width && height <= newSize.height){
return image;
}
if (width == 0 || height == 0){
return image;
}
CGFloat widthFactor = newSize.width / width;
CGFloat heightFactor = newSize.height / height;
CGFloat scaleFactor = (widthFactor<heightFactor?widthFactor:heightFactor);
CGFloat scaledWidth = width * scaleFactor;
CGFloat scaledHeight = height * scaleFactor;
CGSize targetSize = CGSizeMake(scaledWidth,scaledHeight);
UIGraphicsBeginImageContext(targetSize);
[image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
4.base64转成uiimage
+ (UIImage *)base64ToImage:(NSString *)_encodedImageStr {
// _encodedImageStr = [_encodedImageStr stringByReplacingOccurrencesOfString:@"%2B" withString:@"+"];
NSData *_decodedImageData = [[NSData alloc] initWithBase64EncodedString:_encodedImageStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
NSLog(@"===Decoded image size: %@", NSStringFromCGSize(_decodedImage.size));
return _decodedImage;
}
5.照片水印
+(UIImage *)watermarkImage:(UIImage *)img withName:(NSString *)name{
NSString* mark = name;
int w = img.size.width;
int h = img.size.height;
UIGraphicsBeginImageContext(img.size);
[img drawInRect:CGRectMake(0, 0, w, h)];
NSDictionary *attr = @{
NSFontAttributeName: [UIFont boldSystemFontOfSize:40], //设置字体
NSForegroundColorAttributeName : [UIColor whiteColor] //设置字体颜色
};
// [mark drawInRect:CGRectMake(0, 30, 500, 50) withAttributes:attr]; //左上角
//
// [mark drawInRect:CGRectMake(w - 500, 30, 500, 50) withAttributes:attr]; //右上角
//
[mark drawInRect:CGRectMake(w - 500, h - 32 - 30, 500, 50) withAttributes:attr]; //右下角
// [mark drawInRect:CGRectMake(0, h - 32 - 30, 500, 50) withAttributes:attr]; //左下角
UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return aimg;
}