retrieve single image via its url in java

I have a problem and I hope that you can help me. I would appreciate any help from anyone. The problem is the following.

I have a camera that has an http service, and I am communicating with the camera using the http. So the problem is that I send http request and I have back an http response in which I have a binary jpeg data. But I do not know how to convert that data into picture.

So my question is how can I convert that binary data into picture with java?

This is one example

http request:

GET (url to picture) 

http response:

binary jpeg data

I thank to all of you in forward for all of your help.

URL url = new URL("http://10.10.1.154" + GETIMAGESCR());
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String inputLine;
       // while ((inputLine = in.readLine()) != null){
                // inputLine = in.readLine();
                 File file = new File("D:\\alphas\\proba.bin");
                 boolean postoi = file.createNewFile();
                 FileWriter fstream = new FileWriter("D:\\alphas\\proba.bin");
                 BufferedWriter out = new BufferedWriter(fstream);
                 while ((inputLine = in.readLine()) != null){
                 out.write(in.readLine());
                // out.close();
               //  System.out.println("File created successfully.");
            System.out.println(inputLine);
            }
            System.out.println("File created successfully.");
            out.close();
            in.close();

With this code I am getting the binary JPEG data, and I menage to save the data in a file. So the question is now how to convert this data into picture, or how to create the picture? By the way I do not need to save the file that I get, if you have a way to create the picture directly it would be the best way

retrieve single image via its url in java

Upvotes: 1

Views: 264

Answers (3)

Guillaume Polet
Guillaume Polet

Reputation: 47608

Am I missing something or are you just looking for this:

new ImageIcon(new URL("http://some.link.to/your/image.jpg"));

If you need to save the data from the URL, then just read the bytes from the corresponding InputStream and write the read bytes to a FileOutputStream:

Upvotes: 1

Jigar Joshi
Jigar Joshi

Reputation: 240898

you just need to write byte data of image in response and set the proper content type, It will serve image from servlet

Upvotes: 2

try {
    URL url = new URL("http://site.com/image.jpeg");

    java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().createImage(url);
} catch (MalformedURLException e) {
} catch (IOException e) {
}

Upvotes: 1

Related Questions