【发布时间】:2016-06-16 00:32:28
【问题描述】:
我正在使用 Glide 加载图像、调整大小并通过 SimpleTarget<Bitmap> 将其保存到文件中。这些图像将上传到 Amazon S3,但这不是重点。我在上传之前调整图像大小,以尽可能多地节省用户的带宽。对于我的应用程序需要 1024 像素宽的图像已经绰绰有余,所以我使用以下代码来完成:
final String to = getMyImageUrl();
final Context appCtx = context.getApplicationContext();
Glide.with(appCtx)
.load(sourceImageUri)
.asBitmap()
.into(new SimpleTarget<Bitmap>(1024, 768) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
try {
FileOutputStream out = new FileOutputStream(to);
resource.compress(Bitmap.CompressFormat.JPEG, 70, out);
out.flush();
out.close();
MediaScannerConnection.scanFile(appCtx, new String[]{to}, null, null);
} catch (IOException e) {
e.printStackTrace();
}
}
});
它几乎可以完美运行,但生成的图像大小不是 1024 像素宽。使用尺寸为 4160 x 2340 像素的源图像对其进行测试,结果保存图像的尺寸为 2080 x 1170 像素。
我尝试使用传递给new SimpleTarget<Bitmap>(350, 350) 的width 和height 参数,使用这些参数生成的图像尺寸为1040 x 585 像素。
我真的不知道该怎么做才能让 Glide 尊重传递的维度。事实上,我想按比例调整图像的大小,以便将较大的尺寸(宽度或高度)限制为 1024 像素,而较小的尺寸会相应调整(我相信我必须找到一种方法来获取原始图像尺寸,然后将宽度和高度传递给SimpleTarget,但要做到这一点,我需要 Glide 尊重传递的宽度和高度!)。
有人知道发生了什么吗?我正在使用 Glide 3.7.0。
由于这个问题本身可能对尝试使用 Glide 调整大小和保存图像的人有用,我相信提供我的实际“解决方案”符合每个人的利益,该解决方案依赖于自动保存调整大小的图像的新 SimpleTargetimplementation :
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(appCtx)
.load(sourceImageUri)
.asBitmap()
.into(new FileTarget(to, 1024, 768) {
@Override
public void onFileSaved() {
// do anything, or omit this override if you want
}
});
【问题讨论】:
-
您在上面的实际解决方案中没有缺少
.fitCenter()吗? -
@Wess 如果您阅读下面的“解决方案”(如上面的问题本身),您会发现这正是缺少的内容......您甚至在阅读答案之前就已经抓住了它!好的! :-)
标签: java android android-glide