Download Images From URL to SD Card

倾然丶 夕夏残阳落幕 提交于 2019-11-28 20:57:41

Use Picasso and load into a Target

I agree with Ichigo Kurosaki's answer above. Here is a detailed example of how you can use Picasso and a Picasso Target.


How you call the Picasso code

Picasso.with(ImageDetailActivity.this).load(
galleryObjects.get(mViewPager.getCurrentItem()).fullImagePath).into(target);


Picasso Target example

private Target target = new Target() {
    @Override
    public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                File file = new File(
                    Environment.getExternalStorageDirectory().getPath() 
                    + "/saved.jpg");
                try {
                        file.createNewFile();
                        FileOutputStream ostream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.JPEG,100,ostream);
                        ostream.close();
                }
                catch (Exception e) {
                        e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {}

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {}
};
OmerFaruk

You can use this AsyncTask, so that you don't get OnMainThread exception.

  class DownloadFile extends AsyncTask<String,Integer,Long> {
    ProgressDialog mProgressDialog = new ProgressDialog(MainActivity.this);// Change Mainactivity.this with your activity name. 
    String strFolderName;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog.setMessage("Downloading");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.show();
    }
    @Override
    protected Long doInBackground(String... aurl) {
        int count;
        try {
            URL url = new URL((String) aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            String targetFileName="Name"+".rar";//Change name and subname
            int lenghtOfFile = conexion.getContentLength();
            String PATH = Environment.getExternalStorageDirectory()+ "/"+downloadFolder+"/";
            File folder = new File(PATH);
            if(!folder.exists()){
                folder.mkdir();//If there is no folder it will be created.
            }
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(PATH+targetFileName);
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                       publishProgress ((int)(total*100/lenghtOfFile));
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {}
        return null;
    }
    protected void onProgressUpdate(Integer... progress) {
         mProgressDialog.setProgress(progress[0]);
         if(mProgressDialog.getProgress()==mProgressDialog.getMax()){
            mProgressDialog.dismiss();
            Toast.makeText(fa, "File Downloaded", Toast.LENGTH_SHORT).show();
         }
    }
    protected void onPostExecute(String result) {
    }
}

Copy this class into your activity. It mustn't be in another method.

And you can call this like new DownloadFile().execute(“yoururl”);

Also, add these permissions to your manifest.

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

Using picasso to save images in sd card, you can do something like following

private Target mTarget = new Target() {
      @Override
      public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
          // Perform simple file operation to store this bitmap to your sd card
      }

      @Override
      public void onBitmapFailed(Drawable errorDrawable) {
      }

      @Override
      public void onPrepareLoad(Drawable placeHolderDrawable) {
      }
}

...

Picasso.with(this).load("url").into(mTarget);

Here "Target" is a class provided by picasso, and it has very simple method to understand...
Hope this will meet your needs

Dhina k

Aquery is the Fastest and Easiest way to download image from url to sdcard.

try 
{
    String url=" ";   \\Paste the Url.
    aq.id(R.id.img).progress(R.id.progress).image(Url, true,   true, 0, 0, new BitmapAjaxCallback()
    {
        @Override
        public void callback(String url, ImageView iv,Bitmap bm, AjaxStatus status)   
        {
            iv.setImageBitmap(bm);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, baos);                           
            byte[] b = baos.toByteArray();
            String EnString = Base64.encodeToString(b,Base64.DEFAULT);          
            File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();         
            File dir = new File(SDCardRoot.getAbsolutePath()+ "/Aquery" + "/Image");         
            //Download the Image In Sdcard
            dir.mkdirs();    
            try 
            {        
                if (!SDCardRoot.equals("")) 
                {
                    String filename = "img"+ new Date().getTime() + ".png";
                    File file = new File(dir, filename);
                    if (file.createNewFile())                              
                    {
                        file.createNewFile();
                    }
                    if (EnString != null)          
                    {
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] decodedString = android.util.Base64.decode(EnString,
                        android.util.Base64.DEFAULT);                  
                        fos.write(decodedString);      
                        fos.flush();
                        fos.close();
                    }
                }
            }
        } catch (Exception e) {
        }
    });
} catch (Exception e) {
}

For more reference click here http://androiddhina.blogspot.in/2015/03/androiddownload-image-using-aquery.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!