Hot questions for Using Glide in bitmap

Question:

I want to load bitmap from server using Glide. If it's success then put it in my ImageView then add it to my ArrayList. If it's fail (broken url, no internet, etc) then set ImageView to my default image. But Glide's listener not working at all, also LogCat not show "onException" and "onResourceReady" at all. What's wrong with my code?

Glide.with(activity.getApplicationContext())
        .load(MainActivity.URL_SERVER + "/asset/" + imageUrl.getString(i))
        .signature(new StringSignature(String.valueOf(System.currentTimeMillis())))
        .listener(new RequestListener<String, GlideDrawable>() {
            @Override
            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                ivImage.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.noimage));
                return false;
            }
            @Override
            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                ivImage.setImageDrawable(resource);
                imageLoadedBitmap.add(((GlideBitmapDrawable) resource).getBitmap());
                return false;
            }
        });

Answer:

As of now, nothing in that method chain is actually triggering the image loading operation. You could use .into(ivImage) at the end and just use listener for adding bitmap to array. Or you could use .preload() for more customisation. Also, use .error(R.drawable.noimage) for error image.

Storing bitmaps in an array looks like a bad idea though. If you're loading images in a list, put glide call in your adapter and let glide take care of the catching itself.

Question:

How do I use Glide Library to get the bitmap because I want to draw that bitmap image on canvas. Glide only allows me to add image to ImageView.

Is there any way where I can get the refined bitmap by Glide so that I can draw that to canvas.

Currently I am using

Bitmap bitmapImage = BitmapFactory.decodeResource(getResources(), wallpaper_image_id);

and I get this error

java.lang.OutOfMemoryError: Failed to allocate a 43776012 byte allocation with 16767008 free bytes and 40MB until OOM

Answer:

Maybe a target is what you need. Take a look Here.

Glide.with(yourApplicationContext))
    .load(youUrl)
    .asBitmap()
    .into(new SimpleTarget<Bitmap>(myWidth, myHeight) {
        @Override
        public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
            // Do something with bitmap here.
        }
    };

Inside the onResourceReadyyou've got the bitmap ready to be loaded where you want.

EDIT

Your app crashes because you need to run code in the ui thread. Try this:

// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {....} // Your code goes inside the run method
};
mainHandler.post(myRunnable);

Question:

I have to send a downscaled bitmap to my database from Android (using Xamarin).

To do so, I read about Glide or Picasso. Glide seemed to be the best picture library so I've installed Glide-Xamarin 3.7.0.

But I don't get how to load an existing bitmap (from URI), downscale to specific[ish] resolution and save it into a byte[] array in order to send it with the Webservice I'm calling.

If anyone knows the recipe for that one, would be much appreciated.


Answer:

Finally I did it with Picasso

var bitmap = Picasso
             .With(context)
             .Load(originalBitmapUri)
             .Resize(reqWidth, reqHeight)
             .CenterInside()
             .OnlyScaleDown()
             .Get();

This one-liner returns me a resized Bitmap, from which I can call CompressAsync(.)

using (var stream = new MemoryStream())
{
    await bitmap.CompressAsync(Bitmap.CompressFormat.Jpeg, quality, stream);
    return stream.ToArray();
}

Question:

Hi am getting the error: cannot find symbol class GlideBitmapDrawable ,when i try to compile a project in android studio . How to resolve the error.

I have added these three dependencies in module:app

 implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
    implementation "com.github.bumptech.glide:okhttp3-integration:4.0.0-RC1"

Am getting here in import statement and code at GlideBitmapDrawable

import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
 try {
            GlideBitmapDrawable drawable = (GlideBitmapDrawable) photoView.getDrawable();
            bitmap = drawable.getBitmap();
        } 

Can any one please suggest what am missing in this?


Answer:

You need to use

BitmapDrawable.

Instead of

GlideBitmapDrawable

From docs of glide

GlideDrawable in Glide v3 has been removed in favor of the standard Android Drawable. GlideBitmapDrawable has been removed in favor of BitmapDrawable.

for more information please read Read Glide Drawables

Question:

Here is the code in which I am trying to download a large image..

RequestOptions requestOptions = new RequestOptions();
            requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
            requestOptions.skipMemoryCache(true);
