如何使用Glide将图像加载到手机存储中?

时间:2018-07-13 14:03:53

标签: android android-glide

我应该:将图像保存到手机存储中

我的尝试和代码:

/***************************SAVE TO STORAGE ********************************/

private String saveImage(Bitmap image) {
    String savedImagePath = null;

    String imageFileName = "JPEG_" + "FILE_NAME" + ".jpg";
    File storageDir = new File(            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            + "/YOUR_FOLDER_NAME");
    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);
        Toast.makeText(getContext(), "IMAGE SAVED", Toast.LENGTH_LONG).show();
    }
    return savedImagePath;
}

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);
    getContext().sendBroadcast(mediaScanIntent);
}

/***************************SAVE TO STORAGE ********************************/

在按钮侦听器方法中

  fabLoad.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            String URLIMAGE = imgPos;
            Glide.with(getActivity().getApplicationContext())
                    .load(URLIMAGE)
                    .asBitmap()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super
                                Bitmap> glideAnimation)  {

                            saveImage(resource);

                            try {
                                WallpaperManager.getInstance(getActivity().getApplicationContext()).setBitmap(resource);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }
                    });
        }
    });

清单

<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我使用文档编写了代码,但不幸的是它不起作用。 当我单击按钮时,图像不会加载到我的手机存储中。

0 个答案:

没有答案