在和服务器交互的过程中,有时候我们需要把图片编码成base64字符串传输,记录一下工具类

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

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class Base64Util {
    /**
     * 图片转化为base 64字符串
     *
     * @param imgUrl
     * @return
     */
    public static String imgEncode(String imgUrl) {
        if (EmptyUtil.isNotEmpty(imgUrl)) {
            byte[] bytes = new byte[0];

            try {
                FileInputStream fis = new FileInputStream(imgUrl);
                bytes = new byte[fis.available()];
                fis.read(bytes);
                fis.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return Base64.encodeToString(bytes, Base64.NO_WRAP);

        } else {
            return "";
        }
    }

    /**
     * 解码base64字符串
     *
     * @param imgBase64Str
     * @return
     */
    public static byte[] decodeImg(String imgBase64Str) {
        byte[] bytes = new byte[0];
        if (EmptyUtil.isNotEmpty(imgBase64Str)) {
            bytes = Base64.decode(imgBase64Str, Base64.DEFAULT);
        }
        return bytes;
    }


    /**
     * bitmap 转化为Base64字符串
     *
     * @param bitmap
     * @return
     */
    public static String Bitmap2Base64Str(Bitmap bitmap) {
        ByteArrayOutputStream baos = null;
        if (EmptyUtil.isNotEmpty(bitmap)) {
            try {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                baos.flush();
                byte[] bitmapBytes = baos.toByteArray();
                return Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return "";
        }
        return "";
    }

    /**
     * byte转化为Bitmap
     *
     * @param b
     * @return
     */
    public static Bitmap bytes2Bitmap(byte[] b) {
        if (EmptyUtil.isNotEmpty(b)) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        }
        return null;
    }
}