如何像whatsapp一样将图像缓存到特定文件夹

时间:2018-04-19 04:51:06

标签: android firebase firebase-realtime-database android-glide

我正在使用firebase构建聊天应用程序。我正在使用Glide来显示图像

Glide.with(getApplicationContext())
                        .load(imageUrl)
                        .crossFade()
                        .fitCenter()
                        .placeholder(R.drawable.loading)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(imageView);

我想将图像保存到内部存储中的特定文件夹,就像whatsapp一样,并在保存后从中加载图像。图像上传到Firebase存储,其URL保存在Firebase数据库中,我将它们加载到使用Glide

的url的imageView

1 个答案:

答案 0 :(得分:4)

    private static final String IMAGE_DIRECTORY = "/yourfoldername/images";

    //this method return your folder image path
    public String saveImage(Bitmap myBitmap) {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            File wallpaperDirectory = new File(
                    Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
            // have the object build the directory structure, if needed.
            if (!wallpaperDirectory.exists()) {
                wallpaperDirectory.mkdirs();
            }
            try {
                File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
                f.createNewFile();
                FileOutputStream fo = new FileOutputStream(f);
                fo.write(bytes.toByteArray());
                MediaScannerConnection.scanFile(this,
                        new String[]{f.getPath()},
                        new String[]{"image/jpeg"}, null);
                fo.close();
                Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());

                return f.getAbsolutePath();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return "";
        }


    // glide load image
    Glide.with(this)
        .load(imageUrl)
        .asBitmap()
        .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {

                String imagepath = saveImage(resource);
// Parse the gallery image url to uri
                Uri savedImageURI = Uri.parse(imagepath);



// Display the saved image to ImageView
            iv_saved.setImageURI(savedImageURI);

            }
        });