android - 如何压缩使用 Glide 加载的可绘制图像
问题描述
我在这里有这段代码,我想压缩可绘制结果我该怎么做?
Glide.with(context)
.load(Urls.BASE_URI +items.get(holder.getAdapterPosition()).getUserPhotoUrl())
.apply(requestOptions
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true).dontAnimate().fitCenter().circleCrop().override(100,100)
)
.into(new SimpleTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
holder.userPhoto.setImageDrawable(resource);
}
});
解决方案
试试这个
然后编写此代码以获取可绘制位图,然后将位图转换为文件
public void doTheJob(){
Bitmap bitmap= BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon_resource);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
new Compressor(this).compressToFileAsFlowable(f)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(file -> getTheBitmapOfTheFile(file), throwable -> throwable.printStackTrace());
// remember close de FileOutput
fo.close();
}
public void getTheBitmapOfTheFile(File file){
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
但请不要忘记对外部存储的读写权限
推荐阅读
- deep-learning - 如何在深度学习中为图像添加数据?
- javascript - 使用 React Navigation 5,如何使导航到抽屉项重置该堆栈的状态?
- java - 在 xfce4-terminal 中运行 jar 文件而不是 bash
- powershell - 如何在搜索表单中输入命令?
- javascript - 通过数组的循环(for)迭代
- javascript - Vanilla JavaScript
在字符串中一定数量的字符后附加标签 - java - Java自定义比较器实现
- java - 无法选择图像以在 Android Studio 中打开图库
- node.js - MongoDB:按四舍五入值分组
- php - 偶数和奇数规则的问题