Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am new to android. I have some images stored at some path on server. In my application i want that the images should be loaded once from the server and next time the user opens the application the app should not load it again. Please tell me how should i store these images. Please help.
For store image on app cache or internal storage(sdcard0) you can use library like Universal-Image-Loader , Aquery, Picasso etc.
These library helps you to make image loading faster, save images on cache memory or data.
You can download this library from here
Universal Image Loader : https://github.com/nostra13/Android-Universal-Image-Loader (Just import library in your workspace and use it)
Aquery : https://github.com/androidquery/androidquery (You can use Aquery-android.jar file for use Aquery)
Universal image loader has more functionality than Aquery.
Hope this helps you out.
You can store image in file. You need only set unique name to image file, an example md5 hash of url.
You can save image in file use follow code:
File file = File(filePath)
try {
FileOutputStream outStream = FileOutputStream(file)
bitmap!!.compress(Bitmap.CompressFormat.PNG, 100, outStream)
outStream.flush()
outStream.close()
}catch(e: Exception){
Log.e("log", "error save image to cache $filePath")
}
}
and read from file:
try{
BitmapFactory.Options optionsBitmapFactory = BitmapFactory.Options()
optionsBitmapFactory.inPreferredConfig = Bitmap.Config.ARGB_8888
Bitmap bitmap = BitmapFactory.decodeFile(filePath, optionsBitmapFactory)
}catch(e: Exception){
Log.e("log", "error load image from cache $filePath")
}
There are several image loader libraries for it. One of them is Universal Image loader and Glide
You can refer this Picasso v/s Imageloader v/s Fresco vs Glide
It will store images in cache and next time will provide image from cache. For server images Universal Image loader and Glide library is highly recommended. You can also set placeholder image.
There are two way :-
Do cache images for an example just look at picaso library.
//Code how to use picaso :-
/Initialize ImageView
ImageView imageView = (ImageView) findViewById(R.id.imageView);
//Loading image from below url into imageView
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.into(imageView);
Store images to storage either external or internal and fetch second time from storage. you can use again picaso callback to save bitmap cio.economictimes.indiatimes.com
There are some third party libraries available for these purpose which would save some development effort.
Below are some of them:
Picasso
Glide
Universal image loader
Here is some libs for loading image from URL and it will store image in to memory as cache.
UIL : flexible and highly customizable instrument for image loading, caching and displaying. It provides a lot of configuration options and good control over the image loading and caching process.
PICASSO :
Handling ImageView recycling and download cancelation in an adapter.
Complex image transformations with minimal memory use.
Automatic memory and disk caching.
First you must make sure your application has permission to write to the sdcard. To do this you need to add the uses permission write external storage in your applications manifest file. See Setting Android Permissions
Then you can you can download the URL to a file on the sdcard. A simple way is:
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,"myImage.png"));
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
EDIT : Put permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Related
I need to download images from server and store as thumbnails directly.
and for display images also i need to use images from .thumbnails folder directly. i am not getting how to create and save images as .thumbnail . and how to use images from that .thumbnail file.i searched online but everywhere only this below code present.
Bitmap thumb = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(file.getPath()), width, height);
any help?
Please check below code which helps you.
Follow below steps:
Calculate the maximum possible inSampleSize that still yields an image larger than your target.
Load the image using BitmapFactory.decodeFile(file, options), passing inSampleSize as an option.
Resize to the desired dimensions using Bitmap.createScaledBitmap().
Now you have your bitmap ready and you can save it any where using the following code
Bitmap thumbnail;
File thumbnailFile = ...;
FileOutputStream fos = new FileOutputStream(thumbnailFile);
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
hope it helps you and save your time.
Or use Glide library which store image as a full image and 1 thmbnail image which is power caching library which loads image quickly and once download image after load image from cache not from network.
Below is a Glide link please read it advantages and features and after used into your applications.
https://github.com/bumptech/glide
I need to download a GIF and save it to external storage so I can send it via MMS.Messages have a limit 300kb and most of the GIFs are too large so I need to resize them.
I am using Glide in rest of my project and Glide has a nifty function which should, in theory, download a resized image. But it doesn't.
In short, here's the code I'm calling inside a background thread:
byte[] bytes = Glide.with(context)
.load(url)
.asGif()
.toBytes()
.into(250, 250)
.get();
file = new File(fileName);
FileOutputStream fileWriter = new FileOutputStream(file);
fileWriter.write(bytes);
fileWriter.flush();
fileWriter.close();
Downloaded files still keep their original size which is above the MMS limit of 300kb whereas they should be 250x250 pixels.
Asked the same question on Glide Github and got the answer there. Apparently Glide will only resize images that are larger than 500 x 500, unless a fitCenter() (or any other) transformation is used.
So, to resize the .gif file, use this code:
byte[] bytes = Glide.with(context)
.load(url)
.asGif()
.toBytes()
.transform(new GifDrawableTransformation(new CenterCrop(context), Glide.get(context).getBitmapPool()))
.into(250, 250)
.get();
you can do compress that file also and then store in database
this link will help you. in this first convert .gif to .png then use it.
Android - Best way to convert .gif to .png
I'm trying to load an image from the following url:
https://fangkarte.de:8080/fangfisch/file/files/592036af55dfffca0155e01fe10002f7
In Chrome/IE the image will be displayed without problems. When I try to load the image on Android I am not able to store the image as an PNG file. Everytime the image will be saved as a textfile which contains the image as base64 String.
Also I tried the following code but the decodedByte is null:
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Does anyone have an idea how I can show my image from the url as an bitmap or which I prefer to store the image on the device as an png?
Use Universal Image Loder to upload image from Url
Download universal image loder and add to your lib folder and
Implement the below code where you want to load image
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.noimage)
.showImageOnFail(R.drawable.icon3)
.showImageOnLoading(R.drawable.loading).build();
imageLoader.displayImage(url, imageview, options);
For handling images, Use Picasso , Glide , Universal image loader, Volley or Fresco
Eg, in picasso, you will be able to load images, store them in memory cache and handle cancellations in listviews/recyclerviews etc...
Picasso.with(context).load("https://fangkarte.de:8080/fangfisch/file/files/592036af55dfffca0155e01fe10002f7").placeholder("someimagetillyourimagedownloads).into(R.id.yourimageview);
Picasso: https://github.com/square/picasso
Glide: https://github.com/bumptech/glide
Fresco: https://github.com/facebook/fresco ( I use this after extensively testing all 3 except volley )
UIL: https://github.com/nostra13/Android-Universal-Image-Loader
Similar things can be done using all the above libraries.
I highly recommend not trying to handle images on your own. It can turn into quite a mess if you are a novice android dev.
The image you download is much to big ((860.000 bytes)) to make a Bitmap out of it. So BitmapFactory will return null.
Scale image down before use.
I calling following code before loading an image:
String url = getUrlImageIcon();
MemoryCacheUtil.removeFromCache(url, ImageLoader.getInstance().getMemoryCache());
DiscCacheUtil.removeFromCache(url, ImageLoader.getInstance().getDiscCache());
ImageLoader.getInstance().displayImage(url, imageView, listener);
My Problem is, this is not deleting the image from cache, the image loader is still displaying the old image afterwards... The old image is not even existing on the server anymore...
How can I remove all cached files from an image correctly?
PS: I'm using the up-to-date version 1.9.1...
What #vanomart answered is perfect, just to update the answer. Currently, UIL supports,
MemoryCacheUtils.removeFromCache(imageUri, imageLoader.getMemoryCache());
DiskCacheUtils.removeFromCache(imageUri, imageLoader.getDiskCache());
So, there is better way to clear disk cache.
According to developer of this library is solution quite simple. All you need to do is to delete cached image from memory and also from disk. How to do that is shown below.
File imageFile = imageLoader.getDiscCache().get(imageUri);
if (imageFile.exists()) {
imageFile.delete();
}
MemoryCacheUtils.removeFromCache(imageUri, imageLoader.getMemoryCache());
Snippet above is from this issue.
I am designing an Android application which will be displaying some news that will be retrieved from a remote URL in xml format, say http://adomain/latest.xml
The XML file has the following format:
<articles>
<article>
<id>6</id>
<title>A sample title</title>
<image>http://adomain/images/anImage.jpg</image>
<lastupdate>1326938231</lastupdate>
<content><![CDATA[Sample content]]></content>
</article>
...
</articles>
I have created an Updater Service which listens to Connectivity Changes and when the system has a connection over the internet, it tries to download the xml file. Then parse it and save data. The Updater runs on a separate thread, every 10 minutes.
My question is:
What is the best way to handle the images?
a) Should I perform lazy loading on images when a news item is displayed
OR
b) Should I download the image when I parse the xml file?
I recommend lazy loading as the news item is displayed, so you don't use excessive bandwidth (and potentially cost for the user). No point in downloading images if the user never wants to look at them.
for images, I think you always follow lazy loading because, image loading may take some time, and also an efficient lazy loader can help you to avoid any future memory issue.
Just fetch <Image> tag data from your XMl.
String imgURL = your <Image> value;
ImageView imageView = new ImageView(this);
Bitmap bmp = BitmapFactory.decodeStream(new java.net.URL(imgURL).openStream());
imageView.setId(i);
imageView.setImageBitmap(bmp);
This will work to set image and you also get image in "bmp".
Android provide directly show image from URL:
For Store Image to Sd Card:
File file = new File (pathOfSdCard, iamgeName);
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Put Line to your AndroidMenifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
This all i using in my app. it works fine.
I hope this will helps you a lot.