36

I already know where the image is, but for simplicity's sake I wanted to download the image using JSoup itself. (This is to simplify getting cookies, referrer, etc.)

This is what I have so far:

//Open a URL Stream
Response resultImageResponse = Jsoup.connect(imageLocation).cookies(cookies).ignoreContentType(true).execute();

// output here
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(new java.io.File(outputFolder + name));
//BufferedWriter out = new BufferedWriter(new FileWriter(outputFolder + name));
out.write(resultImageResponse.body());          // resultImageResponse.body() is where the image's contents are.
out.close();
Prakash K
  • 11,669
  • 6
  • 51
  • 109
  • 5
    you can do it without jsoup with this one liner. [FileUtils#copyURLToFile](http://commons.apache.org/io/apidocs/org/apache/commons/io/FileUtils.html). – Sorter Feb 12 '13 at 10:32

2 Answers2

53

I didn't even finish writing the question before I found the answer via JSoup and a little experimentation.

//Open a URL Stream
Response resultImageResponse = Jsoup.connect(imageLocation).cookies(cookies)
                                        .ignoreContentType(true).execute();

// output here
FileOutputStream out = (new FileOutputStream(new java.io.File(outputFolder + name)));
out.write(resultImageResponse.bodyAsBytes());  // resultImageResponse.body() is where the image's contents are.
out.close();
Prakash K
  • 11,669
  • 6
  • 51
  • 109
  • 4
    Explanation: Images are binary data, not character data. `Response#body()` returns a `String`, you should be retrieving the raw byte array instead. Also, using a `Writer` converts bytes to characters, you should stick to `OutputStream`. – BalusC Sep 17 '12 at 19:07
  • Indeed, initially I was wrong on many counts. Well, at least I hope I didn't overstep my boundaries by writing an immediate response :-p Couldn't find anything like this anywhere on this site, at least. –  Sep 17 '12 at 19:23
  • 1
    Thanks @BalusC! These other answers helped me: how to get [image bytes from JSoup](http://stackoverflow.com/a/12663619/519951) and [save bytes array to file](http://stackoverflow.com/questions/1580038/byte-array-to-image-file) – ruhong Dec 02 '15 at 13:20
1

Simply you can use these methods-

public static String storeImageIntoFS(String imageUrl, String fileName, String relativePath) {
    String imagePath = null;
    try {
        byte[] bytes = Jsoup.connect(imageUrl).ignoreContentType(true).execute().bodyAsBytes();
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        String rootTargetDirectory = IMAGE_HOME + "/"+relativePath;
        imagePath = rootTargetDirectory + "/"+fileName;
        saveByteBufferImage(buffer, rootTargetDirectory, fileName);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imagePath;
}

public static void saveByteBufferImage(ByteBuffer imageDataBytes, String rootTargetDirectory, String savedFileName) {
   String uploadInputFile = rootTargetDirectory + "/"+savedFileName;

   File rootTargetDir = new File(rootTargetDirectory);
   if (!rootTargetDir.exists()) {
       boolean created = rootTargetDir.mkdirs();
       if (!created) {
           System.out.println("Error while creating directory for location- "+rootTargetDirectory);
       }
   }
   String[] fileNameParts = savedFileName.split("\\.");
   String format = fileNameParts[fileNameParts.length-1];

   File file = new File(uploadInputFile);
   BufferedImage bufferedImage;

   InputStream in = new ByteArrayInputStream(imageDataBytes.array());
   try {
       bufferedImage = ImageIO.read(in);
       ImageIO.write(bufferedImage, format, file);
   } catch (IOException e) {
       e.printStackTrace();
   }

}