将base64字符串转换为android中的字节数组

时间:2015-07-25 17:12:54

标签: android base64 byte bytearray

我通过应用程序中的json数组接收二进制base64图像作为字符串。 我想将此字符串转换为字节数组,并将其作为图像显示在我的应用程序中。

这就是我提出的:

byte[] data = Base64.decode(image, Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
thumbNail.setImageBitmap(bmp);

变量image是我从json数组接收的base64字符串。

2 个答案:

答案 0 :(得分:2)

在项目中使用此Apache Commons Codec

byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(imageString.getBytes()); 

或使用Sun的选项:

import sun.misc.BASE64Decoder;

byte[] byte;
try 
{
    BASE64Decoder decoder = new BASE64Decoder();
    byte = decoder.decodeBuffer(imageString);
} 
catch (Exception e) 
{
    e.printStackTrace();
}

答案 1 :(得分:0)

GZIP和GZIP到String的字符串,完整的类

class GZIPCompression {
static String compress(String string) throws IOException {
    if ((string == null) || (string.length() == 0)) {
        return null;
    }
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);
    gzip.write(string.getBytes("UTF-8"));
    gzip.flush();
    gzip.close();
    return Base64.encodeToString(obj.toByteArray(), Base64.DEFAULT);
}

static String decompress(String compressed) throws IOException {
    final StringBuilder outStr = new StringBuilder();
    byte[] b = Base64.decode(compressed, Base64.DEFAULT);
    if ((b == null) || (b.length == 0)) {
        return "";
    }
    if (isCompressed(b)) {
        final GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(b));
        final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gis, "UTF-8"));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            outStr.append(line);
        }
    } else {
        return "";
    }
    return outStr.toString();
}

private static boolean isCompressed(final byte[] compressed) {
    return (compressed[0] == (byte) (GZIPInputStream.GZIP_MAGIC)) && (compressed[1] == (byte) (GZIPInputStream.GZIP_MAGIC >> 8));
}}

致电

// test compress
    String strzip="";
    try {
        String str = "Main TEST";
        strzip=GZIPCompression.compress(str);
    }catch (IOException e){
        Log.e("test compress", e.getMessage());
    }
    //test decompress
    try {
        Log.e("src",strzip);
        strzip = GZIPCompression.decompress(strzip);
        Log.e("decompressed",strzip);
    }catch (IOException e){
        Log.e("test decompress", e.getMessage());
    }