代码之家  ›  专栏  ›  技术社区  ›  Paramjeet Singh

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

  •  -1
  • Paramjeet Singh  · 技术社区  · 6 年前

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

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

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

    1 回复  |  直到 6 年前
        1
  •  4
  •   Deep    6 年前
        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);
    
                }
            });