Can I import an image from any type of website?

Viewed 82

I'm trying to import images from Internet using Java (IDE IntelliJ) but I don't know how to select an image (in this case the first of the row) from google images. For example I tried to search the capital of Rome and Napoli, but the code can't find any image from images google's section.

Probably you don't understand much what I said, so below you will find the code I wrote with the relative error

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main{
  public static void main(String[] args) {
    String[] listaCapitali = {
            "Roma",
            "Napoli",

    };

    for (String capitale : listaCapitali) {
        ricercaGoogle("https://www.google.com/search?q=" + capitale + "+cartina&source=lnms&tbm=isch&sa=X&ved=2ahUKEwj-moK1y-D0AhXIzaQKHeXUBLUQ_AUoAXoECAEQAw&cshid=1639392166213289&biw=2240&bih=1082&dpr=2");

    }
  }

private static void ricercaGoogle(String urlPath) {

    try {
        URL url = new URL(urlPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        int response = connection.getResponseCode();
        System.out.println(response);

        BufferedImage image = ImageIO.read(url);

        FileOutputStream fos = new FileOutputStream(String.valueOf(image));
        fos.write(response);
        fos.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

The error says:

403
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at Main.ricercaGoogle(Main.java:33)
at Main.main(Main.java:19)

403
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at Main.ricercaGoogle(Main.java:33)
at Main.main(Main.java:19)

Could you also help me to download those images on my computer named with the capital name? Thanks a lot

1 Answers

First thing to do :Your URL is not an URL of an Image ! try to change the URL

You can inspire from that code it works fine : Get an image from a HTTPGET and Put it on a file

 new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpclient = HttpClients.createDefault();
                
                /*
                 * put your urlPath here instead of http://localhost...
                 */
                HttpGet httpget = new HttpGet("http://localhost:9090/imageFilm/1");

             
                // Execute and get the response.
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httpget);
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    try (InputStream instream = entity.getContent()) {

                    // receiving an image and write it within a file 

                        try (FileOutputStream outputStream = new FileOutputStream(
                                /*
                                 * here i create a file with the image received from the httpGet , you can do other things 
                                 */
                                new File("C:\\Users\\OUSSAMA\\Desktop\\xc.png"), false)) {
                            int read;
                            byte[] bytes = new byte[1024];
                            while ((read = instream.read(bytes)) != -1) {
                                outputStream.write(bytes, 0, read);
                            }
                        }
                    } catch (UnsupportedOperationException | IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }).start();

Apache HttpClient dependency needed : https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.13


All The code in one class :


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
public class Main{
  public static void main(String[] args) {
    String[] listaCapitali = {
            "Roma",
            "Napoli",

    };

    for (String capitale : listaCapitali) {
        //ricercaGoogle("https://www.google.com/search?q=" + capitale + "+cartina&source=lnms&tbm=isch&sa=X&ved=2ahUKEwj-moK1y-D0AhXIzaQKHeXUBLUQ_AUoAXoECAEQAw&cshid=1639392166213289&biw=2240&bih=1082&dpr=2");//Your URL is not an URL of an Image ; you must change it !
             ricercaGoogle("https://i.pinimg.com/originals/1b/75/84/1b758419a811ae05ad4da61acdb7ce22.jpg");
    }
  }

private static void ricercaGoogle(String urlPath) {
    HttpClient httpclient = HttpClients.createDefault();
    
    /*
     * put your urlPath here instead of http://localhost...
     */
    HttpGet httpget = new HttpGet(urlPath);

     // Execute and get the response.
    HttpResponse response = null;
    try {
        response = httpclient.execute(httpget);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    HttpEntity entity = response.getEntity();

    if (entity != null) {
        try (InputStream instream = entity.getContent()) {

        // receiving an image and write it within a file 
             try (FileOutputStream outputStream = new FileOutputStream(
                    /*
                     * here i create a file with the image received from the httpGet , you can do other things 
                     */
                    new File("C:\\Users\\Mourad\\Desktop\\xc.png"), false)) {
                int read;
                byte[] bytes = new byte[1024];
                while ((read = instream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
            }
        } catch (UnsupportedOperationException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
}
Related