0

I want to save image into database. I have a Customer model that has Image property in it. I am creating a class that handle all the customer related database operations. In that class I have a method that takes in Customer object and inserts it into the database. Therefore, I have only Customer object to work with. How can I convert that Image object into byte array so that I can insert it into the datbase?

I know how to extract byte array from a file object. Should I change the customer model to contain image file instead of image object?

  • Can you upload your code. – Harun Diluka Heshan Jun 16 '19 at 03:27
  • I just want to know if I can get byte array from an Image object. I have not written any code for the database operations. – Shirish Koirala Jun 16 '19 at 03:51
  • It's possible with a lot of various avenues. Here's a very basic intro to it: https://www.geeksforgeeks.org/image-processing-java-set-1-read-write/ Read around and try to get a better idea of what exactly you want to do, then if you have issues with implementation or anything you can ask a more specific question. – Matthew Kerian Jun 16 '19 at 03:56
  • I want to know if it is possible to get byte array from javafx.scene.image.Image? – Shirish Koirala Jun 16 '19 at 04:09
  • Hey mate can you try with this ? BufferedImage bImage = ImageIO.read(new File("sample.jpg")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bImage, "jpg", bos ); byte [] data = bos.toByteArray(); – Mak Jun 16 '19 at 04:43
  • If you're using JavaFX then you can use the [`PixelReader`](https://openjfx.io/javadoc/12/javafx.graphics/javafx/scene/image/PixelReader.html) and [`PixelWriter`](https://openjfx.io/javadoc/12/javafx.graphics/javafx/scene/image/PixelWriter.html) interfaces. They have methods for reading and writing the pixel data using `byte[]`, `int[]`, `ByteBuffer`, or `IntBuffer`. Note that these won't be compressed (i.e. the data won't be in a format such as PNG or JPG). If you want to store the _file_ as bytes then you should do just that. If you don't have a file, see Mak's comment above. – Slaw Jun 16 '19 at 11:15

1 Answers1

0

This worked for me:

Image image = customer.getImage();

BufferedImage bufferedImage = SwingFXUtils.fromFXImage(image, null);
ByteArrayOutputStream byteArrayInputStream = new ByteArrayOutputStream();
try {
    ImageIO.write(bufferedImage, "jpeg", byteArrayInputStream);
} catch (IOException e) {
    e.printStackTrace();
}
byte[] buffer = byteArrayInputStream.toByteArray();