0

I'm trying to get an image from a web page and write to a file, but in the end my photo viewer doesn't recognize the picture file and can't open it (the file is unreadable).

Here is my code:

URL urlpic = new URL("https://static.asset.aparat.com/lp/16107806-6200-m.jpg");//sample pic url HttpURLConnection connectionToPicFile=(HttpURLConnection)urlpic.openConnection(); BufferedReader buffPic=new BufferedReader(new InputStreamReader(connectionToPicFile.getInputStream()));

String pic = "";
String alldatapic = "";
while((pic=buffPic.readLine()) != null)
{
    alldatapic += pic;
}

try
{
    FileOutputStream fout = new FileOutputStream("D://pic.jpg");//where i want the file to be saved
    byte[] b = alldatapic.getBytes();
    fout.write(b);
    fout.close();
}
catch(Exception ex)
{
    System.out.println(ex.toString()+"   "+ex.getMessage());
}
Ehsan Khodarahmi
  • 4,772
  • 10
  • 60
  • 87
Soheil Rahsaz
  • 719
  • 7
  • 22

1 Answers1

1

You should use something like this:

BufferedImage image = null;
        try {

            URL url = new URL("https://static.asset.aparat.com/lp/16107806-6200-m.jpg");
            image = ImageIO.read(url);

            ImageIO.write(image, "jpg", new File("E:\\out.jpg"));


        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Done");
    }

On windows 10 you cannot use the root path (C:\) to store the new files.

  • Thank you for your answer.But, is there any way to this by writing with bufferedwriter? – Soheil Rahsaz Jan 13 '18 at 22:36
  • Short answer: no – Stephen C Jan 13 '18 at 23:10
  • No need for ImageIO, which will write the file with new parameters. Just [copy the URL](https://docs.oracle.com/javase/9/docs/api/java/nio/file/Files.html#copy-java.io.InputStream-java.nio.file.Path-java.nio.file.CopyOption...-). – VGR Jan 14 '18 at 02:32