安卓 - 将图像从URL保存到SD卡

2022-09-03 17:02:38

我想将图像从URL保存到SD卡(供将来使用),然后从SD卡加载该图像以将其用作Google地图的可绘制叠加层。

以下是该函数的保存部分:

//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卡,但在到达线路时失败。我不明白为什么它会保存到那个目的地,但不能从它加载....createFromPath()


答案 1

请尝试此代码。它的工作原理...

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;

答案 2

请尝试此代码将图像从 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();

创建子目录“/sdcard/Wallpaper/”。

希望它能帮助你。

享受。:)


推荐