我試圖將URL中的JPEG圖像保存爲使用Java的文件。 URL:http://150.214.222.100//axis-cgi/mjpg/video.cgi?resolution=640x480&compression=1&duration=1&timeout=&dummy=garb如何將JPEG從URL保存到文件?
我嘗試以下: 1)
Image image = fetchImage(urlNorthView);
saveImage2Disk(image);
public static Image fetchImage(URL u) throws MalformedURLException, IOException {
Toolkit tk = Toolkit.getDefaultToolkit();
return tk.createImage(u);
}
private void saveImage2Disk(Image Image) throws IOException{
File outputFile = new File("urlNorthView"+Calendar.getInstance().getTimeInMillis()+".jpg");
BufferedImage bufferedImage = new BufferedImage(Image.getWidth(null),Image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(Image, null, null);
ImageIO.write(bufferedImage, "jpg", outputFile);
}
=>異常: 「寬度(-1)和高度(-1)不能< = 0」
2 )
inputStream2Disk((InputStream) urlNorthView.getContent());
private void inputStream2Disk(InputStream in) throws Exception{
File outputFile = new File("urlNorthView"+Calendar.getInstance().getTimeInMillis()+".jpg");
OutputStream out=new FileOutputStream(outputFile);
byte buf[]=new byte[1024];
int len;
while((len=in.read(buf))>0)
out.write(buf,0,len);
out.close();
in.close();
}
該文件不知何故被破壞。當我與Kate打開它,我可以讀:
--myboundary內容類型:圖像/ JPEG內容長度:38256 ....
不應該有在任何文本二進制文件。
問題是什麼?
注意:第二種方法得到的是從URL中檢索的* full *內容 - 包括標題,其中包含信息關於服務器發回的內容。 (通常,我們使用瀏覽器查看互聯網上的項目,瀏覽器將解釋標題以供自己使用,並僅向我們顯示內容。) – Arkaaito 2010-02-13 09:09:43
這些不是http標題,它們是mime標題。它們並不存在於絕大多數http響應中,但在這種情況下它們是http響應主體的一部分。請參閱下面的回覆。如果您的瀏覽器使用給定的URL顯示圖像,這是因爲它足夠聰明來解析MIME部分。 – 2010-02-13 09:32:35