Pregunta

intento cargar una imagen remota desde un servidor y gracias a una gran cantidad de ejemplos de código en StackOverflow tengo una solución que funciona en 2 de 3 imágenes. No se sabe muy bien cuál es el problema con la tercera imagen y, a veces cuando dejar correr el código en el depurador de la imagen es de carga. Además, si me carga la imagen problema en primer lugar las otras dos veces, las fotografías no se cargan.

Este es el código:

public static Drawable getPictureFromURL(Context ctx, String url, final int REQUIRED_SIZE) throws NullPointerException {
    //Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    int scale = 1;
    if (o.outWidth > REQUIRED_SIZE) {
        scale = (int) Math.pow(2, (int) Math.round(Math.log(REQUIRED_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
    }
    Log.i(Prototype.TAG, "scale: "+scale); 

    //Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    Bitmap bmp;
    try {
        bmp = BitmapFactory.decodeStream((InputStream) Tools.fetch(url), null, o2);
        if(bmp!=null)
            return new BitmapDrawable(ctx.getResources(), bmp);
        else
            return null;
    } catch (Exception e) {
        Log.e(Prototype.TAG, "Exception while decoding stream", e);
        return null;
    }
}

Durante la depuración descubrí que o.outWidth es -1, que indica un error, pero no es una excepción es lanzada, así que no puedo realmente decir lo que salió mal. El InputStream siempre se devuelve un valor válido, y sé que existe la imagen en el servidor.

Los mejores deseos, Daniel

¿Fue útil?

Solución

He encontrado la respuesta aquí y actualizó el método fetch a:

private static InputStream fetch(String address) throws MalformedURLException,IOException {
    HttpGet httpRequest = new HttpGet(URI.create(address) );
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
    HttpEntity entity = response.getEntity();
    BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
    InputStream instream = bufHttpEntity.getContent();
    return instream;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top