BitmapFactory.decodeStream restituisce null senza eccezioni
-
08-10-2019 - |
Domanda
provo a caricare un'immagine remota da un server e grazie a un sacco di esempi di codice su StackOverflow ho una soluzione che funziona in 2 su 3 immagini. Io non so davvero che cosa il problema è con la terza immagine e, talvolta, quando si lascia il codice run nel debugger il quadro è carico. Anche se carico il quadro problema prima le altre due immagini non sono a volte caricati.
Ecco il codice:
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 il debug ho scoperto che o.outWidth è -1, che indica un errore, ma non viene generata un'eccezione, quindi non posso davvero dire che cosa è andato storto. L'InputStream sempre restituito un valore valido, e so che l'immagine esiste sul server.
Un caro saluto, Daniel
Soluzione
Ho trovato la risposta qui e aggiornato il metodo di recupero 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;
}