Glide.with(this)
 .load(rogImage)
 .apply(requestOptions)
 .listener(new RequestListener<Drawable>() {
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
            return false;
        }

        @Override
        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
            ProgressBarHandler.unloadProgressScreen(getActivity());
            return false;
        }
    })
    .into(new SimpleTarget<Drawable>() {
        @Override
        public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
            tempImageView.setImageDrawable(resource)
        }

    });

I end up most of the time in onLoad failed method with OutOfMemoryError.

when I checked in the Device File Explorer the images is being downloaded but not loaded into image view second time, First time it works perfectly for large images.

I am repeating the same code for second time call.

Below is the actual error message given in android studio.

Glide: Root cause (1 of 13)
    java.lang.OutOfMemoryError: Failed to allocate a 210639956 byte allocation with 16777216 free bytes and 197MB until OOM
  at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
  at android.graphics.Bitmap.nativeCreate(Native Method)
  at android.graphics.Bitmap.createBitmap(Bitmap.java:975)
  at android.graphics.Bitmap.createBitmap(Bitmap.java:946)
  at android.graphics.Bitmap.createBitmap(Bitmap.java:913)
  at com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool.createBitmap(LruBitmapPool.java:149)
  at com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool.getDirty(LruBitmapPool.java:142)
  at com.bumptech.glide.load.resource.bitmap.Downsampler.setInBitmap(Downsampler.java:688)
  at com.bumptech.glide.load.resource.bitmap.Downsampler.decodeFromWrappedStreams(Downsampler.java:297)
  at com.bumptech.glide.load.resource.bitmap.Downsampler.decode(Downsampler.java:207)
  at com.bumptech.glide.load.resource.bitmap.Downsampler.decode(Downsampler.java:160)
  at com.bumptech.glide.load.resource.bitmap.ByteBufferBitmapDecoder.decode(ByteBufferBitmapDecoder.java:33)
  at com.bumptech.glide.load.resource.bitmap.ByteBufferBitmapDecoder.decode(ByteBufferBitmapDecoder.java:16)
  at com.bumptech.glide.load.engine.DecodePath.decodeResourceWithList(DecodePath.java:72)
  at com.bumptech.glide.load.engine.DecodePath.decodeResource(DecodePath.java:55)
  at com.bumptech.glide.load.engine.DecodePath.decode(DecodePath.java:45)
  at com.bumptech.glide.load.engine.LoadPath.loadWithExceptionList(LoadPath.java:58)
  at com.bumptech.glide.load.engine.LoadPath.load(LoadPath.java:43)
  at com.bumptech.glide.load.engine.DecodeJob.runLoadPath(DecodeJob.java:498)
  at com.bumptech.glide.load.engine.DecodeJob.decodeFromFetcher(DecodeJob.java:469)
  at com.bumptech.glide.load.engine.DecodeJob.decodeFromData(DecodeJob.java:455)
  at com.bumptech.glide.load.engine.DecodeJob.decodeFromRetrievedData(DecodeJob.java:407)
  at com.bumptech.glide.load.engine.DecodeJob.onDataFetcherReady(DecodeJob.java:376)
  at com.bumptech.glide.load.engine.DataCacheGenerator.onDataReady(DataCacheGenerator.java:95)
  at com.bumptech.glide.load.model.ByteBufferFileLoader$ByteBufferFetcher.loadData(ByteBufferFileLoader.java:74)
  at com.bumptech.glide.load.engine.DataCacheGenerator.startNext(DataCacheGenerator.java:75)
  at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:299)
  at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:266)
  at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:230)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
  at java.lang.Thread.run(Thread.java:818)
  at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:446)

you can check out the screenshot which shows that images are been downloaded and stored in device.


Answer:

Add this in manifest

  android:largeHeap="true"

Also Add this is app.gradle

 dexOptions {// Prevent OutOfMemory with MultiDex during the build phase
        javaMaxHeapSize "4g"
    }

Question:

I get image from a web service, i do following to display it in imageView.

Picasso.with(getApplicationContext()).load(imageURL).fit().centerCrop().into(ivNews);

2 days ago a 2048X1600 resolution images was uploaded on server, and all of sudden app start crashing with this exception Canvas: trying to draw too large(144609280bytes) bitmap

There is a possibility that the image uploaded on server was higher than the mentioned resolution, and server can upload more high resolution images in future as well.

I read this article, Its mentioned that glide is faster and better than picasso in terms of performance,

