0

I'm trying to get a png Bitmap from URL but the Bitmap is always NULL in with this code:

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;
    Activity activity;

    public DownloadImageTask(ImageView bmImage, Activity activity) {
        this.bmImage = bmImage;
        this.activity = activity;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Log.i("LEGGERE", urldisplay);
        Bitmap mIcon11 = null;
        try {
            URL url = new URL(urldisplay);
            mIcon11 = BitmapFactory.decodeStream(url.openConnection().getInputStream());

            if (null != mIcon11)
                Log.i("BITMAP", "ISONOTNULL");
            else
                Log.i("BITMAP", "ISNULL");
        } catch (Exception e) {
            Log.e("Error", "PORCA VACCA");

        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

And I create a DownloadImageTask in onCreate():

new DownloadImageTask((ImageView) findViewById(R.id.provaaa),this)
            .execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");

Do I make some mistakes?

Quarillion
  • 65
  • 2
  • 9
  • Consider using Picasso or Glide – VasFou Jul 12 '16 at 10:01
  • Check out this answer: http://stackoverflow.com/questions/8992964/android-load-from-url-to-bitmap – adalpari Jul 12 '16 at 10:01
  • do you have internet permission in the manifest – Linh Jul 12 '16 at 10:01
  • What are you downloading? A .jpg file? What is it's size? Try to save the downloaded file first. If the .jpg is too big a bitmap cannot be made by lack of memory. – greenapps Jul 12 '16 at 10:02
  • @PhanVănLinh Yes, I have Internet Permission – Quarillion Jul 12 '16 at 10:04
  • @greenapps I am trying to download a png file, at this URL: http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png – Quarillion Jul 12 '16 at 10:05
  • Please put the url in your code. And post a complete AsyncTask class. Show how you call it. – greenapps Jul 12 '16 at 10:07
  • @greenapps I edited the question – Quarillion Jul 12 '16 at 10:17
  • Thanks. But before trying your code you shoud react on the comment of adalPaRi as i think the solution lays there. – greenapps Jul 12 '16 at 10:25
  • @adalPaRi I tried the code in the link but it does the exactly same thing – Quarillion Jul 12 '16 at 10:27
  • Unclear. What did you try exactly? You can tell that in a few words. – greenapps Jul 12 '16 at 10:28
  • I try to add "https" and it works, but I have also some png that aren't in a https link (only http). How can I do? – Quarillion Jul 12 '16 at 10:28
  • Nowhere in that link was spoken about https. So what did you try that did not work? – greenapps Jul 12 '16 at 10:30
  • @greenapps I wrote the code linked by adalPari and it doesn't work, the bitamp is always null. But, if I write the link as "https://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png" instead of "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png" it works also with the code that i wrote in the question – Quarillion Jul 12 '16 at 10:35
  • @greenapps https: // java.sogeti.nl /JavaBlog/wp-content/uploads/2009/04/android_icon_256.png Instead of http ://java.sogeti.nl /JavaBlog/wp-content/uploads/2009/04/android_icon_256.png – Quarillion Jul 12 '16 at 10:37
  • please try this : private Bitmap LoadImageFromWebOperations(String url){ try{ String encodedurl = url.replace(" ", "%20"); InputStream is = (InputStream) new URL(encodedurl).getContent(); Bitmap d = BitmapFactory.decodeStream(is); return d; }catch (Exception e) { e.printStackTrace(); // System.out.println("Exc="+e); return null; } } – comeback4you Jul 12 '16 at 10:37
  • Do i have to follow all those links? I will not. What I wanted to know is if you used HttpURLConnection connection = (HttpURLConnection) url.openConnection(); as was answered there. – greenapps Jul 12 '16 at 10:37
  • @greenapps Yes, I tried HttpURLConnection connection = (HttpURLConnection) url.openConnection(); and it doesn't work, only if the URL that i pass is "https" and not "http" – Quarillion Jul 12 '16 at 10:41
  • If you try the http url in a browser you see that it redirects to a https. Thats your problem. BitmapFactory will not do this redirection. – greenapps Jul 12 '16 at 10:49

5 Answers5

1

This is a simple one line way to do it:

 URL url = new URL("http://....");
    Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Nitesh Pareek
  • 362
  • 2
  • 10
1

I suggest to use a Thead (async) to avoid exception errors :

        Thread thread = new Thread(new Runnable(){
            @Override
            public void run() {
                Bitmap thumb;
                // Ur URL
                String link = value.toString();
                try {
                    URL url = new URL(link);
                    thumb = BitmapFactory.decodeStream(url.openConnection().getInputStream());
                   // UI component
                    imageView.setImageBitmap(thumb);

                } catch (Exception e) {
                    Log.e("error message", Objects.requireNonNull(e.getMessage()));
                }
            }
        });
        thread.start();
Renaud
  • 11
  • 2
0

If you try the http url in a browser you see that it redirects to a https. Thats your problem. BitmapFactory.decodeStream will not do this redirection so it returns null.

greenapps
  • 11,154
  • 2
  • 16
  • 19
0

You can try code below...

 public static Bitmap loadBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;
        int IO_BUFFER_SIZE = 4 * 1024;
        try {
            URI uri = new URI(url);
            url = uri.toASCIIString();
            in = new BufferedInputStream(new URL(url).openStream(),
                    IO_BUFFER_SIZE);
            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            int bytesRead;
            byte[] buffer = new byte[IO_BUFFER_SIZE];
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush();
            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
                    options);
        } catch (IOException e) {
            return null;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
Iris Louis
  • 297
  • 6
  • 19
0

To get a bitmap from URL, try this:

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;
        }
    }

Or:

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}
xxx
  • 3,315
  • 5
  • 21
  • 40