2010-12-18 6 views
1

인터넷에서 한 번에 하나의 이미지를 다운로드 한 다음 SD 카드에 저장해야합니다. 어떻게해야합니까? 시도를했지만 다운로드 한 이미지를 보려고하면 "미리보기를 사용할 수 없습니다"라는 메시지가 표시됩니다. 내가 SSL 연결에서 이미지를 다운로드해야 :이미지 (SSL)를 다운로드하여 Android의 SD 카드에 저장 하시겠습니까?

public class ImgDownloader { 

private static final int IO_BUFFER_SIZE = 4 * 1024; 

public static final byte[] downloadImage(String imgURL) { 
    byte[] data = null; 
    try { 
    Log.v("Down", "1"); 
    InputStream in = null; 
    BufferedOutputStream out = null; 
    in = new BufferedInputStream(new URL(imgURL).openStream(), 8 * 1024); 
    Log.v("Down", "2"); 
    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 
    out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); 
    copy(in, out); 
    out.flush(); 
    Log.v("Down", "3"); 
    data = dataStream.toByteArray(); 
    // bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); 
    Log.v("Down", "4"); 
    } catch (Exception ex) { 
    ex.printStackTrace(); 
    // System.out.println("Exception in Image Downloader .." 
    // +ex.getMessage()); 
    } 
    return data; 
} 

private static void copy(InputStream in, OutputStream out) 
    throws IOException { 
    byte[] b = new byte[IO_BUFFER_SIZE]; 
    int read; 
    while ((read = in.read(b)) != -1) { 
    out.write(b, 0, read); 
    } 
} 

} 

참고 : 아래에있는 내 코드를 참조하십시오.

아이디어가 있으십니까? 미리 감사드립니다.

답변

1

당신은 귀하의 요구 사항에 따라 적절한 변경을

try{ 
     URL url = new URL(downloadUrl); //you can write here any link 
     File file = new File(absolutePath); //Something like ("/sdcard/file.mp3") 

      //Create parent directory if it doesn't exists 
      if(!new File(file.getParent()).exists()) 
      { 
       System.out.println("Path is created " + new File(file.getParent()).mkdirs()); 
      } 
      file = new File(absolutePath); //Something like ("/sdcard/file.mp3") 
      file.createNewFile(); 
      /* Open a connection to that URL. */ 
      URLConnection ucon = url.openConnection(); 
      /* 
      * Define InputStreams to read from the URLConnection. 
      */ 
      InputStream is = ucon.getInputStream(); 
      /* 
      * Read bytes to the Buffer until there is nothing more to read(-1). 
      */ 
      FileOutputStream fos = new FileOutputStream(file); 
      int size = 1024*1024; 
      byte[] buf = new byte[size]; 
      int byteRead; 
      while (((byteRead = is.read(buf)) != -1)) { 
       fos.write(buf, 0, byteRead); 
       bytesDownloaded += byteRead; 
      } 
      /* Convert the Bytes read to a String. */ 

      fos.close(); 

    }catch(IOException io) 
    { 
     networkException = true; 
     continueRestore = false; 
    } 
    catch(Exception e) 
    { 
     continueRestore = false; 
     e.printStackTrace(); 
    } 

뭔가를 시도 할 수 있습니다. 인터넷에서 파일을 다운로드하고 SDCard에 저장하는 데 동일한 코드를 사용합니다.

희망이 있습니다!

관련 문제