How to cache the downloaded bitmap using picasso library in Android - android

Hello I am using the picasso for downloading the bitmap in android.
Below is my code for this
// make sure to set Target as strong reference
private Target loadtarget;
public void loadBitmap(String url) {
if (loadtarget == null) loadtarget = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// do something with the Bitmap
handleLoadedBitmap(bitmap);
}
#Override
public void onBitmapFailed() {
}
}
Picasso.with(this).load(url).into(loadtarget);
}
I want to cache the bitmap so that later on it will pcik from cache instead of download it again. Does this code cache the downloaded bitmap ? If not how to enable
cache using picasso library for downloading the bitmap ?

Refer: http://square.github.io/picasso/
It will automatically cache the image.

Related

How do I download Image from Server If URL stored in ArrayList using Asynctask?

Images in a server and I have to download an image from the server. Image Url Stored in ArrayList using Asynctask.
how to download an image from ArrayList URL? I using Download manager and custom download but its give not an actual response.
you can use Picasso library.
for (String url : urlList) {
Picasso.with(this)
.load(url)
.into(new Target() {
#Override
public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){
/* Save the bitmap or do something with it here */
//Set it in the ImageView
theView.setImageBitmap(bitmap);
}
});
}

I am unable to send image from recyclerview.adapter to another activity

#Override
public void onBindViewHolder(final ViewHolder holder ,int position) {
Glide.with(c)
.load(images.get(position))
.placeholder(R.mipmap.ic_launcher)
.into(holder.img);
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
String fileName = "bitmap.png";
FileOutputStream stream = c.openFileOutput(fileName,Context.MODE_PRIVATE);
Intent showBigPicture = new Intent(c,showBigPicture.class);
Bitmap bitmapImage = BitmapFactory.decodeFile(images.get(position));
bitmapImage.compress(Bitmap.CompressFormat.PNG,100,stream);
stream.close();
bitmapImage.recycle();
showBigPicture.putExtra("image",fileName);
c.startActivity(showBigPicture);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
this is showing in logCat " Unable to decode stream: java.io.FileNotFoundException: android.support.v7.widget.AppCompatImageView{e22d977 V.ED..C. ...P.... 0,0-540,890 #7f0b0061 app:id/img}: open failed: ENOENT (No such file or directory)"
I believe you want to follow this answer on saving Bitmap images. I believe the reason you're getting a FileNotFoundException is because you're providing the URI to a file that doesn't exist yet to the decodeFile function that's quite possibly a URL from what I can tell. In short, to save a bitmap:
Create a new File(filename)
Decode file using getName on the File from step 1
Create FileOutputStream from File
Compress the bitmap image into the FileOutputStream
From what I can surmise from your question, it looks as though you're showing a images in a RecyclerView and when an image is clicked, you want to open another activity which shows a version of the full image. If that's close to your use-case, and you're using Glide, I would recommend taking advantage of its built-in automatic caching feature to reduce network calls instead of manually saving the file.
By default, disk and memory-based caching is enabled in Glide as long as the same filename, path, or URL are used to obtain the image on each Glide.load(...). If you'd like to manipulate how the caching occurs, use the DiskCacheStrategy enum to control that every time you load the image:
Glide.with(c)
.load(images.get(position))
.diskCacheStrategy(DiskCacheStrategy.SOURCE) # Will cache the source downloaded image before any transformations are applied
.placeholder(R.mipmap.ic_launcher)
.into(holder.img);
If you still want to save the file for other reasons, use a SimpleTarget instead of loading directly into your ImageView like so:
Glide.with(c)
.load(images.get(position))
.diskCacheStrategy(DiskCacheStrategy.SOURCE) # Will cache the source downloaded image before any transformations are applied
.placeholder(R.mipmap.ic_launcher)
.asBitmap()
.into(new SimpleTarget<GlideDrawable>() {
#Override
public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
holder.img.setImageDrawable(new BitmapDrawable(bitmap));
saveImage(bitmap); # This being an encapsulation of the steps outlined earlier
}
});

Image could not be successfully loaded via Picasso and Target

