为了账号安全,请及时绑定邮箱和手机立即绑定

如何将图像从其URL传输到SD卡?

/ 猿问

如何将图像从其URL传输到SD卡?

DIEA 2019-12-27 15:43:08

如何将图像保存到从图像URL检索的SD卡中?



查看完整描述

2 回答

?
不负相思意

首先,您必须确保您的应用程序有权写入sdcard。为此,您需要在应用程序清单文件中添加使用权限写入外部存储。请参阅设置Android权限


然后,您可以将URL下载到sdcard上的文件中。一种简单的方法是:


URL url = new URL ("file://some/path/anImage.png");

InputStream input = url.openStream();

try {

    //The sdcard directory e.g. '/sdcard' can be used directly, or 

    //more safely abstracted with getExternalStorageDirectory()

    File storagePath = Environment.getExternalStorageDirectory();

    OutputStream output = new FileOutputStream (new File(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();

}

编辑: 将权限放入清单


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


查看完整回答
反对 回复 2019-12-27
?
紫衣仙女

一个很好的例子可以在Android开发者博客的最新文章中找到:


static Bitmap downloadBitmap(String url) {

    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");

    final HttpGet getRequest = new HttpGet(url);


    try {

        HttpResponse response = client.execute(getRequest);

        final int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) { 

            Log.w("ImageDownloader", "Error " + statusCode + 

               " while retrieving bitmap from " + url); 

            return null;

        }


        final HttpEntity entity = response.getEntity();

        if (entity != null) {

            InputStream inputStream = null;

            try {

                inputStream = entity.getContent(); 

                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

                return bitmap;

            } finally {

                if (inputStream != null) {

                    inputStream.close();  

                }

                entity.consumeContent();

            }

        }

    } catch (Exception e) {

        // Could provide a more explicit error message for IOException or

        // IllegalStateException

        getRequest.abort();

        Log.w("ImageDownloader", "Error while retrieving bitmap from " + url,

           e.toString());

    } finally {

        if (client != null) {

            client.close();

        }

    }

    return null;

}


查看完整回答
反对 回复 2019-12-27

添加回答

回复

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信