这是友盟提供的压缩方法,但是还是会有点慢,所以我们自己去压缩图片。
new Thread(new Runnable() {
@Override
public void run() {
String picUrl = goodsDetailsBean.getData().getPro_Info().get(0).get商品图片().split("\\|")[0];
Bitmap bitmap ;
if(!picUrl.equals("")){
bitmap = PhotoBitmapUtils.create(picUrl);
}else{
bitmap = BitmapFactory.decodeResource(SafShopDetailActivity.this.getResources(), R.drawable.accountdefault);
}
Message msg = new Message();
msg.what = SHARE;
msg.obj = bitmap;
mHandler.sendMessage(msg);
}
}).start();
//根据url生成bitmap,需要在子线程中调用
public static Bitmap create(String path) {
Bitmap bit = null;
try {
URL url1 = new URL(path);
InputStream is1 = url1.openStream();
bit = BitmapFactory.decodeStream(is1);
} catch (IOException e) {
e.printStackTrace();
}
return bit;
}
//压缩图片
public static Bitmap compression(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 90;
while (baos.toByteArray().length / 1024 > 128) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset(); // 重置baos即清空baos
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
options -= 10;// 每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
return bitmap;
}
//最后直接调用
UMImage image = new UMImage(activity, compression((Bitmap) msg.obj)));
UMImage imageThumb = new UMImage(activity, compression((Bitmap) msg.obj)));
image.setThumb(imageThumb);
image.compressStyle = UMImage.CompressStyle.SCALE;//大小压缩,默认为大小压缩,适合普通很大的图
//image.compressStyle = UMImage.CompressStyle.QUALITY;//质量压缩,适合长图的分享压缩格式设置
//image.compressFormat = Bitmap.CompressFormat.PNG;//用户分享透明背景的图片可以设置这种方式,但是qq好友,微信朋友圈,不支持透明背景图片,会变成黑色
new ShareAction(activity).setPlatform(platform)
.setCallback(mShareListener)
.withMedias(image)
.share();