无法将BufferedImage保存到指定的URL

时间:2013-07-16 06:10:51

标签: java swing url bufferedimage javax.imageio

我正在尝试将图像存储在远程位置。

BufferedImage img;
img=ImageIO.read(file);
String url="http://localhost:8080/prashant Pic/j.jpg";
ImageIO.write(img, "jpg",new File("/home/com/Documents/images/p.jpg"));
ImageIO.write(img, "jpg",new File("http://localhost:8080/prashant Pic/j.jpg"));

它将图像存储在本地计算机上。但是不在localhost上。

1 个答案:

答案 0 :(得分:0)

完全可以将图像存储在远程位置。而不是使用File,使用类似:

URL url = new URL("http://localhost:8080/prashant%20Pic/j.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);

// Do necessary setup of connection, like:
//  - setting the HTTP method (POST/PUT)
//  - setting authentication parameters?
// These depends on what kind of service you have running on localhost:8080

OutputStream stream = connection.getOutputStream();
try {
    ImageIO.write(img, "jpg", stream);
}
finally {
    stream.close();
}

显然,您还需要在localhost:8080上运行的服务,它接受通过POST或PUT上传文件。