¿Cómo puedo transferir una imagen desde su URL a la tarjeta SD?


¿Cómo puedo guardar una imagen en la tarjeta SD que recupero de la URL de la imagen?

Author: Jeff Axelrod, 2010-07-21

2 answers

Primero debe asegurarse de que su aplicación tiene permiso para escribir en la tarjeta SD. Para hacer esto, debe agregar el permiso uses write external storage en su archivo de manifiesto de aplicaciones. Ver Configuración de permisos de Android

Entonces usted puede usted puede descargar la URL a un archivo en la tarjeta SD. Una manera simple es:

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

EDITAR: Poner permiso en manifiesto

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 46
Author: Akusete,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-27 13:55:15

Un excelente ejemplo se puede encontrar en el último post en el blog del desarrollador 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
Author: ognian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-09 20:25:21