安卓 - 将图片从URL保存到SD卡

14

我想把从URL获取的图片保存到SD卡(以备将来使用),然后从SD卡加载该图片,作为Google地图的可绘制覆盖层。

以下是函数的保存部分:

//SAVE TO FILE

String filepath = Environment.getExternalStorageDirectory().getAbsolutePath(); 
String extraPath = "/Map-"+RowNumber+"-"+ColNumber+".png";
filepath += extraPath;

FileOutputStream fos = null;
fos = new FileOutputStream(filepath); 

bmImg.compress(CompressFormat.PNG, 75, fos);

//LOAD IMAGE FROM FILE
Drawable d = Drawable.createFromPath(filepath);
return d;

图片已成功保存到SD卡上,但在执行createFromPath()时失败。我不明白为什么它能够成功地保存到该目标位置,但不能从该位置加载...


你尝试使用createFromPath加载现有图像了吗? - Ankit
它在try-catch语句中,如果失败则将其设置为null。我还没有测试过另一张图片。我正在使用模拟器。 - Jamie
如何将Firebase存储中的图像保存到SD卡中。我无法解决这个问题。你能帮我解决一下吗?问题链接 - coderpc
6个回答

28

试一下这段代码。它有效的……

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;

老兄!这段代码真的很好用!非常感谢你提供的这个片段。 - Raphael Pineda
9
我不明白你为什么这样做:if(file.createNewFile()) { file.createNewFile(); } - Sebastian Breit
兄弟,我找了两个小时的代码,最后终于行了 :) 非常感谢,已点赞 :) - Ashu Kumar
每次我都得到空的文件路径。有人能告诉我如何设置文件路径吗? - Mustansir
如果将此代码放入异步任务中,它会更好。 - Ravi Yadav
@Giridharan嗨,我使用此URL“www.androhub.com/demo/demo.pdf”时遇到错误消息“java.net.MalformedURLException:no protocol:”。您有任何想法是为什么吗? - user7691120

6
尝试以下代码将图片从URL保存到SD卡中。
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(); 
}

如果您想在SD卡上创建一个子目录,请使用以下命令:
File storagePath = new File(Environment.getExternalStorageDirectory(),"Wallpaper");
storagePath.mkdirs();

创建子目录“/sdcard/Wallpaper/”。
希望这能对您有所帮助。
享受吧。 :)

4
我也遇到了同样的问题,并通过以下方法解决。请尝试:
private class ImageDownloadAndSave extends AsyncTask<String, Void, Bitmap>
        {
            @Override
            protected Bitmap doInBackground(String... arg0) 
            {           
                downloadImagesToSdCard("","");
                return null;
            }

               private void downloadImagesToSdCard(String downloadUrl,String imageName)
                {
                    try
                    {
                        URL url = new URL(img_URL); 
                        /* making a directory in sdcard */
                        String sdCard=Environment.getExternalStorageDirectory().toString();     
                        File myDir = new File(sdCard,"test.jpg");

                        /*  if specified not exist create new */
                        if(!myDir.exists())
                        {
                            myDir.mkdir();
                            Log.v("", "inside mkdir");
                        }

                        /* checks the file and if it already exist delete */
                        String fname = imageName;
                        File file = new File (myDir, fname);
                        if (file.exists ()) 
                            file.delete (); 

                             /* Open a connection */
                        URLConnection ucon = url.openConnection();
                        InputStream inputStream = null;
                        HttpURLConnection httpConn = (HttpURLConnection)ucon;
                        httpConn.setRequestMethod("GET");
                        httpConn.connect();

                          if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) 
                          {
                           inputStream = httpConn.getInputStream();
                          }

                            FileOutputStream fos = new FileOutputStream(file);  
                int totalSize = httpConn.getContentLength();
                        int downloadedSize = 0;   
                        byte[] buffer = new byte[1024];
                        int bufferLength = 0;
                        while ( (bufferLength = inputStream.read(buffer)) >0 ) 
                        {                 
                          fos.write(buffer, 0, bufferLength);                  
                          downloadedSize += bufferLength;                 
                          Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
                        }   

                            fos.close();
                            Log.d("test", "Image Saved in sdcard..");                      
                    }
                    catch(IOException io)
                    {                  
                         io.printStackTrace();
                    }
                    catch(Exception e)
                    {                     
                        e.printStackTrace();
                    }
                }           
        } 

将网络操作在AsyncTask中声明,它会将其作为后台任务加载。不要在主线程上加载网络操作。 在按钮单击或内容视图中调用此类:

 new ImageDownloadAndSave().execute("");

不要忘记添加网络权限,如下所示:

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

希望这能帮助到某些人 :-)

1

试试这段代码,它可以正常工作

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;
        }

并将位图保存到目录中

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();

不要忘记在清单文件中添加权限

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

1
尝试这个... 一种轻松的完成任务的方式。
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) {
                          }
                      }
                );

1

我认为它失败的原因是你正在将位图的压缩版本写入输出流中,而应该使用BitmapFactory.decodeStream()进行加载。请在文档中快速查看

如果你需要一个DrawabledecodeStream()返回一个Bitmap),只需调用Drawable d = new BitmapDrawable(bitmap)即可。


1
我已经使用“decodeStream”解码了 - 现在如何将其转换为Drawable? - Jamie
1
只需调用 Drawable d = new BitmapDrawable(bitmap),其中 bitmap 是调用 decodeStream() 的结果。我已经在上面更新了我的答案,包含这些信息。 - goncalossilva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接