完成将映像从URL加载到视图后如何将映像保存到磁盘

问题描述 投票:0回答:1

我正在构建一个需要从网址中获取图像的Android应用程序,在完成将其显示到图像视图中后,我想将其存储在手机的硬盘中,以便以后可以使用而无需创建新的请求或取决于缓存。我使用滑翔4.9.0

在线的一些解决方案包括使用一些弃用的条款,例如SimpleTarget和Target,它们不适用于这个项目。

这就是我到目前为止所拥有的。

    File file = new File(holder.context.getExternalFilesDir(null), fileName);
        if (file.exists()) {
            GlideApp.with(holder.context).load(file).into(holder.ivProductImage);
        } else {
            GlideApp.with(holder.context).load(urlImage).into(holder.ivProductImage);
            // save the image to the hard drive
        }
java android-glide
1个回答
0
投票
//Step 1
Glide.with(mContext)
.load(images.get(position).getThumbnail())
.asBitmap()
.into(new Target<Bitmap>(100,100) {
    @Override
    public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
        saveImage(resource,position);
    }
});

//Step 2
private String saveImage(Bitmap image, int position) {
    String savedImagePath = null;

    String imageFileName = "JPEG_" + images.get(position).getName() + ".jpg";
    File storageDir = new File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    + "/Comicoid");
    boolean success = true;
    if (!storageDir.exists()) {
        success = storageDir.mkdirs();
    }
    if (success) {
        File imageFile = new File(storageDir, imageFileName);
        savedImagePath = imageFile.getAbsolutePath();
        try {
            OutputStream fOut = new FileOutputStream(imageFile);
            image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Add the image to the system gallery
        galleryAddPic(savedImagePath);
    }
    return savedImagePath;
}

//Step 3
private void galleryAddPic(String imagePath) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(imagePath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    mContext.sendBroadcast(mediaScanIntent);
}
© www.soinside.com 2019 - 2024. All rights reserved.