android decode string base 64 to bitmap - android

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

Related

how upload image with text to server without affecting image quality,

i upload image to server with help of volley and bitmap and i successfully pass the data, but when i take the image using camera the image quality become so poor and also when i pass an image of size above 500kb the app become crash. Why this happen??
can anyone help me,
this is how my camera intent perform
private void onCaptureImageResult(Intent data) {
thumbnail = (Bitmap) data.getExtras().get("data");
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
//fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (thumbnail!=null){
addImageNew.setImageBitmap(thumbnail);
}
}
this is how my gallery intent perform
private void onSelectFromGalleryResult(Intent data) {
thumbnail=null;
if (data != null) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
if (thumbnail!=null){
addImageNew.setImageBitmap(thumbnail);
}
}
this how i convert Bitmap to string
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 90, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
NOTE: i have only problem in image quality and high size image passing
You can try to use below link solution. It may be work for you.
200kb image to base64 cannot send to web service
I didn't find where getStringImage(Bitmap bmp) is called, but you can try to do something like that:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
getStringImage(bitmap);
Or maybe you can change the compress to 100, for high quality:
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);

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

Unable to convert bitmap to string then back to bitmap using BitmapFactory.decodeByteArray

I'm base64 encoding a bitmap to a string in order to send it as part of a JSON object. The recipient of the image will get the string and convert it to an image again.
If this is at all relevant, I'm doing this for an Android app.
Converting the bitmap to a string seems to work ok, but when converting the string back to a bitmap I'm getting a NullPointerException.
I've tried to boil this down to the basics (and converting to a string and back to a bitmap in the same method for testing), so I have the following:
public static void convertBitmapToBase64String(Context context, String filename, int maxStringSize)
{
Bitmap originalBmp = PicUtils.getBitmapFromFilename(filename, null, -1);
String base64Image = PicUtils.convertBitmapToBase64StringFromFile(context, TEMP_FILENAME);
// The encoded string is not null, so encoding seems to work.
DataUtils.log("base64Image length is " + base64Image.length());
// Test if we can convert back
final byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
// This returns null! Is failing here.
Bitmap decodedByteBitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
public static Bitmap getBitmapFromFilename(String filename)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
Bitmap finalBitmap = BitmapFactory.decodeFile(filename);
return finalBitmap;
}
public static String convertBitmapToBase64StringFromFile(Context context, String filename)
{
try {
FileInputStream fis = context.openFileInput(filename);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Base64OutputStream outputStream = new Base64OutputStream(byteArrayOutputStream, Base64.DEFAULT);
IOUtils.copy(fis, outputStream);
return new String(byteArrayOutputStream.toByteArray(),"UTF-8");
} catch (Exception e) {
e.printStackTrace();
DataUtils.log(e.getMessage());
return null;
}
}
Any tips are appreciated!
This is a link I used to solve my problem. I hope this will work for you too.
http://androidtrainningcenter.blogspot.in/2012/03/how-to-convert-string-to-bitmap-and.html.

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

Unable to convert bitmap image into byte[]

I want convert my captured image into byte[]. When I capture image using camera it gets captured and preview is also shown and images saves on my external storage as well successfully.But when I try to convert my preview image it doesn't stores anything in the byte array.
Following is my method which is called when I press preview image button on my phone.
public static void previewCapturedImage() {
try {
static ByteArrayOutputStream stream = null;
imgPreview.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),options);
imgPreview.setImageBitmap(bitmap);
stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
convert image to string & byte array, use following short of code.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
yourbitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//this will convert image to byte[]
byte[] byteArrayImage = baos.toByteArray();
// this will convert byte[] to string
String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);
Check the below working code. This includes quality adjustment also
/**
* #param bitmap
* #param quality 1 ~ 100
* #return
*/
public static byte[] compressBitmap(Bitmap bitmap, int quality)
{
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, quality, baos);
return baos.toByteArray();
} catch (Exception e)
{
PrintLog.print(TAG, e.toString(), e);
}
return null;
}

Categories

Resources