将byte[]数组数据转换为图片用于预览显示

时间:2023-03-08 22:42:29

假如服务器返回给你的图片信息是byte[] 然后你需要将起转换成图片显示到你的view中去:

按以下的步骤

1.将获取的byte数组保存 假如为temp[];

2.将temp[]转化为bitmap,你可以使用下面的这个方法 :

/**
* 将字节数组转换为ImageView可调用的Bitmap对象
* @param bytes
* @param opts 转换属性设置
* @return
**/ public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) { if (bytes != null) if (opts != null)
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
else return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return null; }

  

  

  其中的这个Options是BitmapFactory.Options 大致功能就是设置你转换成bitmap的属性(大小 宽 高 编码格式 预览 等),为了防止图片过大导致oom我们可以获取预览就可以了:

  

BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2;

 3.这样你把这个opts传入上面的函数中,我们获取的bitmap 就是原图的1/4大小了。如果你还需要缩放成固定的宽高来使用 下面提供一个缩放方法:

/**
* @param 图片缩放
* @param bitmap 对象
* @param w 要缩放的宽度
* @param h 要缩放的高度
* @return newBmp 新 Bitmap对象
*/ public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
return newBmp;
}

  这样就能获取到你想要的高度和宽度的图片 是不是很方便呢