【问题标题】:How to get byte[] from javafx imageView?如何从 javafx imageView 获取字节 []?
【发布时间】:2014-07-25 04:01:20
【问题描述】:

如何从 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;
    }

有没有办法将我当前的对象 (imageview),image) 转换为 byte[]?,或者我应该开始考虑为我的图像使用其他类/或者通过引用指向该位置使用路径/网址?

【问题讨论】:

    标签: java image javafx byte processing


    【解决方案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 字节数组

    【讨论】:

    • 谢谢,我担心我将不得不使用一些摇摆方式。我认为这会行得通,难道没有任何纯 JavaFX 方法可以做到这一点吗?或者这是完全推荐的 javafx 获得方式图片中的字节[]?
    • 是的,有一个纯 java fx 解决方案,但它对我来说是未知领域。
    • 我有一个 byte[] 数组。如何使用此字节 [] 加载 ImageView。
    • Image.write的文档说明:该方法在写操作完成后不会关闭提供的OutputStream;如果需要,调用者有责任关闭流。这表明我有必要关闭 ByteArrayOutputStream 或使用 try-with-ressource 块。
    • 如何将整个ImageView 转换为字节数组而不是Image
    【解决方案2】:

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

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

    【讨论】:

    • 如果你使用这个,WritablePixelFormat 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输出在哪里?
    • 在 int[] 缓冲区中
    【解决方案3】:

    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 特定的字节数组存储格式转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多