Android - How to Load Image by name using Glide - android

Hi I'm using Glide to load image from my drawable folder and all works fine, this is my code :
Glide.with(this).load(R.drawable.my_drawable_image_name).into(myImageView);
I'm wondering if there is a way to load the image just by name, something like :
Glide.with(this).load(my_drawable_image_name).into(myImageView);
because i want to get the image name dynamically ,for example from a database...
do you have any suggestion about that?
thanks in advance.

Call getImage method for get Drawable using Name only.
Glide.with(this).load(getImage(my_drawable_image_name)).into(myImageView);
public int getImage(String imageName) {
int drawableResourceId = this.getResources().getIdentifier(imageName, "drawable", this.getPackageName());
return drawableResourceId;
}

Try this:
Glide.with(this)
.load(getResources()
.getIdentifier("my_drawable_image_name", "drawable", this.getPackageName())
.into(myImageView);

Use Uri.
String image = "image.jpg";
String completePath = Environment.getExternalStorageDirectory() + "/" + image;
File file = new File(completePath);
Uri uri = Uri.fromFile(file);
Glide.with(this).load(uri).into(imageView);

You can use the following code to get Bitmap, Drawable from URL using Glide. This code snippet is used to set drawableEnd/drawbleRight for TextView.
Glide.with(context)
.asBitmap()
.load(url)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(
bitmap: Bitmap,
transition: Transition<in Bitmap>?
) {
val drawable: Drawable = BitmapDrawable(
context.resources,
bitmap
)
textView.setCompoundDrawablesWithIntrinsicBounds(
null, null, drawable, null
)
}
override fun onLoadCleared(placeholder: Drawable?) {
}
})

I think you should try this
Glide.with(mContext)
.load(mContext.getResources().getDrawable(R.drawable.my_drawable_image_name))
.placeholder(R.mipmap.icon)
.into(myImageView);
Load method of Glide also accept drawable object as a parameter to load image. You just have to get the drawable object from your drawable image and pass it to the load method.
I wanted rounded-corner of image and that's why I used Glide. In your case, You should use this.
myImageView.setImageDrawable(mContext.getResources().getDrawable(R.drawable.my_drawable_image_name))
If you also want rounded image use this.
Glide.with(mContext)
.load(Glide.with(mContext)
.transform(new FitCenter(), new RoundedCorners((int) mContext.getResources().getDimension(R.dimen._10sdp))
.placeholder(R.mipmap.icon)
.into(myImageView);

Easy way to load image from drawable by using Name
Glide.with(context)
.load(context.getResources().getIdentifier("my_drawable_image_name", "drawable", context.getPackageName()))
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.placeholder(R.drawable.add_photo_placeholder)
.error(R.color.red)
.override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.into(userPhoto);

Related

how can I show a video thumbnail from a video path?

I want to show a video thumbnail in an ImageView from a video path on storage. Is there a function that takes a video path and returns a bitmap of a thumbnail? I get the video path by this code:
public ArrayList<String> getAllMedia() {
HashSet<String> videoItemHashSet = new HashSet<>();
String[] projection = {MediaStore.Video.VideoColumns.DATA, MediaStore.Video.Media.DISPLAY_NAME};
Cursor cursor = getContext().getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
try {
cursor.moveToFirst();
do {
videoItemHashSet.add((cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA))));
} while(cursor.moveToNext());
cursor.close();
} catch(Exception e) {
e.printStackTrace();
}
ArrayList<String> downloadedList = new ArrayList<>(videoItemHashSet);
return downloadedList;
}
It is the default way to create a thumbnail.
For Mini Kind
Bitmap thumb;
//MINI_KIND, size: 512 x 384 thumbnail
thumb = ThumbnailUtils.createVideoThumbnail(filePath, MediaStore.Video.Thumbnails.MINI_KIND);
img_tumbnail.setImageBitmap(thumb);
For Micro Kind
Bitmap thumb;
//MICRO_KIND, size: 96 x 96 thumbnail
thumb= ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MICRO_KIND);
img_tumbnail.setImageBitmap(thumb);
Also, you can use Glide for Url as well as Video path of Device.
Glide.with(context).with(this)
.asBitmap()
.load(videoFilePath) // or URI/path
.into(imgView); //imageview to set thumbnail to
also, you can resize thumbnail by using .override(50,50) with Glide.
Use Glide lib
to show thumbnail from local storage
String filePath = "/storage/emulated/0/Pictures/example_video.mp4";
GlideApp
.with(context)
.asBitmap()
.load(Uri.fromFile(new File(filePath)))
.into(imageViewGifAsBitmap);
You can use ThumbnailUtils to load video thumb in 3 format:
MINI_KIND : Good for media detail view
FULL_SCREEN_KIND : Good for header
MICRO_KIND : Good for recycleView
Ex:
holder.videoThumb.setImageBitmap(ThumbnailUtils.createVideoThumbnail(getItem(position).videoURL, MediaStore.Images.Thumbnails.MICRO_KIND))
The biggest drawback is that ThumbnailUtils operate on UI thread so if you try to use this method in a recycleView then it gone make your app skip frames. Your RecycleView will have laggy scroll and if you have more than 7 items then your app will start throwing ANR.
That means you need to create AsyncTask or Threads which again might lead to memory leaks.
Conclusion; Glide is better in loading video thumbs.
Here DiskCacheStrategy.RESULT is important parameter which worked for me and give a smooth fast scroll in recycle view.
Glide.with(context).load(getItem(position).videoURL)
.asBitmap()
.placeholder(R.drawable.app_icon)
.centerCrop()
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.into(holder.videoThumb)
I have 3rd method to set thumbnail of image/video.
Hope it will help you.
1) ThumbnailUtils --> Effective but Slow
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(thumbPath, MediaStore.Video.Thumbnails.MINI_KIND);
holder.ivThumb.setImageBitmap(thumb);
2) FFmpegMediaMetadataRetriever --> Very Effective but Slow
FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
try {
retriever.setDataSource(thumbPath);
thumb.setImageBitmap(retriever.getFrameAtTime(0));
} catch (Exception ex) {
// Assume this is a corrupt file
}
3) Glide --> Effective and Fast
RequestOptions options = new RequestOptions()
.centerCrop()
.placeholder(android.R.drawable.stat_notify_error)
.error(android.R.drawable.stat_notify_error);
Glide.with(context)
.load(thumPath)
.apply(options)
.into(thumb);
If anyone is looking for a Kotlin version. You can try this extension function.
It is using coil.
/**
* https://github.com/coil-kt/coil/issues/413
*/
fun ImageView.setThumbnail(uri: Uri, frameMillis: Long = 2000) {
val imageLoader = ImageLoader.Builder(context)
.componentRegistry {
add(VideoFrameFileFetcher(context))
add(VideoFrameUriFetcher(context))
}.build()
val request = ImageRequest.Builder(context)
.data(uri)
.videoFrameMillis(frameMillis)
.target(this)
.fetcher(VideoFrameUriFetcher(context))
.build()
findViewTreeLifecycleOwner()?.lifecycleScope?.launch(Dispatchers.Main) {
imageLoader.execute(request)
}
}
In some devices not working for me without FileDescriptorBitmapDecoder
So I used following code with FileDescriptorBitmapDecoder
public static void loadLocalVideoThumbanail(Context context, String path, final ImageView imageView) {
try {
if (path == null || path.isEmpty())
return;
BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
int microSecond = 1000000;// 1st second as an example
VideoBitmapDecoder videoBitmapDecoder = new VideoBitmapDecoder(microSecond);
FileDescriptorBitmapDecoder fileDescriptorBitmapDecoder = new FileDescriptorBitmapDecoder(videoBitmapDecoder, bitmapPool, DecodeFormat.PREFER_ARGB_8888);
Glide.with(context).load(path).asBitmap().thumbnail(0.6f)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.dontAnimate()
.videoDecoder(fileDescriptorBitmapDecoder)
.override(200,200)
.into(imageView);
} catch (Exception e) {
MyLog.e(TAG, "LoadImage: ", e);
}
}

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()

