Mohsen Morshedi
Mohsen Morshedi

Reputation: 183

convert base64 string to byte array in android

I receive a binary base64 image as a string via a json array in my application. I want to convert this string to a byte array and show it in my application as an image.

This is what I came up with:

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

The variable image is the base64 string that I receive from the json array.

Upvotes: 1

Views: 11460

Answers (2)

Vlad
Vlad

Reputation: 385

String to GZIP and GZIP to String, full 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));
}}

for call

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

Upvotes: 1

pez
pez

Reputation: 4235

Use this Apache Commons Codec in your project.

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

Or use Sun's options:

import sun.misc.BASE64Decoder;

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

Upvotes: 3

Related Questions