首先是將圖像轉換爲二進制字節數組進行存儲
// ------------------------將drawable 圖像轉化成二進制字節----------------
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;
}
下面是將二進制字節數組進行轉換爲drawable圖像 對象.
public synchronized Drawable byteToDrawable(byte[] img) {
Bitmap bitmap;
if (img != null) {
bitmap = BitmapFactory.decodeByteArray(img,0, img.length);
Drawable drawable = new BitmapDrawable(bitmap);
return drawable;
}
return null;
}
這個方法應該在開發中會經常用到,留給大家吧!