Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save resized images with Glide

Is possible save an image resized with glide in a file? I' m using this code:

Glide
    .with(context)
    .load(path)
    .override(600, 200) 
    .centerCrop() 
    .into(imageViewResizeCenterCrop);

How i can do?

Thanks

like image 585
Luca Romagnoli Avatar asked Mar 14 '16 09:03

Luca Romagnoli


2 Answers

Yes, it's possible. I'm using a SimpleTarget (a custom target in Glide parlance) descendant I created for this specific purpose. It's very simple to use. Here is the Target code:

import android.graphics.Bitmap;

import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import java.io.FileOutputStream;
import java.io.IOException;

public class FileTarget extends SimpleTarget<Bitmap> {
    public FileTarget(String fileName, int width, int height) {
        this(fileName, width, height, Bitmap.CompressFormat.JPEG, 70);
    }
    public FileTarget(String fileName, int width, int height, Bitmap.CompressFormat format, int quality) {
        super(width, height);
        this.fileName = fileName;
        this.format = format;
        this.quality = quality;
    }
    String fileName;
    Bitmap.CompressFormat format;
    int quality;
    public void onResourceReady(Bitmap bitmap, GlideAnimation anim) {
            try {
                FileOutputStream out = new FileOutputStream(fileName);
                bitmap.compress(format, quality, out);
                out.flush();
                out.close();
                onFileSaved();
            } catch (IOException e) {
                e.printStackTrace();
                onSaveException(e);
            }
    }
    public void onFileSaved() {
        // do nothing, should be overriden (optional)
    }
    public void onSaveException(Exception e) {
        // do nothing, should be overriden (optional)
    }

}

And here is how you would use it within your own example:

Glide
    .with(context)
    .load(path)
    .asBitmap()
    .centerCrop()
    .into(new FileTarget(pathToDestination, 600, 200));

This code does not show the image on any view, it saves it directly to the destination.

like image 90
Loudenvier Avatar answered Sep 28 '22 01:09

Loudenvier


You can do this using custom bitmap transform

Glide.with(this)
            .load(path)
            .bitmapTransform(new CropTransformation(this, 600, 200))
            .into(imageView);

Download CropTransformation

Inside

 public Resource<Bitmap> transform(Resource<Bitmap> resource, int outWidth, int outHeight) {`

Save bitmap before

 return BitmapResource.obtain(bitmap, mBitmapPool);

See all transformations here

like image 29
AndreyICE Avatar answered Sep 28 '22 02:09

AndreyICE