[java] Getting Image from URL (Java)

I am trying to read the following image

enter image description here

But it is showing IIOException.

Here is the code:

Image image = null;
URL url = new URL("http://bks6.books.google.ca/books?id=5VTBuvfZDyoC&printsec=frontcover&img=1& zoom=5&edge=curl&source=gbs_api");
image = ImageIO.read(url);
jXImageView1.setImage(image); 

This question is related to java image url

The answer is


You can try the this class to displays an image read from a URL within a JFrame.

public class ShowImageFromURL {

    public static void show(String urlLocation) {
        Image image = null;
        try {
            URL url = new URL(urlLocation);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");

            conn.connect();
            InputStream urlStream = conn.getInputStream();
            image = ImageIO.read(urlStream);

            JFrame frame = new JFrame();
            JLabel lblimage = new JLabel(new ImageIcon(image));
            frame.getContentPane().add(lblimage, BorderLayout.CENTER);
            frame.setSize(image.getWidth(null) + 50, image.getHeight(null) + 50);
            frame.setVisible(true);

        } catch (IOException e) {
            System.out.println("Something went wrong, sorry:" + e.toString());
            e.printStackTrace();
        }
    }
}

Ref : https://gist.github.com/aslamanver/92af3ac67406cfd116b7e4e177156926


Directly calling a URL to get an image may concern with major security issues. You need to ensure that you have sufficient rights to access that resource. However You can use ByteOutputStream to read image file. This is an example (Its just an example, you need to do necessary changes as per your requirement.)

ByteArrayOutputStream bis = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] bytebuff = new byte[4096]; 
  int n;

  while ( (n = is.read(bytebuff)) > 0 ) {
    bis.write(bytebuff, 0, n);
  }
}

Try This:

//urlPath = address of your picture on internet
URL url = new URL("urlPath");
BufferedImage c = ImageIO.read(url);
ImageIcon image = new ImageIcon(c);
jXImageView1.setImage(image);

Try:

public class ImageComponent extends JComponent {
  private final BufferedImage img;

  public ImageComponent(URL url) throws IOException {
    img = ImageIO.read(url);
    setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));

  }

  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
  }

  public static void main(String[] args) throws Exception {
    final URL kitten = new URL("https://placekitten.com/g/200/300");

    final ImageComponent image = new ImageComponent(kitten);

    JFrame frame = new JFrame("Test");
    frame.add(new JScrollPane(image));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
  }
}

This code worked fine for me.

 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.URL;

public class SaveImageFromUrl {

public static void main(String[] args) throws Exception {
    String imageUrl = "http://www.avajava.com/images/avajavalogo.jpg";
    String destinationFile = "image.jpg";

    saveImage(imageUrl, destinationFile);
}

public static void saveImage(String imageUrl, String destinationFile) throws IOException {
    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    OutputStream os = new FileOutputStream(destinationFile);

    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();
}

}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?