android图片转字节,android图片和二进制数组的相互转换

// 把图片转化为二进制数组

public synchronized byte[] drawableToByte(Drawable drawable)

{

if (drawable != null) {

Bitmap bitmap = Bitmap

.createBitmap(

drawable.getIntrinsicWidth(),

drawable.getIntrinsicHeight(),

drawable.getOpacity() != PixelFormat.OPAQUE ?

Bitmap.Config.ARGB_8888

: Bitmap.Config.RGB_565);

Canvas canvas = new Canvas(bitmap);

drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),

drawable.getIntrinsicHeight());

drawable.draw(canvas);

int size = bitmap.getWidth() * bitmap.getHeight() * 4;

// 创建一个字节数组输出流,流的大小为size

ByteArrayOutputStream baos = new

ByteArrayOutputStream(size);

// 设置位图的压缩格式,质量为100%,并放入字节数组输出流中

bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);

// 将字节数组输出流转化为字节数组byte[]

byte[] imagedata = baos.toByteArray();

return imagedata;

}

return null;

}

//从数据库中读取出来的二进制数组转化图片

public Bitmap getBitmapFromByte(byte[] temp){

if(temp != null){

Bitmap bitmap =

BitmapFactory.decodeByteArray(temp, 0, temp.length);

return bitmap;

}else{

return null;

}

}

你可能感兴趣的:(android图片转字节)