Android的 - 从URL保存图片到SD卡 [英] Android - Save image from URL onto SD card

查看:349
本文介绍了Android的 - 从URL保存图片到SD卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要保存从URL到SD卡上的图像(以供将来使用),然后加载图像从SD卡把它当作一个可绘制覆盖了谷歌地图。

I want to save an image from a URL to the SD card (for future use) and then load that image from the SD card to use it as a drawable overlay for Google maps.

下面是保存功能的部分:

Here is the save section of the function:

//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但得到的 createFromPath()线的时候会失败。我不明白为什么它会确定保存到目的地,但不能从它加载....

The image is saved to the sd card succuessfully but fails when getting to the createFromPath() line. I don't understand why it would save ok to that destination but not load from it....

推荐答案

试试这个code.It工程...

Try this code.It works...

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;

这篇关于Android的 - 从URL保存图片到SD卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