Bitmap toString and back again - android

in android I took a picture by the cam and returnded it to my activity:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Constatnts.ANSWER_TO_LIFE_UNIVERSE_AND_EVERYTHING && data != null && data.getExtras() != null && data.getExtras().get("data") != null) {
Bitmap snapshot = (Bitmap) data.getExtras().get("data");
String convert = InputOutput.bitmapToString(this, snapshot);
Bitmap back = InputOutput.stringToBitmap(convert);
}
}
When I assign the Bitmap 'snapshot' to an imageview it loosk pretty good an works well. But when I assign the Bitmap 'back" to an imageview it does not change its view. So there must be something wrong in transformation. Here is my code for the tranformation:
public static Bitmap stringToBitmap(String bitmapString) {
byte[] bytes = Base64.decode(bitmapString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return bitmap;
}
public static String bitmapToString(Context context, Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
bitmap.recycle();
byte[] byteArray = stream.toByteArray();
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
stream.write(byteArray, 0, byteArray.length);
stream = null;
String strBase64 = Base64.encodeToString(byteArray, Base64.URL_SAFE);
return strBase64;
}
Any suggestions what goes wrong here? Thanks!

Here's a code I used once to try this conversion, it should work:
public final static String bitmapToString(Bitmap in){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
in.compress(Bitmap.CompressFormat.PNG, 100, bytes);
return Base64.encodeToString(bytes.toByteArray(),Base64.DEFAULT);
}
public final static Bitmap stringToBitmap(String in){
byte[] bytes = Base64.decode(in, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
You might want to add some close() calls to the streams though.

Related

Camera base64 image cannot be converted to Bitmap

I have been having trouble converting the base64 String Image that is being sent to me by the backend.
So this is how the backend sends the data.
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
And this is how we convert it.
final byte[] data = Base64.decode(base64, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(data, 0, data.length);
The result is always null. Any help is highly appreciated.
EDIT:
These are the back end codes.
#Override
public BufferedImage base64ToImage(String base64Image) throws IOException {
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
return img;
}
public static String imgToBase64String(final RenderedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString();
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
And this is our converting tool before sending the Base64 Image String to the back end.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP);
Check that ur base64 encoded string does not start with data:image/jpg;base64,. If it does then remove it. The Base64.decode won't be able to decode it in this case. u can remove it by using encodedString.substring(encodedString.indexOf(",") + 1);. Let me know if this solves ur problem.
Try this,
ImageView driverImage = (ImageView) driverReportView.findViewById(R.id.imgViewDriverImage);
try {
byte [] encodeByte = Base64.decode(driverImageString.replace("\'/", "/"), Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
if (bitmap != null)
driverImage.setImageBitmap(bitmap);
}catch (Exception ex){
Log.e(TAG,"Error to display driver info "+ex.toString());
}
Where
driverImageString is your image string

Issue in Covert from String Base64 to Bitmap

Code stuff for convert from Bitmap to String Base64
Bitmap thumbnail = extras.getParcelable("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, baos);
thumbnail.recycle();
byte[] b = baos.toByteArray();
String attachment = Base64.encodeToString(b, Base64.DEFAULT);
Code stuff for convert from String Base64 to Bitmap
byte[] encodeByte = Base64.decode(strBase64, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
imageView.setImageBitmap(bitmap);
but i get bitmap = null;
I also refer Base64 to Bitmap to display in ImageView
Thanks in advance.
// convert Bitmap to String
public static String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] arr = baos.toByteArray();
imageData = Base64.encodeToString(arr, Base64.DEFAULT);
return imageData;
}
// Convert String to Bitmap
public static Bitmap StringToBitMap(String image) {
try {
byte[] encodeByte = Base64.decode(image, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
You are calling thumbnail.recycle(); after loading bitmap,, either remove it or call before loading bitmap

Array of bytes from View in android

I have a drawing view, and i am trying to get array of bytes from that view on button click
this is my code:
public void onClick(
drawView.setDrawingCacheEnabled(true);
String imgSaved = MediaStore.Images.Media.insertImage(
getContentResolver(), drawView.getDrawingCache(),
UUID.randomUUID().toString() + ".png", "drawing");
}
}
please help!
If view is ImageView first convert into bitmap then convert into byte array
Convert ImageView to Bitmap
public static Bitmap getImageViewAsBitmap(ImageView imageView) {
imageView.buildDrawingCache();
Bitmap bmap = imageView.getDrawingCache();
return bmap;
}
Convert Bitmap to Byte Array
public byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
Convert Byte Array to Bitmap
public static Bitmap getByteArrayAsBitmap(byte[] bitmap) {
Bitmap bm = null;
try {
bm = BitmapFactory.decodeStream(new ByteArrayInputStream(bitmap));
} catch (Exception e) {
}
return bm;
}
To call these methods like that:
provide imageview give bitmap
Bitmap m1Bitmap= getImageViewAsBitmap(myimageView);
provide bitmap give byte array
byte[] mbyteArray =getBitmapAsByteArray(mBitmap);
provide byte array give bitmap
Bitmap m2Bitmap= getByteArrayAsBitmap(byte[] bitmap);

How to Save Images In Database (SQLite) and load it to View : Android

How To Save Images In Database And Reload It To View In Image View?
Don't Save Directory To Show Images, Move File(Image) To Database
Android Version 2.2
try this for saving image :
private void saveDownloadedImage(Bitmap bmp, String id) {
if (bmp != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imgBytes = baos.toByteArray();
String base64String = Base64.encodeToString(imgBytes,
Base64.DEFAULT);
ContentValues initialValues = new ContentValues();
initialValues.put("picture", base64String);
// save your base64String to DB
}
}
and this for set image :
private Bitmap setImage(String base64String) {
Bitmap bmp = null;
try {
if (base64String == null || base64String.equals("")) {
} else {
byte[] decodedString = Base64.decode(base64String, Base64.DEFAULT);
bmp = BitmapFactory.decodeByteArray(
decodedString, 0, decodedString.length);
}
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}

android decode string base 64 to bitmap

Hi guys I wanted to ask you one thing, I have a chat that transfers strings and I can even attach of JPEG images before sending them to convert it into a string and then decode in BITMAP just that when I decode it crashes the app. I wanted to know if it is the right code to decode it.
NOME = (TextView) row.findViewById(R.id.comment);
NOME.setText(coment.comment);
String a = NOME.getText().toString();
if(a.length() > 1024 )
{
byte[] image = Base64.decode(a, 0);
int lung = a.length();
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, lung);
Image = (ImageView) row.findViewById(R.id.image);
Image.setImageBitmap(bitmap);
}
The code looks fine, if I had to guess I would say you're getting the Out of Memory error, which is very common when loading images. Check out
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
for some best practices when loading images.
The method for Encoding an Image to String Base64 :
public static String encodeToString() {
String imageString = null;
try {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
imageString = Base64.encodeToString(b, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return imageString;
}
The method for Decoding String Base64 to Image :
public static void decodeToImage(String imageString) {
try {
byte[] imageByte = Base64.decode(imageString, Base64.DEFAULT);
Bitmap bm = BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length);
image_view.setImageBitmap(bm);
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources