Translate

jeudi 25 juillet 2013

Afficher une image à partir de son URL

Pour afficher une image dans un ImageView directement à partir de son URL nous écrirons une AsyncTask qui téléchargera l'image en arrière plan (ne bloque pas l'application). Une c'est fait cette AsyncTask affichera l'image à l'écran.

AsyncTask
public class ImagePreview extends AsyncTask<String, Integer, Object> {

       public ImagePreview() {
             super();
       }

       @Override
       protected final Bitmap doInBackground(final String... url) {
             Bitmap bitmap = null;
             try {
                    bitmap = BitmapFactory.decodeStream((InputStream) new URL(
                                        url[0]).getContent());
             } catch (MalformedURLException e) {
                    e.printStackTrace();
             } catch (IOException e) {
                    e.printStackTrace();
             }
             return bitmap;
       }

       @Override
       protected final void onPostExecute(final Object result) {
             super.onPostExecute(result);
             ImageView photo = (ImageView) findViewById(R.id.image_preview);
             if (result != null)
                    photo.setImageBitmap((Bitmap) result);
             else
                    Toast.makeText(getApplicationContext(), R.string.download_fail,
                                        Toast.LENGTH_LONG).show();
       }

}

Il ne reste plus qu'à appeler cette AsyncTask avec l'url de l'image
ImagePreview d = new ImagePreview();
d.execute(url de l'image à afficher);

Un exemple est disponible : https://github.com/DroiDev/DownloadDocument

Aucun commentaire:

Enregistrer un commentaire