Android will perform some type conversion when processing a write image resource. Now I have time to sort it out:
1. drawable → bitmap
Java code
- Public static bitmap drawabletobitmap (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 );
- // Canvas. setbitmap (Bitmap );
- Drawable. setbounds (0, 0, drawable. getintrinsicwidth (), drawable. getintrinsicheight ());
- Drawable. Draw (canvas );
- Return bitmap;
- }
2. Obtain bitmap from a resource
Java code
- Resources res = getresources ();
- Bitmap BMP = bitmapfactory. decoderesource (Res, R. drawable. PIC );
3. Bitmap → byte []
Java code
- Private byte [] bitmap2bytes (Bitmap BM ){
- Bytearrayoutputstream baos = new bytearrayoutputstream ();
- BM. Compress (bitmap. compressformat. PNG, 100, baos );
- Return baos. tobytearray ();
- }
4. byte [] → bitmap
Java code
- Private bitmap bytes2bimap (byte [] B ){
- If (B. length! = 0 ){
- Return bitmapfactory. decodebytearray (B, 0, B. Length );
- }
- Else {
- Return NULL;
- }
- }
The above are some of the transformations I have encountered in practice. In the future, we don't need to look around for similar conversions. I hope they will be of some use to everyone!