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

convert base64 string to byte array in android

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

这是我想出的:

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

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

在你的项目中使用这个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();
}

字符串转 GZIP 和 GZIP 转字符串,完整 class

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());
    }