El mejor método para descargar la imagen de url en Android

Estoy usando el siguiente método para descargar una sola imagen de url

public static Bitmap getBitmap(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Bitmap d = BitmapFactory.decodeStream(is); is.close(); return d; } catch (Exception e) { return null; } } 

A veces recibo una excepción de memoria externa.

Soy incapaz de captar una excepción de excepción. Se cerrará la aplicación. ¿Cómo prevenir esto?

¿Existe un método mejor para descargar imágenes que también es más rápido?

Trate de usar esto:

 public Bitmap getBitmapFromURL(String src) { try { java.net.URL url = new java.net.URL(src); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setDoInput(true); connection.connect(); InputStream input = connection.getInputStream(); Bitmap myBitmap = BitmapFactory.decodeStream(input); return myBitmap; } catch (IOException e) { e.printStackTrace(); return null; } } 

Y para el problema de OutOfMemory:

  public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // CREATE A MATRIX FOR THE MANIPULATION Matrix matrix = new Matrix(); // RESIZE THE BIT MAP matrix.postScale(scaleWidth, scaleHeight); // "RECREATE" THE NEW BITMAP Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false); return resizedBitmap; } 

Yo uso esta biblioteca, es realmente genial cuando tienes que lidiar con muchas imágenes. Se descarga de forma asincrónica, los almacena en caché, etc.

En cuanto a las excepciones de OOM, usar esto y esta clase los redujo drásticamente para mí.

  public void DownloadImageFromPath(String path){ InputStream in =null; Bitmap bmp=null; ImageView iv = (ImageView)findViewById(R.id.img1); int responseCode = -1; try{ URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setDoInput(true); con.connect(); responseCode = con.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK) { //download in = con.getInputStream(); bmp = BitmapFactory.decodeStream(in); in.close(); iv.setImageBitmap(bmp); } } catch(Exception ex){ Log.e("Exception",ex.toString()); } } 

Usted puede utilizar debajo de la función para descargar la imagen de url.

 private Bitmap getImage(String imageUrl, int desiredWidth, int desiredHeight) { private Bitmap image = null; int inSampleSize = 0; BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inSampleSize = inSampleSize; try { URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); InputStream stream = connection.getInputStream(); image = BitmapFactory.decodeStream(stream, null, options); int imageWidth = options.outWidth; int imageHeight = options.outHeight; if(imageWidth > desiredWidth || imageHeight > desiredHeight) { System.out.println("imageWidth:"+imageWidth+", imageHeight:"+imageHeight); inSampleSize = inSampleSize + 2; getImage(imageUrl); } else { options.inJustDecodeBounds = false; connection = (HttpURLConnection)url.openConnection(); stream = connection.getInputStream(); image = BitmapFactory.decodeStream(stream, null, options); return image; } } catch(Exception e) { Log.e("getImage", e.toString()); } return image; } 

Puede descargar imagen por Asyn task utilizar esta clase:

 public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> { private final WeakReference<ImageView> imageViewReference; private final MemoryCache memoryCache; private final BrandItem brandCatogiriesItem; private Context context; private String url; public ImageDownloaderTask(ImageView imageView, String url, Context context) { imageViewReference = new WeakReference<ImageView>(imageView); memoryCache = new MemoryCache(); brandCatogiriesItem = new BrandItem(); this.url = url; this.context = context; } @Override protected Bitmap doInBackground(String... params) { return downloadBitmap(params[0]); } @Override protected void onPostExecute(Bitmap bitmap) { if (isCancelled()) { bitmap = null; } if (imageViewReference != null) { ImageView imageView = imageViewReference.get(); if (imageView != null) { if (bitmap != null) { memoryCache.put("1", bitmap); brandCatogiriesItem.setUrl(url); brandCatogiriesItem.setThumb(bitmap); // BrandCatogiriesItem.saveLocalBrandOrCatogiries(context, brandCatogiriesItem); imageView.setImageBitmap(bitmap); } else { Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.placeholder); imageView.setImageDrawable(placeholder); } } } } private Bitmap downloadBitmap(String url) { HttpURLConnection urlConnection = null; try { URL uri = new URL(url); urlConnection = (HttpURLConnection) uri.openConnection(); int statusCode = urlConnection.getResponseCode(); if (statusCode != HttpStatus.SC_OK) { return null; } InputStream inputStream = urlConnection.getInputStream(); if (inputStream != null) { Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } } catch (Exception e) { Log.d("URLCONNECTIONERROR", e.toString()); if (urlConnection != null) { urlConnection.disconnect(); } Log.w("ImageDownloader", "Error downloading image from " + url); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } return null; } 

}

Y llaman esto como:

  new ImageDownloaderTask(thumbImage, item.thumbnail, context).execute(item.thumbnail); 

La excepción OOM podría evitarse siguiendo la guía oficial para cargar mapa de bits grande .

No ejecute el código en el subproceso de interfaz de usuario. Utilice AsyncTask en su lugar y debería estar bien.

Agregue esta dependencia para Android Networking en su proyecto

Compilar 'com.amitshekhar.android:android-networking:1.0.0'

  String url = "http://ichef.bbci.co.uk/onesport/cps/480/cpsprodpb/11136/production/_95324996_defoe_rex.jpg"; File file; String dirPath, fileName; Button downldImg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Initialization Of DownLoad Button downldImg = (Button) findViewById(R.id.DownloadButton); // Initialization Of DownLoad Button AndroidNetworking.initialize(getApplicationContext()); //Folder Creating Into Phone Storage dirPath = Environment.getExternalStorageDirectory() + "/Image"; fileName = "image.jpeg"; //file Creating With Folder & Fle Name file = new File(dirPath, fileName); //Click Listener For DownLoad Button downldImg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AndroidNetworking.download(url, dirPath, fileName) .build() .startDownload(new DownloadListener() { @Override public void onDownloadComplete() { Toast.makeText(MainActivity.this, "DownLoad Complete", Toast.LENGTH_SHORT).show(); } @Override public void onError(ANError anError) { } }); } }); } } 

Después de ejecutar este código Compruebe la memoria del teléfono que puede ver allí Una carpeta – Comprobación de la imagen dentro de esta carpeta, ves allí un archivo de imagen con el nombre de "image.jpeg"

Gracias !!!

FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.