It also mentioned that if you use, .fit().centerCrop() then the performance is better, but i was already using these, and got these error message

I want to solve this by using picasso


Answer:

You could use scaleDown() to scale the image if it is of bigger size. You could use it like below.

Picasso  
.with(context)
.load(<image_url>)
.resize(2048, 1600)
.onlyScaleDown() // the image will only be resized if it's bigger than 2048x 1600 pixels.
.into(<image_view>);

Question:

I using below code

Glide.with(context)
     .load("file://"+bitmapList.get(position))
     .override(153,160)
     .crossFade()
     .centerCrop()
     .dontAnimate()
     .skipMemoryCache(true)
     .into(holder.thumbnail);

problem is that here .override(153,160) this line showing compile error like cannot resolve method override(int,int)

I got solution here: glide:4.3.1 override and placeholder features not work tried manyways it not working..please anyone help me

when i change like this

Glide.with(context)
     .load("file://"+bitmapList.get(position))
     .apply(new RequestOptions().override(153,160))
     .crossFade()
     .centerCrop()
     .dontAnimate()
     .skipMemoryCache(true)
     .into(holder.thumbnail); 

// I am getting error this line **.crossFade()**

Answer:

// I am getting error this line .crossFade()

Cross fades

Unlike Glide v3 does NOT apply a cross fade or any other transition by default to requests. Transitions must be applied manually.

To apply a cross fade transition to a particular load, you can use:

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

Glide.with(this)
            .load("https://i.stack.imgur.com/7CChZ.jpg?s=328&g=1")
            .transition(withCrossFade())
            .apply(new RequestOptions().override(100, 100)
                    .placeholder(R.drawable.ic_launcher_background)
                    .error(R.drawable.ic_launcher_background).centerCrop()
            )
            .into(imageView);

Question:

Today I'm trying to use Glide4 image loader in my android application while using this I had facing method not resolving problem. I have searched a lot and also found a solution, I have to created RequestOptions and use like this:

private void loadImages() {
    RequestOptions requestOptions = new RequestOptions();
    requestOptions.placeholder(R.drawable.circle_diff);
    requestOptions.centerCrop();
    Glide.with(this)
            .load("http://localhost/ImageRepo/profile.jpg")
            .apply(requestOptions)
    .into(new BitmapImageViewTarget(mBinding.profilePic){
        @Override
        protected void setResource(Bitmap resource) {
            RoundedBitmapDrawable circularBitmapDrawable =
                    RoundedBitmapDrawableFactory.create(getResources(), resource);
            circularBitmapDrawable.setCircular(true);
            mBinding.profilePic.setImageDrawable(circularBitmapDrawable);
        }
    });

but in .into method i got Cannot resolve method 'into(anonymous com.bumptech.glide.request.target.BitmapImageViewTarget) error. Whats happen ??

My App gradle dependencies:

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    implementation("com.github.bumptech.glide:glide:4.6.1") {
        exclude group: "com.android.support"
    }
    implementation "com.android.support:support-fragment:26.1.0"

    annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
}

Answer:

Try this Use requestOptions.circleCropTransform();

    RequestOptions requestOptions = new RequestOptions();                    
    requestOptions.placeholder(R.drawable.ic_launcher_background);           
    requestOptions.circleCropTransform();                                    
    requestOptions.transforms( new RoundedCorners(300));                     

     Glide.with(this)                                                        
          .load("https://i.stack.imgur.com/7CChZ.jpg?s=328&g=1")             
          .apply(requestOptions)                                             
          .into(imageView);        

OUTPUT

Question:

I'm trying to use the following code which I found from here to save thumbnail of a video at a specific time, but VideoBitmapDecoder doesn't accept int parameter. It only accepts Context or BitmapPool. What should I do?

BitmapPool bitmapPool = Glide.get(getApplicationContext()).getBitmapPool(); 
int microSecond = 6000000;// 6th second as an example 
VideoBitmapDecoder videoBitmapDecoder = new VideoBitmapDecoder(microSecond); 
FileDescriptorBitmapDecoder fileDescriptorBitmapDecoder = new FileDescriptorBitmapDecoder(videoBitmapDecoder, bitmapPool, DecodeFormat.PREFER_ARGB_8888); 
Glide.with(getApplicationContext()) .load(yourUri)
  .asBitmap()
  .override(50,50)//
  .videoDecoder(fileDescriptorBitmapDecoder)       .into(yourImageView);

