Reputation:
I convert bitmap to byte array and byte array to bitmap but when I have to show converted byte array in ImageView then it will show image with black corners not show in PNG format. I want to show image in PNG format, how can I do that??
Here is a code for bitmap to byte array conversion and byte array to bitmap:
Bitmap into byte array in PNG compressed format:
public byte[] convertBitmapToByteArray(Bitmap bitmap) {
ByteArrayOutputStream stream = null;
try {
stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.e(Helper.class.getSimpleName(), "ByteArrayOutputStream was not closed");
}
}
}
}
and convert byte array to bitmap as:
BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
Upvotes: 3
Views: 9300
Reputation: 1
use this code:
public String convertBitmapToString(Bitmap bmp){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream); //compress to which format you want.
byte[] byte_arr = stream.toByteArray();
String imageStr = Base64.encodeBytes(byte_arr);
return imageStr;
}
Upvotes: 0
Reputation: 9188
Try this code
//For encoding toString
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = android.util.Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
//For decoding
String str=encodedImage;
byte data[]= android.util.Base64.decode(str, android.util.Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
Upvotes: 10