天天看點

Android開發之常用必備工具類圖檔bitmap轉成字元串string與String字元串轉換為bitmap圖檔格式...

作者:程式員小冰,

今天給大家提供一個常用的工具類。

Android開發之常用必備工具類圖檔bitmap轉成字元串string與String字元串轉換為bitmap圖檔格式

下面是代碼。當然最下面會分享出來源檔案。

下面是代碼:

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

/**
 * 微網誌:http://weibo.com/mcxiaobing
 * ============================================================================
 * 類名:Android開發之常用必備工具類圖檔bitmap轉成字元串string與String字元串轉換為bitmap圖檔格式
 * ----------------------------------------------------------------------------
 * 功能描述:Android開發之常用必備工具類圖檔bitmap轉成字元串string與String字元串轉換為bitmap圖檔格式
 * ----------------------------------------------------------------------------
 */
public class BitmapAndStringUtils {
    /**
     * 圖檔轉成string
     *
     * @param bitmap
     * @return
     */
    public static String convertIconToString(Bitmap bitmap)
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] appicon = baos.toByteArray();// 轉為byte數組
        return Base64.encodeToString(appicon, Base64.DEFAULT);

    }

    /**
     * string轉成bitmap
     *
     * @param st
     */
    public static Bitmap convertStringToIcon(String st)
    {
        // OutputStream out;
        Bitmap bitmap = null;
        try
        {
            // out = new FileOutputStream("/sdcard/aa.jpg");
            byte[] bitmapArray;
            bitmapArray = Base64.decode(st, Base64.DEFAULT);
            bitmap =
                    BitmapFactory.decodeByteArray(bitmapArray, 0,
                            bitmapArray.length);
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            return bitmap;
        }
        catch (Exception e)
        {
            return null;
        }
    }
}