I have a question about loading an image from a website. The code I use is:
Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); Bitmap bit=null; try { bit = BitmapFactory.decodeStream((InputStream)new URL("http://www.mac-wallpapers.com/bulkupload/wallpapers/Apple%20Wallpapers/apple-black-logo-wallpaper.jpg").getContent()); } catch (Exception e) {} Bitmap sc = Bitmap.createScaledBitmap(bit,width,height,true); canvas.drawBitmap(sc,0,0,null);
But it always returns a null pointer exception and the program crashes out. The URL is valid, and it seems to work for everyone else. I'm using 2.3.1.
This example demonstrates how do I get a bitmap from Url in android app. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Bitmap bm=((BitmapDrawable)imageView. getDrawable()). getBitmap(); Try having the image in all drawable qualities folders (drawable-hdpi/drawable-ldpi etc.)
public static Bitmap getBitmapFromURL(String src) { try { URL url = new 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) { // Log exception return null; } }
If you are using Picasso or Glide or Universal-Image-Loader for load image from url.
You can simply get the loaded bitmap by
For Picasso (current version 2.71828
)
Java code
Picasso.get().load(imageUrl).into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { // loaded bitmap is here (bitmap) } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) {} });
Kotlin code
Picasso.get().load(url).into(object : com.squareup.picasso.Target { override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) { // loaded bitmap is here (bitmap) } override fun onPrepareLoad(placeHolderDrawable: Drawable?) {} override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {} })
For Glide
Check How does one use glide to download an image into a bitmap?
For Universal-Image-Loader
Java code
imageLoader.loadImage(imageUrl, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { // loaded bitmap is here (loadedImage) } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With