Drawable -作为Android平下通用的图形对象,它可以装载常用格式的图像,比如GIF、PNG、JPG,当然也支持BMP,当然还提供一些高级的可视化对象,比如渐变、图形等。
Bitmap -称作位图,一般位图的文件格式后缀为bmp,当然编码器也有很多如RGB565、RGB888。作为一种像素的显示对象执行效率高,但是缺点也很明显存储效率低。我们理解为一种存储对象比较好。
android在处理一写图片资源的时候,会进行一些类型的转换,现在有空整理一下:
1、Drawable → Bitmap 的简单方法
Drawable d = XXX;
BitmapDrawable bd =(BitmapDrawable)d;
Bitmap b =bd.getBitmap();
可简化为:((BitmapDrawable)res.getDrawable(R.drawable.youricon)).getBitmap();
Java代码
public static Bitmap drawableToBitmap(Drawable drawable){
Bitmap bitmap= Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ?Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); //按指定参数创建一个空的Bitmap对象
Canvas canvas= new Canvas(bitmap);
//canvas.setBitmap(bitmap);
drawable.setBounds(0,0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
drawable.draw(canvas);
returnbitmap;
}
3.Bitmap→Drawable 的简单方法
BitmapDrawable bitmapDrawable= (BitmapDrawable)bitmap;
Drawable drawable = (Drawable)bitmapDrawable;
Bitmap bitmap = newBitmap (...);
Drawable drawable = new BitmapDrawable(bitmap);
3、从资源中获取Bitmap
Java代码
Bitmap bmp=BitmapFactory.decodeResource(getResources(),R.drawable.pic);
4、Bitmap → Byte[]
Java代码
private byte[] Bitmap2Bytes(Bitmapbm){
ByteArrayOutputStream baos =new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
returnbaos.toByteArray();
}
5、 byte[] → Bitmap
Java代码
private Bitmap Bytes2Bimap(byte[]b){
if(b.length!=0){
returnBitmapFactory.decodeByteArray(b, 0,b.length);
}
else{
returnnull;