很有可能是图片太大,或者有敏感词。
关于图片太大的话,可以让UI切个小的图片。
或者自己用代码压缩。
先记录一下:
首先用Glide下载下来图片。
1、把Drawable转换成Bitmap。
public static Bitmap drawableToBitmap(Drawable drawable) {
// 获取 drawable 长宽
int width = drawable.getIntrinsicWidth();
int heigh = drawable.getIntrinsicHeight();
drawable.setBounds(0, 0, width, heigh);
// 获取drawable的颜色格式
Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
// 创建bitmap
Bitmap bitmap = Bitmap.createBitmap(width, heigh, config);
// 创建bitmap画布
Canvas canvas = new Canvas(bitmap);
// 将drawable 内容画到画布中
drawable.draw(canvas);
return bitmap;
}
2、把Bitmap转换数组。
public byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 32, output);
if (needRecycle) {
bmp.recycle();
}
byte[] result = output.toByteArray();
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
3、对Bitmap数组进行宽高尺寸压缩。
private static Bitmap calculateInSampleSize( byte[] bitmapBytes,int reqWidth, int reqHeight) {
Bitmap bitmapT=null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);
int originalWidth = options.outWidth;
int originalHeight = options.outHeight;
int inSampleSize = 1;
if (originalHeight > reqHeight || originalWidth > reqHeight){
int halfHeight = originalHeight / 2;
int halfWidth = originalWidth / 2;
//压缩后的尺寸与所需的尺寸进行比较
while ((halfWidth / inSampleSize) >= reqHeight && (halfHeight /inSampleSize)>=reqWidth){
inSampleSize *= 2;
}
}
//获取采样率
options.inSampleSize =inSampleSize;
options.inJustDecodeBounds = false;
bitmapT=BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);
return bitmapT;
}
4、质量压缩。
public static byte[] qualityCompress1(Bitmap bitmap ,int reqSize){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//这里100表示不压缩,0 ~ 100 可以自行调整,把压缩后的数据存放到baos中
bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
int options = 95;
//如果压缩后的大小超出所要求的,继续压缩
while (baos.toByteArray().length / 1024 > reqSize){
baos.reset();
bitmap.compress(Bitmap.CompressFormat.JPEG,options,baos);
//每次减少5%质量
if (options>5){//避免出现options<=0
options -=5;
} else {
break;
}
}
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, options, bao);
return bao.toByteArray();
}
5、最后得到压缩后的Bitmap
bitmap =BitmapFactory.decodeByteArray(bytes2,0,bytes2.length);
菜鸟做此记录。
。如果有大神有更好的方法欢迎。
版权声明:本文为qq_35473951原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。