Answer:

Root cause: From Glide v4 they changed APIs so I will give you 2 options to solve your problem. Option 1: Keep the current code and change Glide dependencies version in app.gradle file.

// implementation 'com.github.bumptech.glide:glide:4.8.0'
// annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
implementation 'com.github.bumptech.glide:glide:3.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:3.8.0'

Option 2: Keep the current Glide dependencies in app.gradle file and change your code.

int microSecond = 6000000;// 6th second as an example
RequestOptions options = new RequestOptions().frame(microSecond).override(50, 50);

Glide.with(getApplicationContext())
        .asBitmap()
        .load(videoUri)
        .apply(options)
        .into(yourImageView);

Update: If you want to process bitmap not display on a view

Glide.with(getApplicationContext())
                .asBitmap()
                .load(videoUri)
                .apply(options)
                .listener(new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Bitmap bitmap, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        // TODO: Process your bitmap here
                        return false;
                    }
                })
                .submit();

Question:

I have an image that is being saved in online server.

That's why I had to convert the image into string first. But I also want to show this picture in PDF form. So how can I use this picture as PNG.

Or is there any other way so I can show it on PDF using iTextpdf. I am confused. I searched a lot but nothing helped.

Here is my code (MainActivity):

String imageName = null;
final ImageSaver imageSaver = new ImageSaver(MainActivity.this);
if (imageUri != null && !imageUri.isEmpty()) {
    imageName = imageSaver.getFileName();
    Glide.with(MainActivity.this).asBitmap().load(imageUri)
        .listener(new RequestListener<Bitmap>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                // TODO : upload image here...
                imageSaver.save(resource);
                return true;
            }
        }).submit();
} else {
    Log.e(TAG, "uploadImageToServer: no image to upload!!!");
}

ImageSaver class :

public class ImageSaver {

    private static String directoryName = "images";

    public String getFileName() {
        return fileName;
    }

    private String fileName;
    private Context context;
    public ImageSaver(Context context) {
        this.context = context;
        this.fileName = generateFileName();
    }

    public String save(Bitmap bitmapImage) {
        String result= "";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(createFile());
            bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            result = fileName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return  result;
    }

    @NonNull
    private File createFile() {
        File directory = context.getDir(directoryName, Context.MODE_PRIVATE);
        if(!directory.exists() && !directory.mkdirs()){
            Log.e("ImageSaver","Error creating directory " + directory);
        }

        return new File(directory, fileName);
    }

    public static byte[] getImage(Context context, String imageName)
    {
        try {
            File directory = context.getDir(directoryName, Context.MODE_PRIVATE);
            File image = new File(directory, imageName);
            Bitmap b = BitmapFactory.decodeStream(new FileInputStream(image));
            //return BitmapUtils.convertBitmapToByteArrayUncompressed(b);
            return BitmapUtils.convertBitmapToByteArray(b);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }

    }

    private static String generateFileName() {
        DateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss");
        Date date = new Date();
        return "image_" + dateFormat.format(date) + ".jpeg";
    }
}

I have added images before from assets folders like this :

try {
            InputStream ims = getAssets().open("naam.PNG");
            Bitmap bmp = BitmapFactory.decodeStream(ims);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            Image image = Image.getInstance(stream.toByteArray());
            image.scaleToFit(75, 90);
            image.setAlignment(Element.ALIGN_CENTER);

            cl = new PdfPCell(image, true);
            cl.setHorizontalAlignment(Element.ALIGN_CENTER);
            cl.setVerticalAlignment(Element.ALIGN_CENTER);
            cl.setBorderColor(BaseColor.WHITE);
            cl.setFixedHeight(21);
            tableclerk.addCell(cl);
        }
        catch(IOException ex) { return; }
        tableclerk.setWidths(columnWidthsc);
        mDoc.add(tableclerk);

Answer:

Just Save Your image in .PNG format

 bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);

Question:

I tried to retrieve bitmap from the assets and then try to load the Horizontal recyclerview image list using glide as asBitmap(). I am getting the duplicate images and the mismatch images(loading wrong image in place of the required image). Below screen shot shows laptop and Mobiles have same bitmap loaded and Footware and Bus has wrong bitmap loaded It worked well after I removed the glide cache using .skipMemoryCache(true).

I want to resolve the same want to use the glide Cache to load the images.

