APP开发过程多数是分享URL/Text,但是也有客户会提出截屏后分享出去。
分享图片代码如下:
- (void)WXSendImage:(UIImage *)image withShareScene:(enum WXScene)scene {
if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]) {
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentPath stringByAppendingPathComponent:@"ocr.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 1);
[imageData writeToFile:filePath atomically:NO];
UIImage *thumbImage = [UIImage imageWithData:UIImageJPEGRepresentation(image, 0.5)];
WXImageObject *ext = [WXImageObject object];
// 小于10MB
ext.imageData = imageData;
WXMediaMessage *message = [WXMediaMessage message];
message.mediaObject = ext;
// message.messageExt = @"";
// message.messageAction = @"";
// message.mediaTagName = @"";
// 缩略图 小于32KB
[message setThumbImage:thumbImage];
SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
req.bText = NO;
req.scene = scene;
req.message = message;
[WXApi sendReq:req];
}else {
// 提示用户安装微信
}
}
或者看一下微信开放平台上的写法
切记缩略图要小于32KB,否则无法调起微信,而微信也没有返回错误信息,只是[WXApi sendReq:req]=NO,
上述压缩方法有时候是小于32KB,有的时候不满足。
更为安全的方法如下(可以将image压缩到指定大小):
将代码
UIImage *thumbImage = [UIImage imageWithData:UIImageJPEGRepresentation(image, 0.5)];
替换为
UIImage *thumbImage = [self compressImage:image toByte:32768];
// (图片压缩的代码也可以封装到工具类中)
#pragma mark - 压缩图片
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
// Compress by quality
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength) return image;
CGFloat max = 1;
CGFloat min = 0;
for (int i = 0; i < 6; ++i) {
compression = (max + min) / 2;
data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength * 0.9) {
min = compression;
} else if (data.length > maxLength) {
max = compression;
} else {
break;
}
}
UIImage *resultImage = [UIImage imageWithData:data];
if (data.length < maxLength) return resultImage;
// Compress by size
NSUInteger lastDataLength = 0;
while (data.length > maxLength && data.length != lastDataLength) {
lastDataLength = data.length;
CGFloat ratio = (CGFloat)maxLength / data.length;
CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
(NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
UIGraphicsBeginImageContext(size);
[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
data = UIImageJPEGRepresentation(resultImage, compression);
}
return resultImage;
}
使用方法:
使用的时候直接传image及最大的字节数即可:32KB = 32*1024B=32678,结果返回压缩之后的image。
如果分享仍然失败,那你需要考虑一下是否是SDK版本低,pod install即可。