Hot questions for Using Glide in android image

Top 10 Java Open Source / Glide / android image

Question:

I'm looking to upgrade my app from Glide v3 to Glide v4. I need to know how long loop is of a gif that is loaded through Glide.

v3 Code:

int duration = 0;
GifDecoder decoder = gifDrawable.getDecoder();
for (int i = 0; i < gifDrawable.getFrameCount(); i++) {
    duration += decoder.getDelay(i);
}

It looks like the GifDecoder is no longer exposed with Glide v4. How do I go about calculating this without it, or how do I obtain the decoder now?


Answer:

Here's a nasty way to acquire GifDecoder using reflection:

 Class gifStateClass = Class.forName("com.bumptech.glide.load.resource.gif.GifDrawable$GifState");
 Field frameLoaderField = gifStateClass.getDeclaredField("frameLoader");
 frameLoaderField.setAccessible(true);
 Object frameLoader = frameLoaderField.get(gifDrawable.getConstantState());

 Class frameLoaderClass = Class.forName("com.bumptech.glide.load.resource.gif.GifFrameLoader");
 Field gifDecoderField = frameLoaderClass.getDeclaredField("gifDecoder");
 gifDecoderField.setAccessible(true);
 GifDecoder gifDecoder = (GifDecoder) gifDecoderField.get(frameLoader);

 int duration = 0;
 for (int i = 0; i < gifDrawable.getFrameCount(); i++) {
     duration += gifDecoder.getDelay(i);
 }

This should not be considered as a stable/reliable solution as long as the API might change. Nevertheless, to quick solve the issue this will certainly work.

I can see an appropriate issue opened, will update the answer as soon as something changes.

Question:

I have created an gradient xml in drawable folder of my project. I want to load that xml in an ImageView using Glide. How can I do that ?

Simple loading of image in ImageView using Glide:

Glide.with(LoginActivity.this).load(R.drawable.a270).asBitmap().diskCacheStrategy(DiskCacheStrategy.RESULT).into(backgroundImage);

But if I use the same code above replacing R.drawable.a270 with R.drawable.gradient_background with a drawable xml its not working.


Answer:

Please try this -

Glide.with(LoginActivity.this).load("").error(R.drawable.gradient_background).diskCacheStrategy(DiskCacheStrategy.RESULT).into(backgroundImage);

OR

Glide.with(LoginActivity.this).load(null).fallback(R.drawable.gradient_background).diskCacheStrategy(DiskCacheStrategy.RESULT).into(backgroundImage);

I doubt you are using VectorDrawable or animated drawable. Please refer this and this for more information on this.

Question:

so I want to be able to grab my images from my s3 bucket and (using glide or picasso) load that image into an imageview. (I don't want to download that image into my phone).

currently i have this:

 downloadButton = (Button) findViewById(R.id.cognito_s3DownloadButton);
        downloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "fromAWS");
                observer = transferUtility.download("zivit-card-images","image1", file);
                Glide.with(getBaseContext()).load("image in byes? or url?").centerCrop().into(myImageView);
            }
        });

Again, how do i retrieve the image from s3 and insert it into an imageview?


Answer:

public String downloadimage()

    {

        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR, +1);
        Date oneHourLater = cal.getTime();
        AmazonS3 s3 = new AmazonS3Client(credentialsProvider);
        URL url = s3.generatePresignedUrl(
                "testproject12345",
                "first.jpg",
                oneHourLater
        );
        Log.e("url was", url.toString());
        String urlstring = url.toString();
        return urlstring;
    }

catch that function in your activity


download = (Button)findViewById(R.id.download);
        final ImageView imageview = (ImageView) findViewById(R.id.image);
        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

 download1 = new Uploader(getmain().getCredentialsProvider(),getApplicationContext());


                String url = download1.downloadimage();
                Picasso.with(getApplicationContext())
                        .load(url)
                        .into(imageview);


            }
        });

Question:

I am using glide library to load image url in image view.

Glide.with(context)
                .load(imageurl)
                .apply(RequestOptions.circleCropTransform())
                .into(holder.thumbnail);

Actually, the image is loaded fine with rounded image.

I need the image to be loaded with rounded + grayscale image

Can this be done by using glide lib?


Answer:

You can use Android's android.graphics.ColorMatrix class to set the saturation to 0 for making an ImageView grayscale.

You can achieve what you want in two steps. 1. Use Glide to make the ImageView rounded. 2. After that use ColorMatrix class to make the ImageView grayscale.

Glide.with(context)
.load(imageurl)
.apply(RequestOptions.circleCropTransform())
.into(holder.thumbnail);