Tried following points which was suggested in this page: Glide recyclerview loading duplicate image 1)I have added palceholder. 2) clearing the bitmap--> Glide.with(context).clear(holder.imgcat); or using holder.imgcat.setImageBitmap(null); 3) skipMemoryCache(true) worked well but require cache for loading images.

InputStream selectedInputStream = Application.get().getAssets().open(ImageSaver.selectedAssets + "/" + mValues.get(position).getImage_url());
                Drawable selectedImagesDrawable = Drawable.createFromStream(selectedInputStream, null);
                Bitmap selectedicon = ((BitmapDrawable) selectedImagesDrawable).getBitmap();
                if(selectedInputStream != null) {
                    try {
                        selectedInputStream.close();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                GlideApp.with(context)
                        .asBitmap()
                        .load(selectedicon)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .error(R.drawable.placeholder)
                        .placeholder(R.drawable.placeholder)
                        .into(holder.imgcat);

I am getting the duplicate images and the mismatch images(loading wrong image in place of the required image) while set .diskCacheStrategy(DiskCacheStrategy.RESOURCE) or .diskCacheStrategy(DiskCacheStrategy.ALL).

skipMemoryCache(true) worked well but require cache for loading images


Answer:

this problem sometimes happens in recyclerviews recyclerviews use the same ViewHolders to show their list items . so chances are that more than one request is being called on one ImageView of your viewholders at the same time.a fix for this could be to stop any other Glide requests already happenning for that ImageView.

//in your onBindViewHolder 
fun onBindViewHolder( holder:ViewHolder ,position:Int){
   //call this to clear previous requests
   Glide.with(context).clear(holder.imageView)
   //then make new request
   Glide.with(context).load(items[position].url).into(holder.imageview)
   //other codes
}

Question:

I'm working on Android (6.0) app that needs to display images on additional screen (connected via HDMI port). It's done by using Glide library and Presentation class. Glide provides "onResourceReady" event, which should fire when loading of image to imageview is finished. Sadly, I know for sure that it doesn't mean that the image has been displayed!

I need to know when there is image on this additional screen, because I need to precisely measure for how long it is shown. I also tried checking if my imageview "isDirty" and I also noticed, that even after my this method returns false (so image view isn't dirty anymore) there is still some time between this (imageview stops being dirty) and an actual drawing of image on the screen.

Does Android provide any mechanism that will fire after image has really been displayed on screen? Even if it requires some hacking, digging into NDK etc?


Answer:

You should use a GlobalLayoutListener to figure out when you're view has been drawn. Example implementation:

yourImageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            yourImageView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            //Put your measurements here.
        }
}

Question:

I'm trying to rotate my image in Glide. I've created BitmapTransformation as it's said in the documentation. Problem is that overrided method transform is not called so image is not rotated at all. I'm using Glide 3.7.0

    @Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Uri imageUri = this.imageUri;

    Glide.with(getContext())
            .load(imageUri)
            .transform(new RotateTransformation(getContext(), 90))
            .fitCenter()
            .into(imageView);
}

public class RotateTransformation extends BitmapTransformation {

    private float rotateRotationAngle = 0f;

    public RotateTransformation(Context context, float rotateRotationAngle) {
        super(context);

        this.rotateRotationAngle = rotateRotationAngle;
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Matrix matrix = new Matrix();

        matrix.postRotate(rotateRotationAngle);

        return Bitmap.createBitmap(toTransform, 0, 0, toTransform.getWidth(), toTransform.getHeight(), matrix, true);
    }

    @Override
    public String getId() {
        return "rotate" + rotateRotationAngle;
    }
}

Answer:

update

Glide.with(getContext())
            .load(imageUri)
            .transform(new RotateTransformation(getContext(), 90))
            .fitCenter()
            .into(imageView);

to

Glide.with(getContext())
            .load(imageUri)
            .fitCenter()
            .transform(new RotateTransformation(getContext(), 90))
            .into(imageView);

Question:

I am trying to fetch Bitmap of image stored on Sd card using Glide but it is not working for me.

Bitmap bitmapByGlide = Glide.with(this).load(imagePath).asBitmap().into(100, 100).get();

Answer:

You can try this way:

   Glide.with(this)
        .load(Uri.fromFile(new File(url)))
        .asBitmap()
        .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
             bitmapByGlide = resource;
            }
        });

(use Uri.formFile() is trick of this)

