title: Convert JavaFX Image object to byte array
body: <p>We can create FX Image object by using</p>
  
  <pre><code>byte [] bytes = ------; //valid image in bytes
  javafx.scene.image.Image image = new Image(new ByteArrayInputStream(bytes));
  </code></pre>
  
  <p>And this can be set to an ImageView.</p>
  
  <p>I need the opposite <strong><em>without</em></strong> converting it first to the <strong><em>BufferedImage</em></strong> (SwingFXUtils.fromFXImage(image,null)).</p>
  
  <p>So that I can directly write the bytes to a file.</p>
  
  <p>I've tried the following:</p>
  
  <pre><code>PixelReader pixelReader = image.getPixelReader();
      int width = (int)image.getWidth();
      int height = (int)image.getHeight();
      byte[] buffer = new byte[width * height * 4];
      pixelReader.getPixels(
              0,
              0,
              width,
              height,
              PixelFormat.getByteBgraInstance(),
              buffer,
              0,
              width * 4
      );
  </code></pre>
  
  <p>But the file generated by writing the <strong>byte [] buffer</strong> is not a valid image.</p>
  
  <p>Any insights on this? </p>
  
  <p><strong>EDIT:</strong> The solutions given at <a href="https://stackoverflow.com/questions/24038524/how-to-get-byte-from-javafx-imageview">How to get byte[] from javafx imageView</a> cannot be applied to my question. As I've already mentioned clearly that I do not want to use converting it to BufferedImage using SwingFXUtils.
  Moreover, I want to convert it to the byte array so that it can be written to an image file.</p>