Search code examples
androidimagekotlindownloadpicasso

Save Image in External Storage By using Picasso from Url , how to download image and show it in imageview


Please Use This Code for save image in your external Storage by using Url

//Please Put your Image url In $url

Picasso.get().load($url).into(object : Target{
                            override fun onPrepareLoad(placeHolderDrawable: Drawable?) {

                            }

                            override fun onBitmapFailed(e: java.lang.Exception?, errorDrawable: Drawable?) {
                                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
                            }

                            override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
                                try {
                                    val root = Environment.getExternalStorageDirectory().toString()
                                    var myDir = File("$root")

                                    if (!myDir.exists()) {
                                        myDir.mkdirs()
                                    }
                                    val name = Date().toString() + ".jpg"
                                    myDir = File(myDir, name)
                                    val out = FileOutputStream(myDir)
                                    bitmap?.compress(Bitmap.CompressFormat.JPEG, 90, out)

                                    out.flush()
                                    out.close()
                                } catch (e: Exception) {
                                    // some action
                                }
                            }
                        })

and Image will be saved in sdcard.


Solution

  • 1- add to AndroidManifest.xml

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    2- Use this method to download image using Picasso from Url:

        private static void SaveImage(final Context context, final String MyUrl){
        final ProgressDialog progress = new ProgressDialog(context);
        class SaveThisImage extends AsyncTask<Void, Void, Void> {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                progress.setTitle("Processing");
                progress.setMessage("Please Wait...");
                progress.setCancelable(false);
                progress.show();
            }
            @Override
            protected Void doInBackground(Void... arg0) {
                try{
    
                    File sdCard = Environment.getExternalStorageDirectory();
                    @SuppressLint("DefaultLocale") String fileName = String.format("%d.jpg", System.currentTimeMillis());
                    File dir = new File(sdCard.getAbsolutePath() + "/savedImageName");
                    dir.mkdirs();
                    final File myImageFile = new File(dir, fileName); // Create image file
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(myImageFile);
                        Bitmap bitmap = Picasso.get().load(MyUrl).get();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        intent.setData(Uri.fromFile(myImageFile));
                        context.sendBroadcast(intent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }catch (Exception e){
                }
                return null;
            }
            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                if(progress.isShowing()){
                    progress.dismiss();
                }
                Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
            }
        }
        SaveThisImage shareimg = new SaveThisImage();
        shareimg.execute();
    }
    

    3- how to use, just call:

    SaveImage(context, "Image URL");