Как сохранить изображение в хранилище, используя Glide при нажатии кнопки? - PullRequest
0 голосов
/ 01 июня 2018

Я показываю изображения с сервера с скольжением в программу просмотра обзоров.когда пользователь нажимает на изображение, оно показывает полное изображение.Я хочу, чтобы пользователь мог сохранить это изображение при нажатии кнопки.

 imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);

        Photos image = images.get(position);
        Glide.with(getActivity())
                .load(image.getUrl())
                .thumbnail(Glide.with(getActivity()).load(R.drawable.loader))
                .fitCenter()
                .crossFade()
                .into(imageViewPreview);

Ответы [ 5 ]

0 голосов
/ 01 июня 2018

если вы хотите загрузить изображение с помощью Glide и сохранить его, вы можете использовать Glide следующим образом:

    Glide.with(getApplicationContext())
                    .load("https://i.stack.imgur.com/quwoe.jpg")
                    .asBitmap()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            saveImage(resource);
                        }
                    });

    //code to save the image 

        private void saveImage(Bitmap resource) {

            String savedImagePath = null;
            String imageFileName =  "image" + ".jpg";


            final File storageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                    "/Pics");

            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);
                    resource.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
                    fOut.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // Add the image to the system gallery
                galleryAddPic(savedImagePath);
                Toast.makeText(this, "IMAGE SAVED", Toast.LENGTH_LONG).show();
            }
        }
    // Add the image to the system gallery
        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);
            sendBroadcast(mediaScanIntent);
        }
0 голосов
/ 01 июня 2018

Решение для этого

  // DownloadImage AsyncTask
    private class DownloadImageCertIV extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Bitmap doInBackground(String... URL) {

            String imageURL = URL[0];

            Bitmap bitmap = null;
            try {
                // Download Image from URL
                InputStream input = new java.net.URL(imageURL).openStream();
                // Decode Bitmap
                bitmap = BitmapFactory.decodeStream(input);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) {

                if (result != null) {


                    File destination = new File(getActivity().getCacheDir(),
                            "your path" + ".jpg");
                    try {
                        destination.createNewFile();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                        byte[] bitmapdata = bos.toByteArray();

                        FileOutputStream fos = new FileOutputStream(destination);
                        fos.write(bitmapdata);
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

        }

Чтобы использовать это при нажатии кнопки

 new DownloadImageCertIV().execute("URL HERE");
0 голосов
/ 01 июня 2018

вы можете попробовать загрузить как растровое изображение перед вызовом в (imageViewPreview)

Glide.with(getActivity())
  .load(image.getUrl())
  .asBitmap()
  ... rest of your stuffs

затем получить доступ к растровому изображению

Bitmap bitmap = ((BitmapDrawable)imageViewPreview.getDrawable()).getBitmap();
0 голосов
/ 01 июня 2018

Поскольку есть много способов добиться этого, если есть одно простейшее решение - использовать UniversalIMageLoader вот руководство по реализации UniversalImageLoader

Вот реализация, которая какскачать изображение

 ImageLoader.getInstance().loadImage(
            "IMAGE URL",
            new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    //SHOW PROGRESS
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    //HIDE PROGRESS
                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                    //HIDE PROGRESS

                    //Use this Bitmap to save in to galler

                    FileOutputStream out = null;
                    try {
                        out = new FileOutputStream("FILE_NAME");
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
                        // PNG is a lossless format, the compression factor (100) is ignored
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (out != null) {
                                out.close();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                @Override
                public void onLoadingCancelled(String s, View view) {
                    //HIDE PROGRESS
                }
            }
    );
0 голосов
/ 01 июня 2018
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto");
    boolean success = false;




public void SaveImage() {
            final Random generator = new Random();
            int n = 10000;
            n = generator.nextInt(n);
            final String fname = "image" + n + ".png";
            myDir.mkdirs();
            File image = new File(myDir, fname);

            imageview.setDrawingCacheEnabled(true);
            Bitmap bitmap = Imgv.getDrawingCache();
            // Encode the file as a PNG image.
            FileOutputStream outStream;
            try {
                outStream = new FileOutputStream(image);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                        /* 100 to keep full quality of the image */
                outStream.flush();
                outStream.close();
                success = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (success) {
                Toast.makeText(getApplicationContext(), R.string.savedimage, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), R.string.errorloadingimage, Toast.LENGTH_LONG).show();
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                final Uri contentUri = Uri.fromFile(image);
                scanIntent.setData(contentUri);
                sendBroadcast(scanIntent);
            } else {
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
            }
        }
...