How do I preload multiple images using Glide for later use

I have many images that I want to preload and use later on. I want to make it so that I can load an image, hide it, and then load it again whenever I want.
https://github.com/bumptech/glide/wiki/Loading-and-Caching-on-Background-Threads#into
I have tried following this, but it doesn't work.
Here is my code:
private void loadImage() throws ExecutionException, InterruptedException {
FutureTarget<File> future = Glide.with(this)
.load(R.drawable.image1)
.downloadOnly(500, 500);
File cacheFile = future.get();
Bitmap myBitmap = Glide.with(this)
.load(cacheFile)
.asBitmap()
.centerCrop()
.into(500, 500)
.get();
Glide.with(this).load(myBitmap).into(image_name);
}
I tried using Picasso because I read that this can easily be done in it, but the images take really long to load in Picasso.

Load Drawable object into ImageView using Picasso or Glide or any cashing library - Android

I need to load App icon into image view. It is too slow to load it in list view.
I tried to use Picasso or Glide to load it.
I could not find out how to load Drawable object (NOT FROM RESOURCES) into image view using any of those libraries?
The function for getting the drawable:
public Drawable getIcon() {
if (icon == null) {
icon = getResolveInfo().loadIcon(ctx.getPackageManager());
}
return icon;
}
You can do this
Drawable icon = ....
Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bitmapdata = stream.toByteArray();
Glide.with(context)
.load(bitmapdata)
.into(imageView);
But i am not sure that in this case the Glide (or Picasso) will be use the cache.
You can create your own RequestHandler for Picasso. There is a tutorial here.
For example,
class AppIconRequestHandler extends RequestHandler {
#Override
public boolean canHandleRequest(Request data) {
return true; // or do validation here
}
#Override
public Result load(Request request, int networkPolicy) {
// Not sure if DISK or correct or if it should be something else, but it works for me.
return new Result(yourApp.getIcon().bitmap, Picasso.LoadedFrom.DISK);
}
}
// When you want to show the icon
Picasso picasso = Picasso.Builder(context)
.addRequestHandler(new AppIconRequestHandler())
.build()
picasso.load(packageName)
.placeholder(placeholderIcon)
.into(imageView)
Don't forget to scale app icons, by the way! You can't rely on them to be small images and you may end up using a lot more ram than you need.
This one is using the Picasso library.
String url = "some url to your image";
ImageView thumbnail = (ImageView) findViewById(R.id.thumbnail);
Picasso.with(context).load(url).into(thumbnail);

Set image on imageview from url resources

I have image with url.
How can I assign this resource to an imageview inside my app?
Check this Picasso library and it very easy to load image url on imageview
http://square.github.io/picasso/
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
Try this :
URL url = new URL("http://yourURL.com/...");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
you must use picasso,
for example
Add this line in build.gradle
compile 'com.squareup.picasso:picasso:2.5.2'
and you code :
ImageView horario = (ImageView)findViewById(R.id.imageView4);
Picasso.with(this).load("http://i.imgur.com/DvpvklR.png").into(horario);
Documentation

Categories

Resources