web-dev-qa-db-ja.com

画像をそのURLからSDカードに転送するにはどうすればよいですか?

画像のURLから取得したSDカードに画像を保存するにはどうすればよいですか?

24
Jameskittu

最初に、アプリケーションにSDカードへの書き込み権限があることを確認する必要があります。これを行うには、アプリケーションのマニフェストファイルに使用権限write external storageを追加する必要があります。 Setting Android Permissions を参照してください。

次に、SDカード上のファイルへのURLをダウンロードできます。簡単な方法は次のとおりです。

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

EDIT:マニフェストに権限を入れます

 <uses-permission Android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />
47
Akusete

優れた例は 最新の投稿 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;
}
8
ognian