java—将图像从url复制到http url

nwo49xxi  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(415)

有人正在提供一个s3预签名的网址,以便我可以上传我的图片到该链接。我所有的照片都在网站上。java中有没有一种方法可以将图像url复制到提供的新url中?
我正试着这么做。似乎有点过分了

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

vq8itlhq1#

当您可以保留原始文件的字节流时,转换为BuffereImage并返回副本就没有意义了。第一部分可以替换为从网站中提取字节的简单调用:

byte[] imageInBytes = read(urlGet);

哪里 read() 是:

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

如果您使用jdk11以后的版本,您可以尝试使用httpclient类进行get和posts,例如,如果传递它,则执行与上面相同的操作 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();
}

相关问题