I am trying to save a JPEG image from a URL to a file with Java. URL: http://150.214.222.100//axis-cgi/mjpg/video.cgi?resolution=640x480&compression=1&duration=1&timeout=&dummy=garb
I tried the following: 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);
}
=> Exception:"Width (-1) and height (-1) cannot be <= 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();
}
The file is somehow broken. When I open it with Kate, I can read:
--myboundary Content-Type: image/jpeg Content-Length: 38256 ....
There should not be any text in a binary file.
What could the problem be?