Primero creamos el método genérico que se encargará de recepcionar el InputStream que le mandemos. Esto lo hago para que lo podamos reutilizar con otros InputStream (por ejemplo una carga de archivo local).
public static Bitmap decodeFile(InputStream instream, int reqWidth)
throws IOException {
// Decodificar tamaño de imagen
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(instream, null, o);
final int width = o.outWidth;
final int height = o.outHeight;
// Find the correct scale value. It should be the power of 2.
int inSampleSize = 1;
if (width > reqWidth) {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
// Decodificar con inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = inSampleSize;
instream.reset();
return BitmapFactory.decodeStream(instream, null, o2);
}
En realidad con solo poner BitmapFactory.decodeStream(instream) ya se decodifica el InputStream, pero primero hago una operación para re-escalar la imagen al ancho requerido de la imagen a mostrar ya que si cargas una cantidad regular de imágenes puedes provocar un OutMemoryException que en español sería saturar la memoria. Igualmente puedes provocar un OutMemoryException si cargas muchas imagenes, pero en teoría de esta forma reducirás las probabilidades y aún más si es que cargas imágenes muy grandes.
Luego de eso creamos el método que se encargará de crear el InputStream que leerá la URL que le enviemos.
public static Bitmap loadFromUrl(String link, int reqWidth)
throws IOException, URISyntaxException {
HttpGet httpRequest = null;
httpRequest = new HttpGet(link);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
return decodeFile(instream, reqWidth);
}
Bueno, si a ti no te preocupa saturar la memoria puedes eliminar lo del re-escalado. El método quedaría así:
public static Bitmap loadFromUrl(String link) throws
IOException, URISyntaxException {
HttpGet httpRequest = null;
httpRequest = new HttpGet(link);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
return BitmapFactory.decodeStream(instream);
}
excelente aporte, gracias!
ResponderEliminar