Android Eclipse-将图像从URL下载到手机上的存储

时间:2012-12-02 05:44:39

标签: android eclipse image download android-asynctask

所以我一直在寻找有关如何将URL图像(.png)下载到手机本身的解释 -

一旦他们选择了照片,我就会在菜单上选择一个方法 - 它会通过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();     
}

1 个答案:

答案 0 :(得分:0)

//To download image from a url
Drawable image;
try {
    InputStream is          = (InputStream) this.fetch(your_image_url);
    image                   = Drawable.createFromStream(is,"src");
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

//Convert drawable to Bitmap
Bitmap bitmap = ((BitmapDrawable)image).getBitmap();

//Save Bitmap to a file
try {image
       FileOutputStream out = new FileOutputStream(filename);
       bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
       e.printStackTrace();
}

还要确保在清单文件中设置了Internet权限,

<uses-permission android:name="android.permission.INTERNET" />