截取图片和缩小图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//截取屏幕的图片
-(NSString * )ScreenShotImage:(float )insertX insertSecond:(float)insertY insertThird:(float)width insertFour:(float)height{
// 获取截取块
UIGraphicsBeginImageContext(webView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
// 截取图片
UIRectClip(CGRectMake(insertX, insertY, width, height));
[webView.layer renderInContext:context];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, CGRectMake(insertX,insertY, width, height));
UIImage *subImage = [UIImage imageWithCGImage:subImageRef];
// 5、关闭上下文
UIGraphicsEndImageContext();
NSData *beforeData = UIImageJPEGRepresentation(subImage, 1.0f);
UIImage *saveImage = [UIImage imageWithData:beforeData];
while (beforeData.length/1024 > 45) {
beforeData = UIImageJPEGRepresentation(subImage, 0.30f);
saveImage = [UIImage imageWithData:beforeData];
}
saveImage = [self compressImage:saveImage toTargetWith:width/3];
NSData *afterData = UIImageJPEGRepresentation(saveImage, 1.0f);
// UIImageWriteToSavedPhotosAlbum(saveImage, nil, nil, nil);//保存图片到照片库
NSString *dataString = [NSString stringWithFormat:@"%@",[afterData base64EncodedStringWithOptions: 0]];
return dataString;
}
// 缩小图片
- (UIImage *)compressImage:(UIImage *)sourceImage toTargetWith:(CGFloat)targetWidth{
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetheight = (targetWidth / width) * height;
UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetheight));
[sourceImage drawInRect:CGRectMake(0, 0, targetWidth, targetheight)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndPDFContext();
return newImage;
}