SoFunction
Updated on 2025-04-10

Implementation code for converting android image types

This article describes the implementation code for converting android image types. Share it for your reference. The details are as follows:

When Android is processing image resources, it will perform some types of conversions. Now if you have time to organize it:

1、Drawable → Bitmap

The Java code is as follows:

public static Bitmap drawableToBitmap(Drawable drawable) { 
 Bitmap bitmap = Bitmap 
   .createBitmap( 
     (), 
     (), 
     () !=  ? .ARGB_8888 
       : .RGB_565); 
 Canvas canvas = new Canvas(bitmap); 
 //(bitmap); 
 (0, 0, (), ()); 
 (canvas); 
 return bitmap; 
} 
public static Bitmap drawableToBitmap(Drawable drawable) { 
 Bitmap bitmap = Bitmap 
   .createBitmap( 
     (), 
     (), 
     () !=  ? .ARGB_8888 
       : .RGB_565); 
 Canvas canvas = new Canvas(bitmap); 
 //(bitmap); 
 (0, 0, (), ()); 
 (canvas); 
 return bitmap; 
} 

2. Get Bitmap from resources

The Java code is as follows:

Resources res=getResources(); 
Bitmap bmp=(res, ); 
Resources res=getResources(); 
Bitmap bmp=(res, ); 

3、Bitmap → byte[]

The Java code is as follows:

private byte[] Bitmap2Bytes(Bitmap bm){ 
 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
 (, 100, baos); 
 return (); 
} 
private byte[] Bitmap2Bytes(Bitmap bm){ 
 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
 (, 100, baos); 
 return (); 
} 

4、 byte[] → Bitmap

The Java code is as follows:

private Bitmap Bytes2Bimap(byte[] b){ 
  if(!=0){ 
  return (b, 0, ); 
  } 
  else { 
  return null; 
  } 
} 
private Bitmap Bytes2Bimap(byte[] b){ 
  if(!=0){ 
  return (b, 0, ); 
  } 
  else { 
  return null; 
  } 
}

The above are some of the transformations I encountered in practice. In the future, I don’t need to look for similar things.

I hope this article will be helpful to everyone's Android programming design.