Convert String to Image in Android? - android

So, here is the thing. I am receiving an imagepath through WebService. I am storing the imagepath in a String. Now I want to convert the String to Bitmap and display the image in an imageView. I tried many codes from the examples in the internet but are not working.
Try 1:
Bitmap bm = BitmapFactory.decodeFile(imagelogo);
imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView2.setImageBitmap(bm);
Try 2: First I am converting String to string Base64 and then string Base64 to Bitmap.
byte[] data;
String base64;
{
try {
data = imagelogo.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
Log.i("Base 64 ", base64);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(base64 ,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
Any help would be appreciated. Thanks in advance.

Oh God, you can't convert a String of image path into a Bitmap! The image path isn't the image itself!
You need to download the image from internet through the image path and store it into a local file. The you need to call this:
Bitmap bm = BitmapFactory.decodeFile(localImagePath);
to load the Image.

Use this link:
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
Its very simple and then use this code:
int loader = R.drawable.loader;
// Imageview to show
ImageView image = (ImageView) findViewById(R.id.image);
// Image url
String image_url = "http://api.androidhive.info/images/sample.jpg";
// ImageLoader class instance
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
// whenever you want to load an image from url
// call DisplayImage function
// url - image url to load
// loader - loader image, will be displayed before getting image
// image - ImageView
imgLoader.DisplayImage(image_url, loader, image);
Hope it will helps you..

Related

how to show Base64 encoded image string in ImageView

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/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB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kbsssg+w48T2Cqq6vqSxBVj
2AGxYs3oTBNuxZJGIIPc+XalO2y7L2JFfflROvryhh8fy9xuAHYozWStpJVsq7Gl7WDVg7PYxJdY
6AwZcdzTelaetpMdVLUOzD0hBbMBnd96VUpaqY7VYxYKoxPfuLJcWSWs2K7kqoAv0CNttQra+QCq
ftqWrBYliPEqWbs5Ygmg1kuQf3rZsAKKDEFgVJ2NElEHYA0SAewJPiDG21RjWQUVO0hAJDEgfQHa
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/

Adding images from assets folder in adapter

I'm trying to display images from assets folder. I have this error:
Bitmap bitmap = getBitmapFormatAssets(product.getProductId());
try { Bitmap bitmap = getBitmap(product.getProductId()); imageView.setImageResource(bitmap);
It must be setImageBitmap(bitmap) not setImageResource(bitmap)
Instead of imageView.setImageResource(bitmap) try to use imageView.setImageBitmap(bitmap) directly.
when you want to set a bitmap image to a image view don't use setImageResource(bitmap)
use setImageBitmap(bitmap) as below
setImageBitmap(bitmap) Sets a Bitmap as the content of this ImageView.
like this
imageView.setImageBitmap(bitmap)
get your bitmap from assets using below code
private Bitmap getBitmapFromAsset(String strName)
{
AssetManager assetManager = getAssets();
InputStream istr = null;
try {
istr = assetManager.open(strName);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(istr);
return bitmap;
}
following are used for getting the image from asset folder and set it to ImageView.
// load image
try {
// get input stream
InputStream ims = getAssets().open("avatar.jpg");
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
mImage.setImageDrawable(d);
}
catch(IOException ex) {
return;
}

Android : How to set an image to an imageview from a url programatically

I have an image url coming from my rest API. Now I want to set it to an imageview when activity is loading. Below is how I get the bean from the rest api and then get the URL out of it.
Message message=new Message();
String imageUrl=message.getImageUrl();
I get Message object from my database and image url is include in that Message object.
Then I used Url object to get that image url.
URL url = null;
try {
url = new URL(imageUrl);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
contentImageView.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
}
I used above codes to load image to an imageview object which is contentImageView.
But still I cannot load this image to imageview, Nothing is getting loaded.
have any ideas?
The easiest way to do it is by using something like Picasso or Glide:
Picasso.with(getContext()).load(imgUrl).fit().into(contentImageView);
you can add picasso library in your gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
Please Try this function to get bitmap
public Bitmap getBitmapfromUrl(String imageUrl)
{
try
{
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
Use Glide or picasa library for efficient performance
Dependices
compile 'com.github.bumptech.glide:glide:3.7.0'
Sample Code
Glide.with(this)
.load(url)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(imageview);
References:
Glide official docs https://github.com/bumptech/glide
If you want to do it without any libraries:
If you have bitmap image in memory
setImageBitmap(Bitmap bm) // Sets a Bitmap as the content of this ImageView.
If you have image in drawable folder
setImageResource(int resId) // Sets a drawable as the content of this ImageView.
Reference: https://developer.android.com/reference/android/widget/ImageView.html

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!

Decoded String Image Can't Be Display As BitMap in Android

Below is the portion of code I used to encode the image file from bitmap to base64 string by import android.util.Base64 in my android project:
`
Bitmap img_bmp=BitmapFactory.decodeStream(getContentResolver().
openInputStream(this.browseImageURI));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
img_bmp.compress(Bitmap.CompressFormat.JPEG, 30, baos);
byte[] image = baos.toByteArray();
String profile_img = Base64.encodeToString(image, Base64.DEFAULT);
`
The string profile_img will be saved in mysql database as a string.
When I retrieve the string value from database, I will decode image string from String to Bitmap by using the below code:
`
Intent i = getIntent(); //pass the value from previous activity
str_img= i.getStringExtra("img");
img_bm = StringToBitMap(str_img);
imgview = (ImageView)findViewById(R.id.imageView1);
imgview.setImageBitmap(img_bm); // display the image
//Function to convert string to bitmap
public 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;
}
}
`
I expected it will display the image, however the image is not displayed and I get a log message from the Base64 decoder "--- decoder->decode returned false".
Can someone help me to figure out what is wrong in my code?
And do anyone know how to convert the base64 string image (pass from JSON to php script) into a blob format so that I can store it as BLOB in mysql.
Thank you in advance.

Categories

Resources