之前项目中需要分享图文消息到微信和朋友圈,但接口返回的图片大小超过32K,需要我们在应用中将图片压缩。
最开始,使用了“UIImageJPEGRepresentation(newImg, 0.5)”这种方式,发现没用,图片大小反而变大了。
然后,就使用如下这种重绘图片压缩大小的方式。
// 分享到微信好友||朋友圈
- (void)shareWithMark:(int)mark {
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.wxDelegate = self;
WXMediaMessage *message = [WXMediaMessage message];
message.title = _dataModel.dHairdresserName;
message.description = _dataModel.dBuyKnow;
// 图片限制大小32KB
NSData *tpData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_dataModel.dPicUrl]];
NSInteger dxLengh = [tpData length]/1024;
NSInteger num = 0;
while (dxLengh >= 32) {
if (num > 30) {
break;
}
UIImage *tpImg = [UIImage imageWithData:tpData];
CGSize tpSize = tpImg.size;
UIImage *newImg = [self scaleToSize:tpImg size:CGSizeMake(tpSize.width*0.5, tpSize.height*0.5)];
tpData = UIImageJPEGRepresentation(newImg, 1);
dxLengh = [tpData length]/1024;
num = num + 1;
}
[message setThumbData:tpData];
WXWebpageObject *webpageObject = [WXWebpageObject object];
webpageObject.webpageUrl = _dataModel.url;
message.mediaObject = webpageObject;
SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
req.bText = NO;
req.message = message;
if (mark == 1) {
req.scene = WXSceneTimeline;
} else {
req.scene = WXSceneSession;
}
[WXApi sendReq:req];
}
/// 压缩图片大小 并不是截取图片而是按照size绘制图片
- (UIImage*)scaleToSize:(UIImage*)img size:(CGSize)size {
// 创建一个基于位图的上下文(context),并将其设置为当前上下文(context)
UIGraphicsBeginImageContext(size);
// 绘制改变大小的图片
[img drawInRect:CGRectMake(0, 0, size.width, size.height)];
// 从当前context中创建一个改变大小后的图片
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
// 保存图片
// UIImageWriteToSavedPhotosAlbum(scaledImage, nil, nil, nil);
return scaledImage;
}
网友评论