使用Glide保存调整大小后的图像

6

能否用Glide调整大小并保存图片到文件中呢?我正在使用以下代码:

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

我该怎么做?

谢谢

2个回答

9

是的,这是可能的。我正在使用一个SimpleTarget(Glide术语中的自定义目标)后代,我为此特定目的创建了它。它非常简单易用。这是Target代码:

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

}

以下是如何在您自己的示例中使用它的方法:

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

这段代码不会在任何视图中显示图片,而是直接保存到目标位置。

@ArMo372,你做错了什么或者漏掉了某些步骤。如果你发出相关的代码,我可以尝试帮助你。 - Loudenvier
2
@Loudenvier 很棒的回答,我也将 ImageView 目标作为参数传递,如果你想将图像设置到 ImageView 中并保存到文件中。https://gist.github.com/agustinsivoplas/7261d7316e854a66a547e17da02476c3 :) - AndroidRuntimeException
1
@ArMo372,在“用法”代码中出现了一个错误。缺少asBitmap()调用。答案现已更新! - Loudenvier
1
太棒了!我一直在使用BitmapFactory来后期处理相机图像,但是如果要进行裁剪,则需要进行大量的工作,因为在新设备上由于图像尺寸(然后裁剪为1024x1024),导致严重损失大量图像。我在项目的其他地方使用Glide,所以这很完美,简单,而且可能在内存上更好!谢谢 - WallyHale
@Loudenvier,将上述代码用作Glide: Glide.with(context) .asBitmap() .load(path) .centerCrop() .into(new FileTarget(pathToDestination, 600, 200)); - Kimmi Dhingra
显示剩余2条评论

1
您可以使用自定义位图转换来完成此操作。
Glide.with(this)
            .load(path)
            .bitmapTransform(new CropTransformation(this, 600, 200))
            .into(imageView);

下载 CropTransformation

内部

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

保存位图

之前

 return BitmapResource.obtain(bitmap, mBitmapPool);

查看所有转换这里


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接