This question already has an answer here:
How to convert a image into Base64 string without compressing the image?
(1 answer)
Closed 3 years ago.
I am trying to convert a bitmap image into base64 String using this code. I and getting a very low-quality image. How can I get a good quality image after convert bitmap into Base64 Sring
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
base64Image = Base64.encodeToString(b, Base64.DEFAULT);
return base64Image;
}
If I have a 5MB image. After convert, I am getting the only 160KB image. But in my case, I don't want to compress my image too much I just want to get Base64 String based on Bitmap image only JPEG format, not any other. Please help me with this.
Try this:
public String getBase64Image(Bitmap bitmap) {
try {
ByteBuffer buffer =
ByteBuffer.allocate(bitmap.getRowBytes() *
bitmap.getHeight());
bitmap.copyPixelsToBuffer(buffer);
byte[] data = buffer.array();
return Base64.encodeToString(bytes, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Related
Guys I am facing this issue since 2 days straight. I want to pick an image from gallery and convert it to Base64 method. I have tried Picasso but my imageview is large. Can you please help me. I tried everything but out of memory is too much for me when converting it to bitmap and then to base64.
BitmapDrawable drawable = (BitmapDrawable) ProfilePic.getDrawable();
yourSelectedIBitmapDrawable drawable = (BitmapDrawable) ProfilePic.getDrawable();
yourSelectedImage = drawable.getBitmap();mage = drawable.getBitmap();
Code which is converting this bitmap to Base64. Is there any possibility of skipping the bitmap and directly converting to Base64
private String encodeToBase64(Bitmap image) {
Bitmap immagex = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
//Log.e("LOOK", imageEncoded);
return imageEncoded;
}
Profile Pic is name of Imageview.
EDIT: So guyz one of the ways is to use the large heap, but Google says you should not use that unless absolutely necessary. The other one that worked for me is the accepted answer. Now I came up with my own solution. In theory, I am using Picasso to load the image into image view. So what if I can extract the image from the ImageView. Not from URI or path, but from Imageview. This way you have an image which is already reduced by Picasso. Picasso provides Callback to for Success or failure. So on Success, you can access the cache memory of ImageView and extract the Bit map out of it.
I will post the code as an answer shortly. I tried it and even an image of 35Mb originally can be converted to bitmap without Out of memory exception.
So here is my ans: https://stackoverflow.com/a/52125006/6022584
You can try to read the bitmap data with a buffer. Something like that :
private String encodeToBase64(Bitmap image) {
// get an InputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(CompressFormat.PNG, 0, baos);
byte[] bitmapdata = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bitmapdata);
// prepare a buffer to read the inputStream
byte[] buffer = new byte[10 * ONE_KIO]; // ONE_KIO = 1024
int bytesRead;
// prepare the stream to encode in Base64
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Base64OutputStream base64OutputStream = new Base64OutputStream(outputStream, Base64.DEFAULT);
// read the inputStream
while ((bytesRead = bais.read(buffer)) != -1) {
base64OutputStream.write(buffer, 0, bytesRead);
}
base64OutputStream.close();
// get the encoded result string
return outputStream.toString();
}
This is my Code that worked. New Issue is the name of Activity for me
if (requestCode == PICK_IMAGE) {
if(resultCode == RESULT_OK){
//isImageFromGallery = true;
//isImageSelected = true;
ImagePath = data.getData();
Picasso.get()
.load(ImagePath)
.resize(1024,1024)
.onlyScaleDown()
.centerCrop()
.into(picture, new Callback(){
#Override
public void onSuccess() {
BitmapDrawable drawable = (BitmapDrawable) picture.getDrawable();
yourSelectedImage = drawable.getBitmap();
//isImageSelected = true;
Log.d("FileSize",Formatter.formatFileSize(NewIssue.this,
yourSelectedImage.getByteCount()));
}
#Override
public void onError(Exception e) {
Toast.makeText(NewIssue.this, "Could Not Load Image", Toast.LENGTH_SHORT).show();
}
});
}
}
In Java server I fetch image from external service URL like:
InputStream in = new java.net.URL(imageWebServiceURL).openStream();
String resultToCleint = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(IOUtils.toByteArray(in));
Then on Android I parse it like:
byte[] imageAsBytes = Base64.decode(resultToCleint.getBytes(), Base64.DEFAULT);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
Result: Image not displayed, ain't errors/exceptions neither on server nor on client.
What is the problem here?
EDIT: On android I use class android.util.Base64
Thanks,
Use Picasso library to load image:
You just need to add 1 line of code to show the image on ImageView
//Loading image from below url into imageView
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.into(imageView);
You can learn more from here
use this to convert to base 64
public static String uploadPic(Bitmap bm) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = ""+ Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}
check if image is uploaded then using volley String request object download the string response using this code convert it back.
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
As commented, let's assume base64Content is the base64 string responsed from your web service/server-side app, you can refer to the following sample code:
String base64Content = jsonObject.getString("Base64Content");
byte[] bytes = Base64.decode(base64Content, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Moreover, if your server compressed reponse data either by gzip or deflate, your client app must decompress the data first.
Hope this helps!
I have a Base64 string image .I want to convert it into blob type and save it in database..
I have
String base64Image="iVBORw0KGgoAAAANSUhEUgAAAGAAAACgCAYAAADzcGmMAAAACSV...";
This is what I tried..
byte[] byteImage=org.apache.commons.codec.binary.Base64.decodeBase64(befImage.getBytes());
json.put("during_unloading_photo", byteImage);
where json is my JSONObject and
during_unloading_photo is the column name which is blob type.
for saving blob into DataBase you have to convert your base64 satring image to Byte[] and then you can save byte[] into db.
for converting base64 stringto bitmap
public static Bitmap decodeBase64Profile(String input) {
Bitmap bitmap = null;
if (input != null) {
byte[] decodedByte = Base64.decode(input, 0);
bitmap = BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}
return bitmap;
}
and now you can convert this Bitmap to Byte[] Like:
public static byte[] getBytesFromBitmap(Bitmap bitmap) {
if (bitmap!=null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
return null;
}
then finally you can save this Byte[] to Db.make sure your column name have type with blob
enjoy your code:)-
getBytes gives you the bytes of the string, it does not do base64 decoding. You will need to use a Base64 decoder to do the conversion. A little search will show up several options you can use.
I have an Android application which sends an image to a web service. I want to send the same photo back from the web service to Android.
I made a test program to compare the base64 data that's sent from Android to the server and the base64 that's sent back from server to Android -- they are exactly equal.
I want to use the base 64 string to create a bitmap, so I tried this:
String image = client1.getBaseURI("restaurantFoods/OneFood/"
+ this.getID() + "/getImage");
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0,
decodedString.length);
if(decodedByte == null){
Log.d(this.getFoodItem().getName(), image);
Log.d("isNull", "Yes");
}
else{
Log.d("isNull", "No");}
I keep getting null because the log just prints "YES".
Can anyone please help?
If you want to know how I encode the image it is as follows:
private String getBase64(Bitmap bitmap) {
String imgString = Base64.encodeToString(getBytesFromBitmap(bitmap),
Base64.NO_WRAP);
return imgString;
}
private byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
Bitmap icon = BitmapFactory.decodeResource(this.getResources(),
R.drawable.pizza);
String iconBase64 = this.getBase64(icon);
Try this to bitmap;
public Bitmap convert(String img){
byte[] b = Base64.decode(img, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
And this to String
public String convert(Bitmap bm, int quality){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, quality, baos);
byte[] byt = baos.toByteArray();
bm.recycle();
return Base64.encodeToString(byt, Base64.DEFAULT);
}
Really I don't see any real problems with your code, but these have worked for me so I suggest that you try them and see if that is actually your problem.
In my application I have faced a small issue in encoding and decoding images to String and pass it to web service.
After getting the bitmap image, I convert it into byte[] and encode to String value but in Some cases it shows error I don't know why it comes.
And one more doubt is Base64 class only supports to convert Bitmap image to String or any other tools available to do the same.
Thanks in advance...
In the case of OutOfMemoryError, below code helps me.
public String BitMapToString(Bitmap bitmap){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100, baos);
byte [] b=baos.toByteArray();
String temp=null;
try{
System.gc();
temp=Base64.encodeToString(b, Base64.DEFAULT);
}catch(Exception e){
e.printStackTrace();
}catch(OutOfMemoryError e){
baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,50, baos);
b=baos.toByteArray();
temp=Base64.encodeToString(b, Base64.DEFAULT);
Log.e("EWN", "Out of memory error catched");
}
return temp;
}
Basically what i did is : i catch OutofMemoryError and in that catch block i resize it by 50% and then i encode it to string.
Try My Below Sample Code Of Project
Bitmap bmp = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(bmp);
btnadd.requestFocus();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);