如何从JavaFXImageView获取字节[]?

如何从JavaFXImageView获取字节[]?,java,image,javafx,byte,processing,Java,Image,Javafx,Byte,Processing,如何从javafx image/imageview类中获取字节[]?我想将我的图像作为一个Blob存储到我的数据库中。这是我使用的方法 public PreparedStatement prepareQuery(HSQLDBConnector connector) { try { Blob logoBlob = connector.connection.createBlob(); logoBlob.setBytes(0,logo.

如何从javafx image/imageview类中获取字节[]?我想将我的图像作为一个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;
    }
public PreparedStatement prepareQuery(HSQLDBConnector连接器){
试一试{
Blob logoBlob=connector.connection.createBlob();
logoBlob.setBytes(0,logo.getImage());//卡在这里
对于(int i=0,a=1;i
是否有方法将当前对象(imageview)、图像转换为字节[]?或者我应该开始考虑使用其他类来处理图像/或者指向具有引用的位置并使用路径/URL?尝试以下方法:

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字节数组


Lorenzo的答案是正确的,这个答案只是考察了效率和可移植性方面

根据图像类型和存储要求,将图像转换为压缩格式以便存储可能是有效的,例如:

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

在持久化图像之前,将图像转换为png等通用格式的另一个优点是,处理数据库的其他程序能够读取图像,而无需尝试将其从JavaFX特定的字节数组存储格式转换

谢谢,我担心我必须使用一些swing方式。巴德,我认为这会很好。巴德,难道没有任何纯JavaFX方式可以做到这一点吗?或者这是JavaFX从图像中获取字节[]的完全推荐方式吗?是的,有一个纯JavaFX解决方案,但对我来说这是一个未知领域。我有一个字节[]数组。如何使用此字节[]加载ImageView。
Image.write
的文档说明:写入操作完成后,此方法不会关闭提供的输出流;如果需要,调用方有责任关闭流。这对我来说意味着必须关闭ByteArrayOutputStream或使用try with ressource块。如何将整个
ImageView
转换为字节数组而不是
Image
?如果使用此选项,可写PixelFormat wf=PixelFormat.getByteBgraInstance();然后pr.getPixels(0,0,(int)(i.getWidth()),(int)i.getHeight(),wf,buffer,0,(int)(4*i.getWidth());scanlineStride需要是4*image.getwidth(),我不明白,blob输出在哪里?
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
ImageIO.write(SwingFXUtils.fromFXImage(fxImage, null), "png", byteOutput);
Blob logoBlob = connector.connection.createBlob();
logoBlob.setBytes(0, byteOutput.toByteArray());