作者:锦瑟城门 | 来源:互联网 | 2023-05-19 04:44
android在处理一写图片资源的时候,会进行一些类型的转换,现在有空整理一下:1、Drawable→Bitmap[java]viewplaincopypublicstaticBitmap
android在处理一写图片资源的时候,会进行一些类型的转换,现在有空整理一下:
1、Drawable → Bitmap
[java] view plaincopy
- 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);
- Canvas canvas = new Canvas(bitmap);
-
- drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
- drawable.draw(canvas);
- return bitmap;
- }
2、从资源中获取Bitmap
[java] view plaincopy
- Resources res=getResources();
-
- Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
3、Bitmap → byte[]
[java] view plaincopy
- private byte[] Bitmap2Bytes(Bitmap bm){
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
- return baos.toByteArray();
- }
4、 byte[] → Bitmap
[java] view plaincopy
- private Bitmap Bytes2Bimap(byte[] b){
- if(b.length!=0){
- return BitmapFactory.decodeByteArray(b, 0, b.length);
- }
- else {
- return null;
- }
- }
5.
很多开发者表示,不知道Android的Drawable和Bitmap之间如何相关转换。下面Android123给大家两种比较简单高效的方法。
一、Bitmap转Drawable
Bitmap bm=xxx; //xxx根据你的情况获取
BitmapDrawable bd=BitmapDrawable(bm);
Android开发网提示因为BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。
二、 Drawable转Bitmap
转成Bitmap对象后,可以将Drawable对象通过Android的SK库存成一个字节输出流,最终还可以保存成为jpg和png的文件。
Drawable d=xxx; //xxx根据自己的情况获取drawable
BitmapDrawable bd = (BitmapDrawable) d;
Bitmap bm = bd.getBitmap();
最终bm就是我们需要的Bitmap对象了。