android 中bitmap与String(base64) byte[]、和drawable的互相转换

  • Post author:
  • Post category:其他


记录下bitmap与String(base64) byte[]、和drawable之间的转换

参考博客:

http://blog.csdn.net/bear_huangzhen/article/details/47168123

bitmap转base64格式的字符串

/**
     * 将bitmap转为base64格式的字符串
     * @param bit 传入的bitmap
     * @return 
     */
    public String BitmapToStrByBase64(Bitmap bit){
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 100, bos);//参数100表示不压缩
        byte[] bytes=bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

base64格式的字符串转bitmap

public static Bitmap base64ToBitmap(String base64Data) {  
    byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);  
    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);  
    return bitmap;
}  

bitmap转byte[]数组

     /** 
     * bitmap 转  byte[]数组 
     */  
    public byte[] bitmapTobyteArray(Bitmap bitmap){  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);  
        byte[] bytes = baos.toByteArray();  
        return bytes;  
    }  

byte[]转bitmap

     /** 
     * byte[]数组   转   bitmap 
     */  
    public Bitmap byteArrayToBitmap(byte[] bytes){  
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);  
        return bitmap;  
    } 

bitmap转drawable

      /** 
     * bitmap 转  Drawable 
     */  
    public Drawable bitmapToDrawable(Bitmap bitmap){  
        BitmapDrawable bd = new BitmapDrawable(bitmap);  
        Drawable img = bd;  
        return img;  
    }  

drawable转bitmap

    /** 
     * Drawable 转  bitmap 
     */  
    public Bitmap drawableToBitmap(Drawable img){  
        BitmapDrawable bd = (BitmapDrawable) img;  
        Bitmap bitmap = bd.getBitmap();  
        return bitmap;  
    }