Can I save a image dynamically and use it in layouts? - android

I have a small query, is it possible to get an image dynamically every-time the app is launched over the internet and then that Image can be used to be shown on UI(via xml file)please let me know if this can be achieved in android and with any sample code.
Thanks & Regards.

In this case the best way to do it is to load image via HTTP GET, store it in Bitmap object and inject programmatically into ImageView element defined in layout.
You can't override resource image so you cant use #drawable.
Here you have loadBitmap method that loads image by url and stores it in Bitmap: How to load an ImageView by URL in Android?
Next thing is to inject it into ImageView:
ImageView image = (ImageView) findViewById(R.id.image);
Bitmap bitmap = loadBitmap("http://www.android.com/images/logo.png");
image.setImageBitmap(bitmap);

Not possible through XML.
I'd recommend having a placebo bitmap also in case there is no Internet access available at the time. Use AsyncTask when downloading.
new GetAndSetBitmap.execute(url)
private class GetAndSetBitmap extends AsyncTask<String, Void, Bitmap>
{
protected Bitmap doInBackground(String... urls)
{
Bitmap bitmap = loadBitmap(url[0]);
// Used the loadBitmap from other answer. Anything goes wrong
// load a local resource with the same dimensions.
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bm)
{
yourImageView.setImageBitMap(bm);
}
}

Guys found a better solution
try {
ImageView i = (ImageView)findViewById(R.id.image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Related

How to pass the dynamic path of a drawable to BitmapFactory.decoreResource()'s 2nd parameter

I'm trying to implement Bitmap memeCanvas = BitmapFactory.decodeResource(getResources(), xxx).copy(Bitmap.Config.ARGB_8888, true); to draw on the images that I upload from my phone to my ImageView. Because I don't have a specific drawable path like R.drawable.hypotheticalImage, I don't know how to pass the same information for a drawable path that is dynamic as the 2nd parameter of BitmapFactory.decodeResource().
I can supply code per request.
This is my solution. I had to call getContext() to be able to access getContentResolver() and wrap the entire thing in a try-catch block.
Bitmap memeCanvas = null;
try {
memeCanvas = BitmapFactory
.decodeStream(getContext()
.getContentResolver()
.openInputStream(imageUri))
.copy(Bitmap.Config.ARGB_8888, true);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

How to set the image to image view that is downloaded to your application in android local

I have a image downloaded locally in application
/data/data/com.starboard.stella/files/Stella/FragranceFinder/QuestionImages/option1_woman.png
How do I access the image to set for image view?
you can use Picasso for that
Picasso.with(context).load(new File(...)).into(imageView);
refernce: http://square.github.io/picasso/
Creating a File type using your filepath, creating a Bitmap out of that File and setting the Image bitmap of your ImageView using setImageBitmap is probably the best way to go.
Paresh Mayani gives a great solution with code here: https://stackoverflow.com/a/4182060/5920187
To load an image
File imgFile = new File(pathToPicture);
Bitmap bitmap = BitmapFactory.decodeFile(pathToPicture);
then
imageView.setImageBitmap(bitmap);
I think you should try this:
try {
File file = new File(getExternalFilesDir(null) + "/Stella/FragranceFinder/QuestionImages/", "option1_woman.png");
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
ImageView image =(ImageView)findViewById(R.id.image);
image.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Saving and getting image url in internal storage

I am working on an Android application in which I am getting image url from the server. Now I have to do save that image url and image file in my local storage, because for the first time if I want to check if the same url is available in my internal storage then it will get that image file from my local storage, if not then it will first save that image url reference and image file in my internal storage.
My code is given below. I wish to save image url and image file in my internal storage and according to the above conditions.
new DownloadImageTask((ImageView) view.findViewById(R.id.imageViewProfile))
.execute(imageURL);
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
If you are looking for saving image once and reusing it many times this may help you Google Volley Library. Universal Image Loader which is widely used after Volley.
EDIT :
Now there are bunch of libaries which are so popular.
Picasso
Glide
Fresco
Choose according to your requirement.Here is comparison.
You can store url in table and check your condition whatever
download file from server and store it in external/internal storage.

storing images into sd card after loading it in listview

I am downloading images from server into the ListView , now to perform this task i am using ImageDownloader example code. so far its working fine.
But i want to save images of ListView in a SD card but i am confused when to store the images as images are being downloaded Asynchronously and because of ViewHolder pattern its little tough for me to judge.
Once i stored it in a SD card next time i want to read it from memory only.
ImageDownload is storing bitmap in cache and fetching it from there once it gets downloaded.But the problem is its behavior is not predictable.
Sometimes it downloads from server and sometimes from cache.
so can anyone help me in finding what is the proper place to store the images in sd card once.
Modify your ImageDownloader class to save the image like this :
add a parameter to download method like :
download(String url, ImageView imageView, Boolean saveData)
make a global variable saveData in yout ID class :
private Boolean saveData;
and store in it the value given as parameter in download dmethod:
this.saveData = saveData;
and the BitmapDownloaderTask's onPostExecute method should look like this :
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
addBitmapToCache(url, bitmap);
if (saveData == true) {
try {
FileOutputStream out = new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
}
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
BitmapDownloaderTask bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
// Change bitmap only if this process is still associated with it
if (this == bitmapDownloaderTask) {
imageView.setImageBitmap(bitmap);
}
}
}
where path is the path were you want to save the image .
and next time before you want to load the image you have to see if it is already downloaded and load it from the path otherwise call ImageDownloader.
that's it! enjoy!

Bitmapfactory example

I want to create a dynamic image view where every image in my gallery will going to use bitmapfactory and not image drawable that binds in the image view. Is there some sites that has bitmapfactory tutorial for this? i believe that using bitmapfactory uses less memory that binding the image into image view? Is this right? I want also to minimize the risk of memory leaks thats why I want to use bitmapfactory. Please help. I cant find basic examples that teaches bitmapfactory.
Building Bitmap Objects
1) From a File
Use the adb tool with push option to copy test2.png onto the sdcard
This is the easiest way to load bitmaps from the sdcard. Simply pass the path to the image to BitmapFactory.decodeFile() and let the Android SDK do the rest.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeFile("/sdcard/test2.png");
image.setImageBitmap(bMap);
}
}
All this code does is load the image test2.png that we previously copied to the sdcard. The BitmapFactory creates a bitmap object with this image and we use the ImageView.setImageBitmap() method to update the ImageView component.
2) From an Input stream
Use BitmapFactory.decodeStream() to convert a BufferedInputStream into a bitmap object.
public class TestImages extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
FileInputStream in;
BufferedInputStream buf;
try {
in = new FileInputStream("/sdcard/test2.png");
buf = new BufferedInputStream(in);
Bitmap bMap = BitmapFactory.decodeStream(buf);
image.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
Log.e("Error reading file", e.toString());
}
}
}
This code uses the basic Java FileInputStream and BufferedInputStream to create the input stream for BitmapFactory.decodeStream(). The file access code should be surrounded by a try/catch block to catch any exceptions thrown by FileInputStream or BufferedInputStream. Also when you're finished with the stream handles they should be closed.
3) From your Android project's resources
Use BitmapFactory.decodeResource(res, id) to get a bitmap from an Android resource.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.test_image);
Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
image.setImageBitmap(bMap);
}

Categories

Resources