Android 微信分享(超详细)-解决图片处理问题
最近公司要原生微信分享功能,楼主想哎呀不就是微信分享嘛做就是了,谁知道巨坑啊!
微信分享规则
- 针对微信分享时需要压缩图片到较小的图片尺寸 并且需要设置缩略32k的限制. (注意:必须是32k的图片)
分享
这里就不浪费时间说什么导入sdk什么的了 官网都有说明
一、获取bitmap图片
这里我主要是获取网络图片转成bitmap的,我使用的是 Glide转成bitmap(楼主比较菜只能这样了,哈哈)当然你也可以试试其他的网络图片转Bitmap方法。
//1
Glide.with(mContext).asBitmap().load(fitnessBean.getFitnessIndexImg()).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//2
Bitmap thumbBmp = null;
if (resource.getHeight()>100 && resource.getWidth()>100) {
thumbBmp = Bitmap.createScaledBitmap(resource, 100, 100, true);
}else {
thumbBmp = resource;
}
if (thumbBmp != null) {
dismissLoading();
DialogUtils.shareDailog(mContext, url, "标题", "内容", thumbBmp);
} else {
dismissLoading();
ToastUtils.showShort("获取分享图片失败");
}
}
});
二、将bitmap对象转化成byte数据字节
public static byte[] bitmapBytes(final Bitmap bmp, final boolean needRecycle) {
int i;
int j;
if (bmp.getHeight() > bmp.getWidth()) {
i = bmp.getWidth();
j = bmp.getWidth();
} else {
i = bmp.getHeight();
j = bmp.getHeight();
}
Bitmap localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565);
Canvas localCanvas = new Canvas(localBitmap);
while (true) {
localCanvas.drawBitmap(bmp, new Rect(0, 0, i, j), new Rect(0, 0,i, j), null);
if (needRecycle)
bmp.recycle();
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
localBitmap.compress(Bitmap.CompressFormat.JPEG, 100,
localByteArrayOutputStream);
localBitmap.recycle();
byte[] arrayOfByte = localByteArrayOutputStream.toByteArray();
try {
localByteArrayOutputStream.close();
return arrayOfByte;
} catch (Exception e) {
//F.out(e);
}
i = bmp.getHeight();
j = bmp.getHeight();
}
}
三、微信分享配置
/**
* 微信分享
* @param mContext
* @param url 地址
* @param title 标题
* @param desc 介绍
* @param isFriends朋友圈或好友
* @param img 图片
*/
public static void wxShare(Context mContext, String url, String title, String desc, boolean isFriends, Bitmap img) {
WXWebpageObject webpage = new WXWebpageObject();
webpage.webpageUrl = url;
WXMediaMessage msg = new WXMediaMessage(webpage);
msg.title = title;
msg.description = desc;
msg.thumbData = bitmapBytes(img,true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = String.valueOf(System.currentTimeMillis());
req.message = msg;
req.scene = friendsCircle ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
BaseApp.mWxApi.sendReq(req);
}
四、疑难杂症
如果你遇到这样的错误checkArgs fail, thumbData is invalid
那么恭喜你是你的图片大于32kb,微信demo里边图片处理好像是有问题的解决办法发可以参照上文。
五、参考博客
https://www.cnblogs.com/wsfjlagr/p/3711796.html
此解决方案,供大家参考如有不对的地方可以提出来一起解决