Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get byte[] from javafx imageView?

How do i get byte[] from javafx image/imageview class? I want to store my image as a Blob into my database.This is the method that i use for it

 public PreparedStatement prepareQuery(HSQLDBConnector connector) {
        try {
            Blob logoBlob = connector.connection.createBlob();
            logoBlob.setBytes(0,logo.getImage());//stuck  here
            for (int i = 0, a = 1; i < data.length; i++, a++) {

                connector.prepStatCreateProfile.setString(a, data[i]);

            }
            //store LOB

            connector.prepStatCreateProfile.setBlob(11, logoBlob);

        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return connector.prepStatCreateProfile;
    }

Is there a way to convert from my current object (imageview),image) into byte[]?, or shoud i start to think about using other class for my image/ alternatively point to the location with reference and work with paths/urls?

like image 658
Tomas Bisciak Avatar asked Jun 04 '14 13:06

Tomas Bisciak


2 Answers

pure java fx solution trace ( == you will have to fill in missing points :)

Image i = logo.getImage();
PixelReader pr = i.getPixelReader();
PixelFormat f = pr.getPixelFormat();

WriteablePixelFromat wf = f.getIntArgbInstance(); //???

int[] buffer = new int[size as desumed from the format f, should be  i.width*i.height*4];

pr.getPixels(int 0, int 0, int i.width, i.height, wf, buffer, 0, 0);
like image 69
Lorenzo Boccaccia Avatar answered Oct 16 '22 09:10

Lorenzo Boccaccia


Lorenzo's answer is correct, this answer just examines efficiency and portability aspects.

Depending on the image type and storage requirements, it may be efficient to convert the image to a compressed format for storage, for example:

ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ImageIO.write(SwingFXUtils.fromFXImage(fxImage, null), "png", byteOutput);
Blob logoBlob = connector.connection.createBlob();
logoBlob.setBytes(0, byteOutput.toByteArray());

Another advantage of doing a conversion to a common format like png before persisting the image is that other programs which deal with the database would be able to read the image without trying to convert it from a JavaFX specific byte array storage format.

like image 3
jewelsea Avatar answered Oct 16 '22 08:10

jewelsea