En Android, ¿cuál es el método más sencillo a lo siguiente:Carga de imágenes remotas
- Cargar una imagen desde un servidor remoto.
- Muestrelo en un ImageView.
En Android, ¿cuál es el método más sencillo a lo siguiente:Carga de imágenes remotas
Aquí es un método que realmente he utilizado en una aplicación y sé que funciona:
try {
URL thumb_u = new URL("http://www.example.com/image.jpg");
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
myImageView.setImageDrawable(thumb_d);
}
catch (Exception e) {
// handle it
}
no tengo idea de lo que el segundo parámetro es Drawable.createFromStream
, pero pasando "src"
parece funcionar. Si alguien sabe, por favor arroje algo de luz, ya que los documentos no dicen nada al respecto.
La forma más fácil hasta ahora es construir un simple retriver imagen:
public Bitmap getRemoteImage(final URL aURL) {
try {
final URLConnection conn = aURL.openConnection();
conn.connect();
final BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
final Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
return bm;
} catch (IOException e) {}
return null;
}
Entonces, sólo hay que suministrar una URL para el método y lo hará devuelve una Bitmap
. Luego, solo tendrá que usar el método setImageBitmap
de ImageView
para mostrar la imagen.
habría que saber cómo hacer esto en una conexión HTTPS? – Woppi
Tenga cuidado con las dos respuestas aquí; ambas corren el riesgo de OutOfMemoryException
. Pruebe su aplicación intentando descargar una imagen grande, como un fondo de escritorio. Para ser claros, las líneas ofensivas son:
final Bitmap bm = BitmapFactory.decodeStream(bis);
y
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
respuesta de Félix lo cogerá en la sentencia catch {}, y se podía hacer algo al respecto existe.
Aquí es cómo evitar el error OutOfMemoryException
:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(is, null, options);
} catch (OutOfMemoryError ome) {
// TODO - return default image or put this in a loop,
// and continue increasing the inSampleSize until we don't
// run out of memory
}
Y aquí están mis comentarios sobre esto en mi código
/**
* Showing a full-resolution preview is a fast-track to an
* OutOfMemoryException. Therefore, we downsample the preview image. Android
* docs recommend using a power of 2 to downsample
*
* @see <a
* href="https://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966">StackOverflow
* post discussing OutOfMemoryException</a>
* @see <a
* href="http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize">Android
* docs explaining BitmapFactory.Options#inSampleSize</a>
*
*/
También puedes probar esta lib: https://github.com/codingfingers/fastimage
cuando tuvimos algunos proyectos con el mismo patrón, y de la librería se acercó;) ¿por qué no compartir con los demás ...
Eso es mucho mejor ... ¡gracias por la propina! – Cristian
¿Has probado esto? No parece estar funcionando aquí. –
No, esto no funciona. – alexanderblom