如何在Android设备中存储图像

时间:2013-09-03 07:17:26

标签: android image storage

我有来自服务器的图像集。我需要将图像存储在设备中。如何做到这一点。任何人都可以指导我将图像存储在android设备中。这是执行此过程的最佳方式。

提前致谢:)

1 个答案:

答案 0 :(得分:0)

您可以从网址下载图片并将其存储在SD卡中。每当您想要显示图像时,只需加载该图像即可。这是这项工作的简单代码。

   private void downloadImagesToSdCard(String downloadUrl,String imageName)
  {
try{
    URL url = new URL(downloadUrl); //you can write here any link

    File myDir =  new File("/sdcard"+"/"+Constants.imageFolder);
    //Something like ("/sdcard/file.mp3")


    if(!myDir.exists()){
        myDir.mkdir();
        Log.v("", "inside mkdir");

    }

    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = imageName;
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete (); 

         /* Open a connection to that URL. */
        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();
      }

        /*
         * 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 = inputStream.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();
}

}

希望这会对你有所帮助。