Copying Image from URL to HTTP URL



Someone is providing a S3 Presigned URL so that I can upload my images to that link. All my images are on the website. Is there a way in JAVA to copy the image URL to the new URL provided ?

I am trying to do this. Seems like an overkill

try {

        // Get Image from URL
        URL urlGet = new URL("http://something.com/something.png");
        BufferedImage image = ImageIO.read(urlGet);

        //for png
        ImageIO.write(image, "png",new File("/something.png"));

        // for jpg
        //ImageIO.write(image, "jpg",new File("/something.jpg"));

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        outputStream.flush();
        byte[] imageInBytes = outputStream.toByteArray();
        outputStream.close();

            URL url = new URL(putUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod(HttpMethod.PUT);
            connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, PNG_MIME_TYPE);
            OutputStream stream = connection.getOutputStream();

            try {
                stream.write(imageInBytes);
            } finally {
                stream.close();
                connection.disconnect();
            }

            switch (connection.getResponseCode()) {
                case HttpURLConnection.HTTP_OK:
                    return "";
                default:
                    break;
            }

        } catch (Exception e) {
        log.error("Exception occured", e);
        throw e;
    }

Answer

There would be no point converting to BufferedImage and back for the copy when you can preserve the byte stream of the original files. The first part can be replaced with simple call to extract the bytes off your website:

byte[] imageInBytes = read(urlGet);

Where read() is:

private static byte[] read(URL url) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream(16*1024);
    try (var in = url.openStream()) {
        in.transferTo(out);
    }
    return out.toByteArray();
}

If you use JDK11 onwards you could try the HttpClient class for the GET and POSTs, for example this does same as above if passing it urlGet.toURI():

private static byte[] read(URI uri) throws IOException, InterruptedException
{
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder().uri(uri).build();
    var resp = client.send(request, BodyHandlers.ofByteArray());
    return resp.body();
}


Source: stackoverflow