ColorMatrix colorMatrix = new ColorMatrix();
colorMatrix.setSaturation(0);
ColorMatrixColorFilter filter = new ColorMatrixColorFilter(colorMatrix);
holder.thumbnail.setColorFilter(filter);

Question:

I'm implemented Glide library to load image in ImageView it's working fine.

Dependency:

compile "com.github.bumptech.glide:glide:4.5.0"
annotationProcessor "com.github.bumptech.glide:compiler:4.5.0"
compile "jp.co.cyberagent.android.gpuimage:gpuimage-library:1.3.0"

In Adapter:

                    Glide.with(context)
                    .load(ImageUrl)
                    .apply(bitmapTransform(new jp.wasabeef.glide.transformations.BlurTransformation(25)
                    ).diskCacheStrategy(DiskCacheStrategy.ALL))
                    .apply(new RequestOptions()
                            .placeholder(R.mipmap.ic_launcher))
                    .into(view);

Issue is that when I'm upload image and display in recyclerview and get URL from API then it's display previously added image from cache instead of new one. I just need to add new image in first position instead of refresh whole list.

By using this:

.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)

Above code refresh whole list because clear whole cache data. I just need to display new uploaded image in list.


Answer:

Please set like this:-

Glide.with(context)
        .load(img_url)
        .apply(new RequestOptions()
        .placeholder(R.mipmap.personal_pic)
        .diskCacheStrategy(DiskCacheStrategy.ALL))
        .into(iv_profile_pic);

Question:

I've started to face an issue with Glide Image Download.

My application is running on Glide version 4.8.0 and minSdkVersion 21, targetSdkVersion 26, and compileSdkVersion 28.

The problem is Glide is unable to download an image from Apple News and causes it to lock and crash application. The URL of the image is https://c.apple.news/AgEXQU9SSmFycEhYUUVlSkxKUE52XzN1M1EAMA

The code to execute the image download is:

Glide.with(context)
.setDefaultRequestOptions(getRequestOptionsForImage(item.ContentPersonStatusUpdate.widthURLImageWidth,context.getResources().getDimensionPixelSize(R.dimen.image_height_external_link),context))
.asBitmap()
.load(https://c.apple.news/AgEXQU9SSmFycEhYUUVlSkxKUE52XzN1M1EAMA)
.into(imageViewContent);

public static RequestOptions getRequestOptionsForImage(int width, int height, Context context){
        return  new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).override(width,height).placeholder(context.getDrawable(R.drawable.ic_news_thumbnail_loading));
    }

Any idea/solution about this issue? This problem only occurs for Apple News Image URLs.

***UPDATE

I've tried to download image with the code below. Getting no responses, even catch never firing.

new DownloadImageTask(imageViewContent).execute(https://c.apple.news/AgEXQU9SSmFycEhYUUVlSkxKUE52XzN1M1EAMA);


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 bmp = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                bmp = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bmp;
        }
        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }

Answer:

Serkan your code is correct except the request option part. i try below code and worked fine:

    String url="https://c.apple.news/AgEXQU9SSmFycEhYUUVlSkxKUE52XzN1M1EAMA";

    RequestOptions requestOptions = new RequestOptions();
    requestOptions.error(R.drawable.img_placeholder);
    Glide.with(context)
            .setDefaultRequestOptions(requestOptions)
            .load(url)
            .into(imgImage);

i try your code too without request option like below:

    Glide.with(context)
            .asBitmap()
            .load(url)
        .into(imgImage);

and worked fine too

when i try to use with your request option code its tell me use @RequiresApi(LOLLIPOP) annotation. may you are testing app in below api and the method doesn't work.

Question:

I am using Glide v4 to load a bitmap that can then be used to as a marker on the map. When I use the deprecated SimpleTarget like so everything works fine.

GlideApp.with(getContext()).asBitmap().load(url)
    .into(new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

            // load bitmap as marker
        }
    });

When I try removing the deprecated code and using Target<Bitmap> like given below I can see the onLoadStarted gets called but the onResourceReady is never called neither is the onLoadFailed.

GlideApp.with(getContext()).asBitmap()
    .load(UrlHelper.createUrl(poi.getMapMarker()))
    .into(marketBitmap);

