转换Bitmap对象
Posted Yi米阳光
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了转换Bitmap对象相关的知识,希望对你有一定的参考价值。
把一个View转换bitmap对象
1 public static Bitmap getViewBitmap(View view) { 2 view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), 3 View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); 4 view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight()); 5 view.buildDrawingCache(); 6 Bitmap bitmap = view.getDrawingCache(); 7 return bitmap; 8 }
根据已有的Drawable创建一个新的Bitmap:
1 private Bitmap bitmap; 2 private void drawableToBitamp(Drawable drawable) 3 { 4 int w = drawable.getIntrinsicWidth(); 5 int h = drawable.getIntrinsicHeight(); 6 System.out.println("Drawable转Bitmap"); 7 Bitmap.Config config = 8 drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 9 : Bitmap.Config.RGB_565; 10 bitmap = Bitmap.createBitmap(w,h,config); 11 //注意,下面三行代码要用到,否在在View或者surfaceview里的canvas.drawBitmap会看不到图 12 Canvas canvas = new Canvas(bitmap); 13 drawable.setBounds(0, 0, w, h); 14 drawable.draw(canvas); 15 }
直接从现有的Drawable中取出Bitmap:
1 private Bitmap bitmap; 2 3 private void drawableToBitamp(Drawable drawable) 4 { 5 BitmapDrawable bd = (BitmapDrawable) drawable; 6 bitmap = bd.getBitmap(); 7 }
Bitmap转Byte
1 private byte[] Bitmap2Bytes(Bitmap bm){ 2 3 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 4 5 bm.compress(Bitmap.CompressFormat.PNG, 100, baos); 6 7 return baos.toByteArray(); 8 }
byte[] 转Bitmap:
1 private Bitmap Bytes2Bimap(byte[] b){ 2 3 if(b.length!=0){ 4 5 return BitmapFactory.decodeByteArray(b, 0, b.length); 6 7 } 8 9 else { 10 11 return null; 12 13 } 14 15 }
以上是关于转换Bitmap对象的主要内容,如果未能解决你的问题,请参考以下文章
如何将Canvas 上的内容转换为一张Bitmap-Android开发问答
Android 图片Bitmap,drawable,res资源图片之间转换
从 VB 转换为 C#:bitmap.save() 参数错误