i´m using Picasso and Target for downloading an image and saving it as a bitmap to pass it into an Object which i use for and RecyclerView.
But when I try to download the image the Target also loads the onBitmapFailed or onPrepareLoad and the bitmapis not successfully received...
where´s the bug in my code? The URL is absolutely correct. when i take the passed URL and paste it in chrome browser the image shows...
Code
//Get Bitmap
targetForBitmap = new Target() {
#Override
public void onBitmapLoaded (final Bitmap responseBitmap, Picasso.LoadedFrom from){
bitmap = responseBitmap;
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.i("prepareLoad", "onPrepereLoad ääääääääääääääääääää ");
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.i("onBitmapFailed", "onBitmapFailed xxxxxxxxxxxxxxxx");
}
};
String url = "Http://" + server_wan + ":" + port_wan + "/" + server_path + "/Produktbilder/" + product_image + ".png";
Log.i("url", url);
Picasso.with(SpeisekarteActivity.this)
.load(url)
.into(targetForBitmap);
targetForBitmap is string instance at beginning of the class (private Target targetForBitmap)
Please provide the imageview where you want to load the image inside the onBitmapLoaded.
Try using .placeholder(drawable) and .error(drawable) with picasso.Use it after .load function.
Try checking out here:
[1]: Picasso Library, Android: Using Error Listener

Is there a way to load image as bitmap to Glide

Im looking for a way to use bitmap as input to Glide. I am even not sure if its possible. It's for resizing purposes. Glide has a good image enhancement with scale. The problem is that I have resources as bitmap already loaded to memory. The only solution I could find is to store images to temporary file and reload them back to Glide as inputStream/file.. Is there a better way to achieve that ?
Please before answering .. Im not talking about output from Glide.. .asBitmap().get() I know that.I need help with input.
Here is my workaround solution:
Bitmap bitmapNew=null;
try {
//
ContextWrapper cw = new ContextWrapper(ctx);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File file=new File(directory,"temp.jpg");
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
//
bitmapNew = Glide
.with(ctx)
.load(file)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into( mActualWidth, mActualHeight - heightText)
.get();
file.delete();
} catch (Exception e) {
Logcat.e( "File not found: " + e.getMessage());
}
I'd like to avoid writing images to internal and load them again.That is the reason why Im asking if there is way to to have input as bitmap
Thanks
For version 4 you have to call asBitmap() before load()
GlideApp.with(itemView.getContext())
.asBitmap()
.load(data.getImageUrl())
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {}
});
}
More info: http://bumptech.github.io/glide/doc/targets.html
This solution is working with Glide V4.
You can get the bitmap like this:
Bitmap bitmap = Glide
.with(context)
.asBitmap()
.load(uri_File_String_Or_ResourceId)
.submit()
.get();
Note: this will block the current thread to load the image.
A really strange case, but lets try to solve it. I'm using the old and not cool Picasso, but one day I'll give Glide a try.
Here are some links that could help you :
Bitmap POC
Supporting bitmaps topic
Someone also facing your problem
And actually a cruel but I think efficient way to solve this :
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Glide.with(this)
.load(stream.toByteArray())
.asBitmap()
.error(R.drawable.ic_thumb_placeholder)
.transform(new CircleTransform(this))
.into(imageview);
I'm not sure if this will help you, but I hope it can make you a step closer to the solution.
There is little changes according to latest version of Glide. Now we need to use submit() to load image as bitmap, if you do not class submit() than listener won't be called.
here is working example i used today.
Glide.with(cxt)
.asBitmap().load(imageUrl)
.listener(new RequestListener<Bitmap>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object o, Target<Bitmap> target, boolean b) {
Toast.makeText(cxt,getResources().getString(R.string.unexpected_error_occurred_try_again),Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onResourceReady(Bitmap bitmap, Object o, Target<Bitmap> target, DataSource dataSource, boolean b) {
zoomImage.setImage(ImageSource.bitmap(bitmap));
return false;
}
}
).submit();
It is working and I'm getting bitmap from listener.
Please use Implementation for that is:
implementation 'com.github.bumptech.glide:glide:4.9.0'
Glide.with(this)
.asBitmap()
.load("http://url")
.into(new CustomTarget <Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition <? super Bitmap> transition) {
// you can do something with loaded bitmap here
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
Most of the API's and methods of Glide are now deprecated.
Below is working for Glide 4.9 and upto Android 10.
For image URI
Bitmap bitmap = Glide
.with(context)
.asBitmap()
.load(image_uri_or_drawable_resource_or_file_path)
.submit()
.get();
Use Glide as below in build.gradle
implementation 'com.github.bumptech.glide:glide:4.9.0'
The accepted answer works for previous versions, but in new versions of Glide use:
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(android.R.drawable.waiting);
requestOptions.error(R.drawable.waiting);
Glide.with(getActivity()).apply(requestOptions).load(imageUrl).into(imageView);
Courtesy
here's another solution which return you a bitmap to set into your ImageView
Glide.with(this)
.load(R.drawable.card_front) // you can pass url too
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
// you can do something with loaded bitmap here
imgView.setImageBitmap(resource);
}
});
This worked for me in recent version of Glide:
Glide.with(this)
.load(bitmap)
.dontTransform()
.into(imageView);
For what is is worth, based upon the posts above, my approach:
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri imageUri = Uri.withAppendedPath(sArtworkUri, String.valueOf(album_id));
then in the adapter:
// loading album cover using Glide library
Glide.with(mContext)
.asBitmap()
.load(imageUri)
.into(holder.thumbnail);
Updated answer 2022 Aug
Glide.with(context)
.asBitmap()
.load(uri) // Uri, String, File...
.into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, Transition<? super Bitmap> transition) {
useIt(resource);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
onResourceReady : The method that will be called when the resource load has finished.
resource parameter is the loaded resource.
onLoadCleared : A mandatory lifecycle callback that is called when a load is cancelled and its resources are freed. You must ensure that any current Drawable received in onResourceReady is no longer used before redrawing the container (usually a View) or changing its visibility.
placeholder parameter is the placeholder drawable to optionally show, or null.
In Kotlin,
Glide.with(this)
.asBitmap()
.load("https://...")
.addListener(object : RequestListener<Bitmap> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Bitmap>?,
isFirstResource: Boolean
): Boolean {
Toast.makeText(this#MainActivity, "failed: " + e?.printStackTrace(), Toast.LENGTH_SHORT).show()
return false
}
override fun onResourceReady(
resource: Bitmap?,
model: Any?,
target: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
//image is ready, you can get bitmap here
return false
}
})
.into(imageView)
For 2021 :
val bitmap=Glide.with(this).asBitmap().load(imageUri).submit().get()

