【发布时间】:2011-01-16 10:49:10
【问题描述】:
我正在尝试使用 Java 将 JPEG 图像从 URL 保存到文件中。 网址:http://150.214.222.100//axis-cgi/mjpg/video.cgi?resolution=640x480&compression=1&duration=1&timeout=&dummy=garb
我尝试了以下方法: 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) 不能
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 Content-Type: image/jpeg Content-Length: 38256 ....
二进制文件中不应有任何文本。
可能是什么问题?
【问题讨论】:
-
注意:您使用第二种方法得到的是从 URL 检索到的 full 内容 - 包括标头,其中包含有关服务器发回的信息的信息。 (通常我们使用浏览器查看互联网上的项目,浏览器会解释标题以供自己使用并仅向我们显示内容。)
-
那些不是 http 标头,它们是 mime 标头。它们不存在于绝大多数 http 响应中,但在这种情况下它们是 http 响应主体的一部分。请参阅下面的回复。如果您的浏览器使用给定的 url 显示图像,那是因为它足够聪明,可以解析 mime 部分。