0
所以我一直在四處尋找關於如何將URL圖片(.png)下載到手機上的解釋itself-Android的Eclipse的從URL存儲在手機
我有一個方法下載圖像在菜單上選擇一旦他們選擇照片 - 它發送的URL路徑以及文件名我希望它被稱爲(test.png暫時)
我想要做到這一點AsynC以及保持UI免費 -
下面的代碼實際上關閉罰款,但它似乎並沒有保存任何圖像,雖然 - (我不有我的手機上的SD卡,但我想保存到測試數據文件夾,以及與相同的結果)
protected void saveImage(String imageUrl, String fileName){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
private String imageUrl;
private String fileName;
public SendPostReqAsyncTask (String imageUrl, String fileName)
{
super();
this.imageUrl=imageUrl;
this.fileName=fileName;
}
@Override
protected String doInBackground(String... params) {
String newfilename="";
try {
File externalStorageDirectory = Environment.getExternalStorageDirectory();
URL urlTmp = new URL(imageUrl);
newfilename = urlTmp.getFile();
newfilename = externalStorageDirectory + "/" + fileName;
Bitmap bitmap = BitmapFactory.decodeStream(urlTmp.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(newfilename);
if (bitmap != null) {
bitmap.compress(CompressFormat.PNG, 50, fileOutputStream);
return newfilename;
}
} catch (MalformedURLException e) {
Log.w("errorSaving", "Could not save image with url: " + imageUrl, e);
} catch (IOException e) {
Log.w("errorSaving", "Could not save image with url: " + imageUrl, e);
}
Log.d("errorSaving", "Failed to save image " + fileName);
return newfilename;
}
//handle result when done
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), "Photo saved to phone: " + result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask(imageUrl,fileName);
sendPostReqAsyncTask.execute();
}
標準問題:您是否有權寫入外部存儲?如果是,您是否有權訪問互聯網?如果是的話,請解釋你的代碼失敗的地方。 – 323go
是的,我在清單中設置了權限,不幸的是我沒有收到任何錯誤 - 代碼運行,但它實際上並沒有保存任何文件 – sykal
逐行瀏覽您的代碼。無論如何,如果你只是拋出警告(Log.w),你就不會有錯誤。第一個newFilename分配是多餘的。這是顯而易見的,就像一個不正確的url或一個缺少的fileName。 – 323go