Android - Save image from URL onto SD card

后端 未结 7 1283
太阳男子
太阳男子 2020-11-28 07:37

I want to save an image from a URL to the SD card (for future use) and then load that image from the SD card to use it as a drawable overlay for Google maps.

Here is

相关标签:
7条回答
  • 2020-11-28 08:11

    Try this... An easy way to the task done.

    Picasso.with(getActivity())
                    .load(url)
                    .into(new Target() {
                              @Override
                              public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                                  try {
                                      String root = Environment.getExternalStorageDirectory().toString();
                                      File myDir = new File(root + "/yourDirectory");
    
                                      if (!myDir.exists()) {
                                          myDir.mkdirs();
                                      }
    
                                      String name = new Date().toString() + ".jpg";
                                      myDir = new File(myDir, name);
                                      FileOutputStream out = new FileOutputStream(myDir);
                                      bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
    
                                      out.flush();
                                      out.close();
                                  } catch(Exception e){
                                      // some action
                                  }
                              }
    
                              @Override
                              public void onBitmapFailed(Drawable errorDrawable) {
                              }
    
                              @Override
                              public void onPrepareLoad(Drawable placeHolderDrawable) {
                              }
                          }
                    );
    
    0 讨论(0)
  • 2020-11-28 08:12

    I believe it's failing because you're writing a compressed version of the bitmap to the output stream, which should be loaded with BitmapFactory.decodeStream(). Have a quick look at the documentation on this.

    If you need a Drawable (decodeStream() returns a Bitmap), simply call Drawable d = new BitmapDrawable(bitmap).

    0 讨论(0)
  • 2020-11-28 08:14

    Try this code..It works fine

    public static Bitmap loadImageFromUrl(String url) {
                URL m;
                InputStream i = null;
                BufferedInputStream bis = null;
                ByteArrayOutputStream out =null;
                try {
                    m = new URL(url);
                    i = (InputStream) m.getContent();
                    bis = new BufferedInputStream(i,1024 * 8);
                    out = new ByteArrayOutputStream();
                    int len=0;
                    byte[] buffer = new byte[1024];
                    while((len = bis.read(buffer)) != -1){
                        out.write(buffer, 0, len);
                    }
                    out.close();
                    bis.close();
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                byte[] data = out.toByteArray();
                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                //Drawable d = Drawable.createFromStream(i, "src");
                return bitmap;
            }
    

    and save the bitmap into directory

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    _bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
    
    //you can create a new file name "test.jpg" in sdcard folder.
    File f = new File(Environment.getExternalStorageDirectory()
                            + File.separator + "test.jpg")
    f.createNewFile();
    //write the bytes in file
    FileOutputStream fo = new FileOutputStream(f);
    fo.write(bytes.toByteArray());
    
    // remember close de FileOutput
    fo.close();
    

    and do not forget to add permission to manifest

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    
    0 讨论(0)
  • 2020-11-28 08:25

    Try this code.It works...

    try
    {   
      URL url = new URL("Enter the URL to be downloaded");
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(true);                   
      urlConnection.connect();                  
      File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
      String filename="downloadedFile.png";   
      Log.i("Local filename:",""+filename);
      File file = new File(SDCardRoot,filename);
      if(file.createNewFile())
      {
        file.createNewFile();
      }                 
      FileOutputStream fileOutput = new FileOutputStream(file);
      InputStream inputStream = urlConnection.getInputStream();
      int totalSize = urlConnection.getContentLength();
      int downloadedSize = 0;   
      byte[] buffer = new byte[1024];
      int bufferLength = 0;
      while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
      {                 
        fileOutput.write(buffer, 0, bufferLength);                  
        downloadedSize += bufferLength;                 
        Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
      }             
      fileOutput.close();
      if(downloadedSize==totalSize) filepath=file.getPath();    
    } 
    catch (MalformedURLException e) 
    {
      e.printStackTrace();
    } 
    catch (IOException e)
    {
      filepath=null;
      e.printStackTrace();
    }
    Log.i("filepath:"," "+filepath) ;
    return filepath;
    
    0 讨论(0)
  • 2020-11-28 08:30

    Try this code to save the Image from the URL to SDCard.

    URL url = new URL ("file://some/path/anImage.png"); 
    InputStream input = url.openStream(); 
    try {     
        File storagePath = Environment.getExternalStorageDirectory();
        OutputStream output = new FileOutputStream (storagePath, "myImage.png");     
        try {         
            byte[] buffer = new byte[aReasonableSize];         
            int bytesRead = 0;         
            while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, bytesRead);         
            }     
        }   
        finally {         
            output.close();     
        } 
    } 
    
    finally {     
        input.close(); 
    }
    

    If you want to create a sub directory on the SD card use:

    File storagePath = new File(Environment.getExternalStorageDirectory(),"Wallpaper");
    storagePath.mkdirs();
    

    To create a the sub directory "/sdcard/Wallpaper/".

    Hope it will help you.

    Enjoy. :)

    0 讨论(0)
  • 2020-11-28 08:31

    DownloadManager does all these for you.

    public void downloadFile(String uRl) {
        File direct = new File(Environment.getExternalStorageDirectory()
                + "/AnhsirkDasarp");
    
        if (!direct.exists()) {
            direct.mkdirs();
        }
    
        DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
    
        Uri downloadUri = Uri.parse(uRl);
        DownloadManager.Request request = new DownloadManager.Request(
                downloadUri);
    
        request.setAllowedNetworkTypes(
                DownloadManager.Request.NETWORK_WIFI
                        | DownloadManager.Request.NETWORK_MOBILE)
                .setAllowedOverRoaming(false).setTitle("Demo")
                .setDescription("Something useful. No, really.")
                .setDestinationInExternalPublicDir("/AnhsirkDasarpFiles", "fileName.jpg");
    
        mgr.enqueue(request);
    
        // Open Download Manager to view File progress
        Toast.makeText(getActivity(), "Downloading...",Toast.LENGTH_LONG).show();
        startActivity(Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
    
    }
    
    0 讨论(0)
提交回复
热议问题