Glide完成文件下载,并压缩后显示

build.gradle

    implementation "com.github.bumptech.glide:glide:4.9.0"

代码部分:

    public void fetchImage(View view) {
        final ImageView carView = findViewById(R.id.iv);
        final String temp = getExternalCacheDir().getAbsolutePath() + "/abc.jpg";
        String url = "";
        url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1572796331763&di=678053d81344db34636ce5f62ae320d1&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01f3cf5618cbd36ac7255b14dfafd4.jpg%401280w_1l_2o_100sh.jpg";
        Glide.with(this)
                .asFile()
                .load(url)
                .placeholder(android.R.drawable.ic_delete)
                .thumbnail(0.1f)//此缩略图机制无法完成对下载图片的压缩
                .into(new CustomTarget() {
                    @Override
                    public void onResourceReady(@NonNull File resource, @Nullable Transition transition) {
                      //实现压缩,并重新生成BitMap对象
                        Bitmap bitmap = BitmapFactory.decodeFile(resource.getAbsolutePath(), null);
                        try {
                            FileOutputStream out = new FileOutputStream(temp);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 4, out);
                            bitmap = BitmapFactory.decodeFile(temp);
                            out.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        carView.setImageBitmap(bitmap);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                    }
                });
    }

你可能感兴趣的:(Glide完成文件下载,并压缩后显示)