画像の URL から取得した SD カードに画像を保存するにはどうすればよいですか?
38150 次
2 に答える
47
まず、アプリケーションに SD カードへの書き込み権限があることを確認する必要があります。これを行うには、アプリケーション マニフェスト ファイルにuses パーミッションwrite external storageを追加する必要があります。Android 権限の設定を参照してください
次に、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();
}
編集: マニフェストに許可を入れる
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
于 2010-07-21T07:04:06.000 に答える
8
優れた例は、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;
}
于 2010-07-21T10:05:35.737 に答える