Bitmap too large. Tried All - android

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

Related

How to convert Bitmap into Base64 String without compressing? [duplicate]

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

getting null point exception while converting file to Base64

I'm going to convert file to base64 so I send file and convert it to bitmap and when i want to compress it, it give me error null point exception
this is what everything that i did.
public static String getFileToByte(String path){
Bitmap bm = null;
ByteArrayOutputStream baos = null;
byte[] b = null;
String encodeString = null;
try{
bm = BitmapFactory.decodeFile(path);
baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
b = baos.toByteArray();
encodeString = Base64.encodeToString(b, Base64.DEFAULT);
}catch (Exception e){
e.printStackTrace();
}
return encodeString;
}
I got error on this error:
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
and pass:
getFileToByte(image.getAbsolutePath());
Do not convert the file to a bitmap first. Your bitmap is null as there is not enough memory to construct a bitmap for that image file with big resolution.
Instead you should directly base64 encode the bytes of the file.
Then your code is the same for all kind of files too.

Android: Recover image bitmap from representation as decoded string [duplicate]

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!

Unable to locate imageview for uploading to parse

Edit: Solved.
I'm trying to upload an image to parse that has been selected from the phone's gallery. However I cannot seem to locate the imageview as it returns null. I think this page: Saving images to Parse has a similar question to what I'm asking but there is no answer to it.
Fragment class:
public void onClick(View view) {
img = (ImageView) rootView.findViewById(R.id.imageView1);
// Locate the image (error is here)
Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), img);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
//byte[] image = img.getContext().toString().getBytes();
//Bitmap bitmap = BitmapFactory.decodeFile(img);
ParseFile file = new ParseFile("image.jpg", image);
file.saveInBackground();
ParseObject familyTree = new ParseObject("FamilyTree");
familyTree.put("image", file);
familyTree.put("name", etName.getText().toString());
familyTree.put("relation", etRelation.getText().toString());
familyTree.saveInBackground();
Toast.makeText(FamilyTreeFragment2.this.getActivity(), "Saved.", Toast.LENGTH_SHORT).show();
// getFragmentManager().beginTransaction().replace(R.id.container, new FamilyTreeFragment2()).addToBackStack(null).commit();
}
Any help is appreciated. Thank you.
I've managed to find the solution.
Replaced
Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), img);
with
Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();

android bitmap isn't created from base64

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.

Categories

Resources