图片选择库相机-相册

Android图片转换为Base64编码

2019-09-16  本文已影响0人  NoBugException

假如服务器需要拿到客户端的图片数据,有两种方法可以实现:

本文就重点讲解一下图片转Base64

Android在util包中提供了android.util.Base64类,该类提供了四个编码方法,分别是:

public static byte[] encode(byte[] input, int flags)
public static byte[] encode(byte[] input, int offset, int len, int flags)
public static String encodeToString(byte[] input, int flags)
public static String encodeToString(byte[] input, int offset, int len, int flags)

提供了三个解码

public static byte[] decode(String str, int flags)
public static byte[] decode(byte[] input, int flags)
public static byte[] decode(byte[] input, int offset, int len, int flags)

我们发现,四个编码方法都有一个flags参数,这就是编码标志位,或者编码标准。

编码标准有以下几种:

Win风格的换行符,意思就是使用CR和LF这一对作为一行的结尾而不是Unix风格的LF。

CRLF是Carriage-Return Line-Feed的缩写,意思是回车(\r)换行(\n)。

也就是说,Window风格的行结束标识符是\r\n,Unix风格的行结束标识符是\n。
这个参数是默认,使用默认的方法来加密
这个参数是略去加密字符串最后的“=”
这个参数意思是略去所有的换行符(设置后CRLF就没用了)
这个参数意思是加密时不使用对URL和文件名有特殊意义的字符来作为加密字符,具体就是以-和_取代+和/。
通常与`Base64OutputStream`一起使用,是传递给`Base64OutputStream`的标志指示它不应关闭正在包装的输出流。

图片转Base64代码如下:

/**
 * 将图片转换成Base64编码的字符串
 */
public static String imageToBase64(String path){
    if(TextUtils.isEmpty(path)){
        return null;
    }
    InputStream is = null;
    byte[] data = null;
    String result = null;
    try{
        is = new FileInputStream(path);
        //创建一个字符流大小的数组。
        data = new byte[is.available()];
        //写入数组
        is.read(data);
        //用默认的编码格式进行编码
        result = Base64.encodeToString(data,Base64.NO_CLOSE);
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        if(null !=is){
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return result;
}

Base64转图片代码如下:

/**
 * 将Base64编码转换为图片
 * @param base64Str
 * @param path
 * @return true
 */
public static boolean base64ToFile(String base64Str,String path) {
    byte[] data = Base64.decode(base64Str,Base64.NO_WRAP);
    for (int i = 0; i < data.length; i++) {
        if(data[i] < 0){
            //调整异常数据
            data[i] += 256;
        }
    }
    OutputStream os = null;
    try {
        os = new FileOutputStream(path);
        os.write(data);
        os.flush();
        os.close();
        return true;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    }catch (IOException e){
        e.printStackTrace();
        return false;
    }
}

[本章完...]

上一篇 下一篇

猜你喜欢

热点阅读