I'm trying to convert base64 image into bitmap image and then load it using picasso library into a recycler view. However, I get an error whenever I run my code saying I need to pass in a URI into the picasso method.
public String getImage(){
Context context =null;
byte[] decodedString = Base64.decode(image, Base64.URL_SAFE);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
decodedByte.compress(Bitmap.CompressFormat.PNG, 100, bytes);
path = MediaStore.Images.Media.insertImage(context.getContentResolver(), decodedByte, null, null);
return Uri.parse(path);
}
DataAdapter:
Picasso.with(context).load(data.get(i).getImage()).into(holder.reportImage);
Once you have downloaded and decoded a bitmap, there is no point of using an image loading library. All of the benefits (request queue and cache) are lost. You can simply use holder.reportImage.setImageBitmap(bmp);
Another approach would be to write a custom RequestHandler, that will decode the base64 data after downloading.
Assuming that you are using base64 image as a placeholder for your item in recycler view I suggest you use this method to convert base64 string to bitmap -
fun fromBase64ToBitmap(context: Context, base64string: String?): BitmapDrawable {
val decodedString = Base64.decode(string, Base64.DEFAULT)
val bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
return BitmapDrawable(context.resources, bitmap)
}
and set
picasso.load(your_high_quality_image)
.placeholder(bitmapDrawableFromAboveMethod)
.into(imageHolder)
Hope this helps.
Note: Code is in Kotlin but you can easily convert it in java
Related
I am picking an image from gallery and converting into Base64 encoded string and sending to server
Below code for conversion to Base64:
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
But when I get encoded String from server it don't get displayed in ImageView
Base64 encoded image string below:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAi8CLwDASIA
AhEBAxEB/8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PEqWbs5Ygmg1kuQf3rZsAKKDEFgVJ2NElEHYA0SAewJPiDG21RjWQUVO0hAJDEgfQHa
xdAkFB+5/VgipBBIJIqN6oImr9O18X8fZe9/+P46KA1qCCQQAV1bvXYWxsMy0R8gB796JHrLMX0U
sA0ZBpAyh01VFDk/IZCGsDUuboABRt6wRZ2XYP2UBP3yqB3+0+kbsVYkMANNjqxFuV/cFF93plpS
WBAP7VsMaFfz9dj3npt7aL/92/y74gmDbV5RUpD0qb/XvgRb49gybKWCEAHuBa/ZAX9zqdTTErYY
+djpACCpU332oLdhQCp3vY9lYggCipHdfWY11VQ9hlUhKBKhQbVAbIYhvMMfuxqSO58pA2DXtRAq
2JTuYzRZAG2A7WCwNXSqTQjclRJlWVRwRR/xWdqhATkzJ2MRUgIAVFPU8r5jhRnjOxEYDswYEsAo
Ozgq9hlvVu/aiGIHrMrByERgEa1ZlCsr/wAFLpwrkldaP23agGBDGSpWJd9WYaFygYKC+yagFiuh
Ut5XY7lvsiZNSg12VhsdCaCsA
and i display this encode image string in ImageView like this
String imageDataBytes = path;
InputStream stream = new ByteArrayInputStream(Base64.decode(imageDataBytes.getBytes(), Base64.URL_SAFE));
Bitmap image = BitmapFactory.decodeStream(stream);
dashboard_img.setImageBitmap(image);
Above code I use Base.64URL_SAFE and Default also but not working. So please help me to fix this
Try this
Bitmap bmp = BitmapFactory.decodeByteArray(yourBase64String, 0, yourBase64String.length);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, customWidth, customHeight, false));
Refresh imageview with invalidate. Use this code snippet
try {
byte[] decodedString = Base64.decode(imageDataBytes, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
dashboard_img.setImageBitmap(bitmap);
dashboard_img.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
Edit:
I have checked your base64 string it is not a valid base 64.
For set base64 image in imageView you can follow given code:
String filePath;
Bitmap bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), Uri.parse(filePath)); // filePath is our BASE64 string
imgView.setImageBitmap(bm);
And in-case your base64 string may be wrong, because this also can not decode on online decoder : https://www.base64decode.org/
Xamarin Android Application to Store Image in SQLite From Gallery(available images in the phone) .My Question is How to Image Storage in SQLite? And Retrieve Image From SQLite? Is possible only Image Compressing using bitmap function ?
The basic idea to store/fetch Image bitmaps in most of the DB is following,
Store: Convert the Image bitmap into a Base64String and store it to SQLite.
public static string Base64Encode(string plainText) {
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
Retrieve: Fetch the Base64String and convert that to Bitmap again.
public static string Base64Decode(string base64EncodedData) {
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
You can store your bitmap image as a byte[] to SQlite. For this operation you should convert bitmap to byte array. This piece of code, convert bitmap to byte[]
var memoryStream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 0, memoryStream);
imageByteArray = memoryStream.ToArray();
imageView.BuildDrawingCache (true);
Bitmap bitmap = imageView.GetDrawingCache (true);
BitmapDrawable drawable = (BitmapDrawable)imageView.GetDrawable();
Bitmap bitmap = drawable.GetBitmap();
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 use Retrofit to transfer Data(class) from android to Server.Generally we create Same class on Client and Server side which contain data type like int,String same on both side.Now I need to send Image in class to Server.Also I just don't want to send just image to server but I want to send class which contain 1 image as datatype.So how can I do that ?or any suggestion how can I do this with some other tool ?
Suppose you already have a File pointing to the image:
final File imageFile = ...;
Note: How to get this file depends on whether you only allow local files in your file chooser (or e. g. images that are actually in Google Drive) and on which Android version you are on, etc.
To upload the image you need to use Retrofit's TypedFile - here is what worked for me:
#POST("/api/image/upload")
#Multipart
public void submitPictureToVoting(#Part("user_id") Integer userId,
#Part("image_title") String imageTitle,
#Part("file") TypedFile file,
Callback<UploadImageResponse> callback);
And then:
final TypedFile typedImageFile = new TypedFile("application/octet-stream", imageFile);
mApiClient.submitPictureToVoting(
1234567,
"This is me!",
typedImageFile,
new Callback<UploadImageResponse> {
// ...
});
I dont think this is answer but by doing this we can solve proble of Retrofit easily
Hi I tried this by Encoding Image to String ,so that we can easily send this "String" data type like other String, & when we want image back,we can decode it.
1.Code for Encoding
Here Image taken from ImageView.
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
2.Code for Decoding
byte[] decodedByte = Base64.decode(encodedImage, 0);
Bitmap decodedImg= BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
imageView.setImageBitmap(decodedImg);
My app reads several BASE64 encoded images one by one from DB. But for some images(<0.1%), it fails to load. The method, BitmapFactory.decodeByteArray() return null which means its invalid format. But when I created a separate app with hard-coded culprit image, it worked. Now I have one big app where the same image didn't work and in my test app it works. Can anyone tell me why in God's name this is happening? Here is my code:
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap setBMPPath = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
if (setBMPPath != null) {
qImage.setImageBitmap(setBMPPath);
}
Is there any other method that I can use to convert byte array to Bitmap?
You can try adding Base64.NO_WRAP:
byte[] decodeResponse = Base64.decode(base64Image, Base64.DEFAULT | Base64.NO_WRAP);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodeResponse, 0, decodeResponse.length);
Hope this helps someone.