0

因此,我一直在寻找有关如何将 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();     
}
4

1 回答 1

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();
}

还要确保在清单文件中设置互联网权限,

<uses-permission android:name="android.permission.INTERNET" />
于 2012-12-02T07:05:16.853 回答