Updating ImageView based on URL

I have spent a lot of time trolling through multiple different threads concerning this topic, but I have yet to find an answer that works well with my code (Android SDK 23, in 2016). A lot of the answers are deprecated, and others just flat-out don't work like they're supposed to, and I was wondering if I could get a solid answer on this:
I am trying to include a Pokemon sprite (static image) in my program from Serebii. nums is a variable indicating the Pokemon's dex number (this one functions correctly, I promise). And this code is running in the main UI thread, which I know is frowned upon, but right now I'm trying to get the image loading, and then the smoothness of the app down. I don't really need a Bitmap, per se, but I need my ImageView to update and display the image given by the URL. How do I do it?
URL url = null;
try {
url = new URL("http://www.serebii.net/xy/pokemon/" + nums + ".png");
} catch (MalformedURLException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
mImageView.setImageBitmap(bmp);
Just use Picasso library, it will do all your image loading. You only need to provide the url of the image correctly.
String url = "http://www.serebii.net/xy/pokemon/" + nums + ".png";
Picasso.with(yourContext)
.load(url)
.into(mImageView);
You can use Picasso Library to load images.
a) Add Gradle into your project.
compile 'com.squareup.picasso:picasso:2.5.2'
b) Usage
Picasso.with(context).load("http://www.serebii.net/xy/pokemon/" + nums + ".png").into(imageView);
Also there are another libraries, you can use like
Fresco by Facebook, Universal Image loader
You can try using Picasso as:
Picasso.with(context)
.load(url)
.into(imageview);
Or use Universal Image loader as:
ImageLoader imageLoader = new ImageLoader(context);
imageLoader.displayImage(imageUri, imageView);
Use the Piassco library for it..Library link
For setting the Bitmap on the ImageView
Picasso.with(getContext()).load("your url").into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//do what ever you want with your bitmap
imgView.setImageBitmap(loadedImage);///imgView is use to set the image in it
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
And another method of Picasso :-
Picasso.with(this)
.load("your_image_url")
.placeholder(R.drawable.no_image)
.error(android.R.drawable.stat_notify_error)
.networkPolicy(NetworkPolicy.OFFLINE)//user this for offline support
.into(YOUR_IMAEGVIEW);
OR
You can also use the Universal Image Loader..Here is the link Universal image loader
ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getActivity()));
imageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.YOUR_DRAWABLE)
.showImageForEmptyUri(R.drawable.YOUR_DRAWABLE)
.showImageOnFail(R.drawable.YOUR_DRAWABLE)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
imageLoader.displayImage("your_image_url", YOUR_IMAGEVIEW, null);

Categories

Resources