private Target<Bitmap> marketBitmap = new Target<Bitmap>() {
    @Override
    public void onLoadStarted(@Nullable Drawable placeholder) {
        Log.d("GlideMar", "marker load started");
    }

    @Override
    public void onLoadFailed(@Nullable Drawable errorDrawable) {
        Log.e("GlideMar", "marker load failed");
    }

    @Override
    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
        Log.d("GlideMar", "onResourceReady");
    }

    @Override
    public void onLoadCleared(@Nullable Drawable placeholder) {
        Log.d("GlideMar", "marker onLoadCleared");
    }

    @Override
    public void getSize(@NonNull SizeReadyCallback cb) {

    }

    @Override
    public void removeCallback(@NonNull SizeReadyCallback cb) {

    }

    @Override
    public void setRequest(@Nullable Request request) {

    }

    @Nullable
    @Override
    public Request getRequest() {
        return null;
    }

    @Override
    public void onStart() {
        Log.d("GlideMar", "marker onStart");
    }

    @Override
    public void onStop() {
        Log.d("GlideMar", "marker onStop");
    }

    @Override
    public void onDestroy() {
        Log.d("GlideMar", "marker onDestroy");
    }
};

Answer:

From Glide Custom Targets documentation.

If you’re using a custom Target and you’re not loading into a View that would allow you to subclass ViewTarget, you’ll need to implement the getSize() method.

So in your case just put the below code in getSize method

@Override
public void getSize(SizeReadyCallback cb) {
    cb.onSizeReady(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
}

Now the onResourceReady method will be called when you run the app.

Question:

I have issue with image loading. Only some of the images are not loading. I have tried using glide and image loader.

Glide code :

Glide.with(context)
                .load(model.getImage4x3().trim()+"?w=430&h=275")
                .into(holder.mBinding.ivPromotion);

Glide dependency :

 implementation 'com.github.bumptech.glide:glide:4.9.0'

I have also tried : 3.9.0 , 4.0.0 , 3.6.1 , 3.8.0

Error :

load failed for http://mcms-uat.mercatus.com.sg/en/-/media/E3BE24B58E1144228C62D2364F4FF543.ashx?rev=50ebbcc572e6488c826a23276ab9bf08 with size [320x240]
    class com.bumptech.glide.load.engine.GlideException: Failed to load resource
    There were 4 causes:
    java.io.IOException(java.lang.RuntimeException: setDataSource failed: status = 0x80000000)
    java.io.IOException(java.lang.RuntimeException: setDataSource failed: status = 0x80000000)
    java.io.IOException(java.lang.RuntimeException: setDataSource failed: status = 0x80000000)
    java.io.IOException(java.lang.RuntimeException: setDataSource failed: status = 0x80000000)
     call GlideException#logRootCauses(String) for more detail
      Cause (1 of 6): class com.bumptech.glide.load.engine.GlideException: Failed LoadPath{DirectByteBuffer->Object->Drawable}, DATA_DISK_CACHE, http://mcms-uat.mercatus.com.sg/en/-/media/E3BE24B58E1144228C62D2364F4FF543.ashx?rev=50ebbcc572e6488c826a23276ab9bf08
        Cause (1 of 3): class com.bumptech.glide.load.engine.GlideException: Failed DecodePath{DirectByteBuffer->GifDrawable->Drawable}
        Cause (2 of 3): class com.bumptech.glide.load.engine.GlideException: Failed DecodePath{DirectByteBuffer->Bitmap->Drawable}
        Cause (3 of 3): class com.bumptech.glide.load.engine.GlideException: Failed DecodePath{DirectByteBuffer->BitmapDrawable->Drawable}

Image :

http://mcms-uat.mercatus.com.sg/en/-/media/E3BE24B58E1144228C62D2364F4FF543.ashx?rev=50ebbcc572e6488c826a23276ab9bf08

Please check!


Answer:

1) Add below dependencies into app/build.gradle      
    annotationProcessor 'com.github.bumptech.glide:compiler:your_glide_version'

2) put android:largeHeap="true" into tag of manifest file

3) and use like below

    ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
    Glide.with(context)  // this
       .load(imagePath)
       .placeholder(R.drawable.loading_spinner)
       .into(imageView);

Question:

I'm loading an image to my app using Glide from https://source.unsplash.com/daily?nature It is a free to use image platform and the link above updates images daily.

However, Glide is showing the old cached image, even if the image has been updated on the site.

Code used :

Glide.with(this)
             .load("https://source.unsplash.com/daily?nature")
             .into(imageView);

Glide Version: 4.0.0


Answer:

public static void loadImageWithGlide(Context theCtx, ImageView theImageView, String theUrl) {
        // skipMemoryCache true, because it load the same image from cache when URL not change.
        Glide.with(theCtx)
                .load(theUrl)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .fitCenter()
                .into(theImageView);

        // use below lines, to enable memory cache. so that image does not load again ones loaded
        //.diskCacheStrategy(DiskCacheStrategy.ALL)
        //.skipMemoryCache(false)
    }