Android将drawable图像转化为二进制字节数组与逆转换

          首先是将图像转换为二进制字节数组进行存储

// ------------------------将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;

	}

 
  

这个方法应该在开发中会经常用到,留给大家吧!

你可能感兴趣的:(Android将drawable图像转化为二进制字节数组与逆转换)