46

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

Maher Abuthraa
  • 17,493
  • 11
  • 81
  • 103

13 Answers13

79

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

Teffi
  • 2,498
  • 4
  • 21
  • 40
26

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.

Tom Sabel
  • 3,935
  • 33
  • 45
19

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 :

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.

Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
Yurii Tsap
  • 3,554
  • 3
  • 24
  • 33
  • Just because of my interest, why are you facing such kind of issue? Can't you load your images directly with Glide from an url etc.? – Yurii Tsap Feb 16 '17 at 16:42
  • "Efficient": I/O on UI thread? Compress just to decompress? Use the POC to squeeze it through the pipeline instead. Even just calling the transformation directly in the background while creating the image would be better. – TWiStErRob Feb 16 '17 at 18:33
  • @YuriiTsap I am making screen shots from bitmap of views in memory. These views are not just images.. – Maher Abuthraa Feb 16 '17 at 18:40
  • @YuriiTsap I have case for your question. I using XML RPC odoo api which returns image in base64 json string format only. – Ashish Sahu Nov 29 '17 at 18:29
13

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.

Boken
  • 4,825
  • 10
  • 32
  • 42
Ashu Kumar
  • 832
  • 19
  • 38
7

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) { 
 } 
});
Arslan Maqbool
  • 519
  • 1
  • 7
  • 21
6

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'
Mayuri Khinvasara
  • 1,437
  • 1
  • 16
  • 12
5

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

Sam Judd
  • 7,317
  • 1
  • 38
  • 38
Safeer
  • 1,407
  • 1
  • 25
  • 29
  • Don't use setDefaultRequestOptions for an individual request. It's only useful if you want to apply the same options across all requests in a particular Activity or Fragment. To apply options to a specific request, use .apply(RequestOptions): http://bumptech.github.io/glide/doc/options.html#requestoptions – Sam Judd Oct 13 '17 at 18:10
4

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);
                }
            });
Ankush Bist
  • 1,862
  • 1
  • 15
  • 32
3

This worked for me in recent version of Glide:

Glide.with(this)
        .load(bitmap)
        .dontTransform()
        .into(imageView);
Rajeev Jayaswal
  • 1,423
  • 1
  • 20
  • 22
2

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);
Theo
  • 2,012
  • 1
  • 16
  • 29
2

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.

ucMedia
  • 4,105
  • 4
  • 38
  • 46
1

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)
Kishan Solanki
  • 13,761
  • 4
  • 85
  • 82
1

For 2021 :

  val bitmap=Glide.with(this).asBitmap().load(imageUri).submit().get()
Saurabh Dhage
  • 1,478
  • 5
  • 17
  • 31