如何从javafx imageView获取byte[]?

2022-09-03 12:51:39

如何从javafx image/imageview类中获取byte[]?我想将图像作为 Blob 存储到我的数据库中。这是我使用它的方法

 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;
    }

有没有办法从我当前的对象(图像视图),图像)转换为byte[]?,或者我应该开始考虑为我的图像使用其他类/或者指向带有引用的位置并使用路径/urls?


答案 1

试试这个:

BufferedImage bImage = SwingFXUtils.fromFXImage(logo.getImage(), null);
ByteArrayOutputStream s = new ByteArrayOutputStream();
ImageIO.write(bImage, "png", s);
byte[] res  = s.toByteArray();
s.close(); //especially if you are using a different output stream.

应该根据徽标类工作

您需要在写入和读取时指定格式,据我所知,bmp不受支持,因此您将在数据库上得到一个png字节数组


答案 2

纯java fx解决方案跟踪( == 你将不得不填写缺失的点:)

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);

推荐