Decode large base64 string

android, base64

Solution

You need decode the image in Background thread like AsyncTask or you need reduce your image quality using BitmapFactory . Example:

 BitmapFactory.Options options = new BitmapFactory.Options();

            options.inSampleSize = 2;
            options.inPurgeable=true;
        Bitmap bm = BitmapFactory.decodeFile("Your image exact loaction",options);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object 

        byte[] b = baos.toByteArray(); 
        String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);

Problem

I have created a base64 string from a picture on the SD card using this(below) code, and it works but when I try to decode it (even further below) I get a `java.lang.outOfMemoryException`, presumably because I am not splitting the string into a reasonable size before I decode it as I am before I encode it. ``` byte fileContent[] = new byte[3000]; StringBuilder b = new StringBuilder(); try{ FileInputStream fin = new FileInputStream(sel); while(fin.read(fileContent) >= 0) { b.append(Base64.encodeToString(fileContent, Base64.DEFAULT)); } }catch(IOException e){ } ``` The above code works well, but the problem comes when I try to decode the image with the following code; ``` byte[] imageAsBytes = Base64.decode(img.getBytes(), Base64.DEFAULT); ImageView image = (ImageView)this.findViewById(R.id.ImageView); image.setImageBitmap( BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length) ); ``` I have tried this way too ``` byte[] b = Base64.decode(img, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length); image.setImageBitmap(bitmap); ``` Now I assume that I need to split the string up into sections like my image encoding code, but I have no clue how to go about doing it.

Original source