2016-08-17 4 views
1

주어진 URL에서 이미지를 다운로드하고 싶습니다. 다운로드 한 이미지는 SD 카드에 저장해야합니다. 아래 코드를 사용했습니다.URL에서 이미지 다운로드 및 저장

 URL newurl = null; 
        try { 
         newurl = new URL(strHitRes); 
        } catch (MalformedURLException e) { 
         e.printStackTrace(); 
        } 
        try { 
         HttpURLConnection connection = (HttpURLConnection) newurl.openConnection(); 
         connection.setDoInput(true); 
         connection.connect(); 
         InputStream input = connection.getInputStream(); 
         Bitmap myBitmap = BitmapFactory.decodeStream(input); 
         String root = Environment.getExternalStorageDirectory().toString(); 
         File myDir = new File(root + "/saved_images"); 
         myDir.mkdirs(); 
         Random generator = new Random(); 
         int n = 10000; 
         n = generator.nextInt(n); 
         String fname = "Image-"+ n +".jpg"; 
         File file = new File (myDir, fname); 
         if (file.exists()) file.delete(); 
         try { 
          FileOutputStream out = new FileOutputStream(file); 
          myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); 
          Toast.makeText(getApplicationContext(),"download successful",Toast.LENGTH_LONG).show(); 
          out.flush(); 
          out.close(); 

         } catch (Exception e) { 
          e.printStackTrace(); 
         } 
        } catch (IOException e) { 
         e.printStackTrace(); 
        } 

이미지가 다운로드되지 않습니다. 심지어 디버그 모드에서 테스트 한 결과 비트 맵이 null 인 것으로 나타났습니다. 이 문제를 해결하는 방법.

+0

에서의 허가 아래 사용하는 것을 잊지 마세요? – Jas

+0

내 장치에서 정상적으로 작동합니다. 먼저 인터넷과 WRITE_EXTERNAL_STORAGE를 추가했는지 확인하십시오. 둘째, 유효한 이미지에 대한 링크가 있는지 확인하십시오. – anhtuannd

+0

제가 필요한 모든 권한을 추가 –

답변

0

// SD 카드

private void SaveImage(Bitmap finalBitmap) { 

    String root = Environment.getExternalStorageDirectory().toString(); 
    File myDir = new File(root + "/saved_images");  
    myDir.mkdirs(); 
    Random generator = new Random(); 

    String fname = "Image.jpg"; 
    File file = new File (myDir, fname); 
    if (file.exists()) file.delete(); 
    try { 
     FileOutputStream out = new FileOutputStream(file); 
     finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); 
     out.flush(); 
     out.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
0으로 비트 맵을 저장하려면

public Bitmap getbmpfromURL(String surl){ 
     try { 
      URL url = new URL(surl); 
      HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); 
      urlcon.setDoInput(true); 
      urlcon.connect(); 
      InputStream in = urlcon.getInputStream(); 
      Bitmap mIcon = BitmapFactory.decodeStream(in); 
      return mIcon; 
     } catch (Exception e) { 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
      return null; 
     } 
    } 

URL에서 비트 맵을 다운로드하려면

그리고 당신은 매니페스트 파일에 필요한 권한을 추가나요 당신 manifest.xml

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

죄송하지만 이것은 장치 저장소로 파일을 다운로드하는 방법이 아닙니다. 정답으로 표시되는 이유는 무엇입니까? 다른 하나 가져가. – greenapps

+0

# greenapps 다른 대안이 있다면 게시 할 수 있습니다. 나를 위해 일하고. – AshisParajuli

+0

'다른 하나 가져라. '나는 말했다. 나는 이미 당신에게 대안을 말했어. 더 좋은 것. 너는 그것을 읽을 수 있었다. Bitmap이나 BitmapFactory를 사용하지 않기 때문에 다른 대답이 가장 좋습니다. @Prakash U의 대답. – greenapps

1

는 대한 Vineet에 감사의 말씀을 자신의 answer

try { 
    URL url = new URL("url from apk file is to be downloaded"); 
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
    urlConnection.setRequestMethod("GET"); 
    urlConnection.setDoOutput(true); 
    urlConnection.connect(); 

    File sdcard = Environment.getExternalStorageDirectory(); 
    File file = new File(sdcard, "filename.ext"); 

    FileOutputStream fileOutput = new FileOutputStream(file); 
    InputStream inputStream = urlConnection.getInputStream(); 

    byte[] buffer = new byte[1024]; 
    int bufferLength = 0; 

    while ((bufferLength = inputStream.read(buffer)) > 0) { 
     fileOutput.write(buffer, 0, bufferLength); 
    } 
    fileOutput.close(); 

} catch (MalformedURLException e) { 
     e.printStackTrace(); 
} catch (IOException e) { 
     e.printStackTrace(); 
} 
} 
+0

예. 이렇게하는 방법입니다. Bitmap과 BitmapFactory를 사용하여 이미지를 다운로드하지 마십시오. 이미지의 해상도가 높아집니다. 비트 맵을 만들 수 없었고 BitmapFactory가 null을 반환했습니다. – greenapps

+0

'urlConnection.setDoOutput (true);'. 완료 출력이 없습니다. – greenapps

+0

답장을 보내 주셔서 감사합니다. 정상적으로 작동합니다. Ashis Parajuli가 게시 한 코드가 분리되기를 원합니다. –

관련 문제