Question:

My app, when user click capture button, start camera capture.

I use bitmap API. but sometimes memory problem. so I want use Glide library.

current my source

//Run on Preview call from Camera
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
  YuvImage image = new YuvImage(data, previewFormat, 640, 480, null);

  Rect rect = new Rect(0, 0, 640, 480);
  ByteArrayOutputStream bao = new ByteArrayOutputStream();
  image.compressToJpeg(rect, 100, bao); //Compress data in YUY2 format into a rectangular area in jpeg format.

  byte[] jpeg = bao.toByteArray();
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inPreferredConfig = Bitmap.Config.RGB_565;

  Bitmap convertedImage = BitmapFactory.decodeByteArray(jpeg, 0, jpeg.length, options); //byte array to bitmap

  mCallback.imageTaken(Bitmap.createScaledBitmap(convertedImage, 480, 360, true));
}

imageTaken(CaptureView.class)

   //completed capture picture.
   public void imageTaken(Bitmap bitmap) {
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

      displayImage(bitmap); //preview bitmap image.
   }

displayImage(CaptureView.class);

public class CaptureView extends View implements CaptureViewer {

   private Bitmap mBitmap = null;
   private Rect src = new Rect(120, 96, 342, 272);
   private Rect dst;
   private int viewWidth, viewHeight = 0;

   @Override
   protected void onMeasure(int width, int height) {
      super.onMeasure(width, height);
      viewWidth = getLayoutParams().width;
      viewHeight = getLayoutParams().height;

      dst = new Rect(0, 0, viewWidth, viewHeight);
   }

   @Override
   public void displayImage(Bitmap image) {
      if (mBitmap != null) {
          mBitmap.recycle();
      }
      mBitmap = null;
      mBitmap = Bitmap.createBitmap(image);
      postInvalidate();
  }

  @Override
  protected void onDraw(Canvas canvas) {
     super.onDraw(canvas);
     canvas.drawBitmap(mBitmap, src, dst, null);
  }
}

this source work, but I want use Glide library. most of the examples, use url glide library.

but I want bitmap to image glide library.

How to convert a bitmap or byte array to an image using glide android?


Answer:

I think using below code you can get bitmap

Glide.with(this)
    .asBitmap()
    .load(path)
    .into(new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
            imageView.setImageBitmap(resource);
        }
    });

Question:

I am trying to run below code to get cover image, if no cover is found method returns default drawable (R.drawable.no_cover).

private Bitmap getCoverImage(final Song song) {
    Bitmap bitmap;
    final Uri uri = ContentUris.withAppendedId(Utilities.sArtworkUri, song.getAlbumId());
        try {
            bitmap = Glide.with(service)
                .load(uri)
                .asBitmap()
                .into(256, 256)
                .get();
        } catch (InterruptedException | ExecutionException e) {
            bitmap = BitmapFactory.decodeResource(service.getResources(), R.drawable.no_cover);
        }
    return bitmap;
}

However I get error (log below). Should I create new thread for this??

07-17 08:25:30.508 21095-21095/com.example.app E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.app, PID: 21098
    java.lang.IllegalArgumentException: YOu must call this method on a background thread
        at com.bumptech.glide.util.Util.assertBackgroundThread(Util.java:144)
        at com.bumptech.glide.request.RequestFutureTarget.doGet(RequestFutureTarget.java:169)
        at com.bumptech.glide.request.RequestFutureTarget.get(RequestFutureTarget.java:100)
        at com.example.app.notification.PlayerNotification$1.run(PlayerNotification.java:151)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Answer:

Because you need this Bitmap for showing a notification, that means, that you have to first fetch the bitmap and later take care of actually displaying the notification.

This is an AsyncTask implementation, which may help you:

public class TestActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new MyAsyncTask(getApplicationContext(), "some url").execute();
    }

    private static class MyAsyncTask extends AsyncTask<Void, Void, Bitmap> {

        private Context context;
        private String url;

        MyAsyncTask(Context context, String url) {
            this.context = context;
            this.url = url;
        }

        @Override
        protected Bitmap doInBackground(Void... params) {
            try {
                return Glide.with(context)
                        .load(url)
                        .asBitmap()
                        .into(256, 256)
                        .get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);

            if (null != bitmap) {
                // show notification using bitmap
            } else {
                // couldn't fetch the bitmap
            }
        }
    }
}