Sam-In-TechValens
Sam-In-TechValens

Reputation: 2519

Not able to convert Bitmap to perfect Base64 String in Android?

I am working on an application in which I need to capture an Image from camera. After capture, I have to convert the Bitmap to Base64. After converting to Base64, I have to send that String to SERVER. I am using below code for this task:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
base64Image = Base64.encodeToString(b,Base64.DEFAULT);

Problem : When I convert that Base64 to image, I am getting INCOMPLETE IMAGE. The same result is happening over server where my image is not perfectly re-constructed from Base64 String.

Please suggest me the solution. I have already search a-lot and getting same code which I am using right now.

Edited: please see the below incomplete Image

enter image description here

Code use to capture the Image:

intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, TAKE_PHOTO);

Upvotes: 12

Views: 9049

Answers (2)

Yakov
Yakov

Reputation: 481

Ok, i solved it. the problem was in the storing of the base64 string on the database. my column was declare as "TEXT" and it cuts the other picture's parts because the lenght of the string. so i changes it to "LONGTEXT" and now it's work perfectly!

Upvotes: 3

Francesco Vadicamo
Francesco Vadicamo

Reputation: 5542

When I convert that Base64 to image, I am getting INCOMPLETE IMAGE

Try to do this with your image Bitmap and check if something is not as expected:

Bitmap originalBitmap = (Bitmap) data.getExtras().get("data"); //or whatever image you want
Log.d(TAG, "original bitmap byte count: " + originalBitmap.getByteCount());

ByteArrayOutputStream baos = new ByteArrayOutputStream();
originalBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
Log.d(TAG, "byte array output stream size: " + baos.size());

byte[] outputByteArray = baos.toByteArray();
Log.d(TAG, "output byte array length: " + outputByteArray.length);

String base64EncodedString = Base64.encodeToString(outputByteArray, Base64.DEFAULT);
Log.d(TAG, "base64 encoded string length: " + base64EncodedString.length());

byte[] inputByteArray = Base64.decode(base64EncodedString, Base64.DEFAULT);
Log.d(TAG, "input byte array length: " + inputByteArray.length);

ByteArrayInputStream bais = new ByteArrayInputStream(inputByteArray);
Log.d(TAG, "byte array input stream size: " + bais.available());

Bitmap decodedBitmap = BitmapFactory.decodeStream(bais);
Log.d(TAG, "decoded bitmap byte count: " + decodedBitmap.getByteCount());

Log.d(TAG, "decoded bitmap same as original bitmap? " + decodedBitmap.sameAs(originalBitmap));

If all is ok then the problem is not the base64 encoding. Let me know!

Upvotes: 0

Related Questions