2011-02-02 111 views
11

我想將URL中的圖像保存到SD卡中(以備將來使用),然後從SD卡上加載該圖像以將其用作Google地圖的可繪製覆蓋圖。Android - 將URL上的圖像保存到SD卡上

下面是函數的節省部分:開始的createFromPath()線時

//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卡succuessfully但失敗。我不明白爲什麼它會保存到目的地,但不加載它...

+0

你會得到什麼錯誤? – Cristian 2011-02-02 13:45:32

+0

您是否嘗試使用createFromPath加載現有圖像? – Ankit 2011-02-02 13:47:07

+0

它位於try-catch語句中,如果失敗,則將其設置爲null。我還沒有測試過其他圖片。我正在使用仿真器 – Jamie 2011-02-02 13:57:23

回答

1

我相信這是失敗的,因爲你正在寫輸出流的壓縮版本的位圖,應該加載與BitmapFactory.decodeStream()。在這個文件上有一個quick look

如果您需要DrawabledecodeStream()返回Bitmap),只需撥打Drawable d = new BitmapDrawable(bitmap)即可。

5

嘗試此代碼以將圖像從URL保存到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(); 
} 

如果你想在SD卡的使用創建一個子目錄:

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

要創建一個子目錄「/ SD卡/牆紙/」。

希望它能幫助你。

享受。 :)

1

試試這個code..It工作正常

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" /> 
28

試試這個code.It工程...

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

DownloadManager做所有這些你。

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

} 
3

我也面臨同樣的問題,並解決我的這個。試試這個

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

試試這個...一個簡單的方法來完成任務。

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