如何从FileInputStream中的数据库读取Image Blob类型

时间:2018-10-16 08:28:21

标签: java ms-word apache-poi

我想将数据库中的图像插入到Microsoft Word文件中。 图像格式为Blob。 我使用Apache POI制作MS Word文件。 要将图像插入MS Word文件,需要

XWPFRun run.addPicture( new FileInputStream(ImageFile) , ImageFormat, ImageName, Units.toEMU(650), Units.toEMU(80));

该函数需要一个FileInputStream对象作为参数。 那么如何使“ Image Blob类型”可以在FileInputStream中读取呢? 我已经使用文件类将其转换为“文件”,并转换为OutputStream对象,但是它不起作用。 这是我的最后一个密码

................    
XWPFRun run1 = paragraph.createRun();        
    File image = get_dataImage();
    String gambar = image.toString();
    int imgFormat = getImageFormat(nama_gambar());
    run1.addPicture( new FileInputStream(image) , imgFormat, nama_gambar(), Units.toEMU(650), Units.toEMU(80));
    CTDrawing drawing = run1.getCTR().getDrawingArray(0);
    CTGraphicalObject graphicalobject = drawing.getInlineArray(0).getGraphic();
    CTAnchor anchor = getAnchorWithGraphic(graphicalobject, nama_gambar(), 
    Units.toEMU(600), Units.toEMU(70), 
    Units.toEMU(-5), Units.toEMU(-10));
                drawing.setAnchorArray(new CTAnchor[]{anchor});
                drawing.removeInline(0);
........................

功能获取图像文件

public static File get_dataImage() throws SQLException, IOException {
        File file = null;
        Connection conn = Koneksi.getKoneksi();
        String sql = "SELECT*FROM setting";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            Blob imageBlob = resultSet.getBlob("file_gambar");
            byte [] array = imageBlob.getBytes( 1, ( int ) imageBlob.length() );
            file = File.createTempFile("something-", ".binary", new File("."));
        }
        return file;
    }

功能获取图像名称

public String nama_gambar() throws SQLException {
        String nama_gambar = null;
        Connection conn = Koneksi.getKoneksi();
        String sql = "SELECT*FROM setting";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            nama_gambar = resultSet.getString("nama_gambar");
        }
        return nama_gambar;
    }

这是结果 enter image description here

1 个答案:

答案 0 :(得分:0)

我刚刚找到了解决方案。我不知道为什么我没有意识到,解决方案非常简单。也许是因为过去几天我因缺乏睡眠而太困了

public static InputStream get_dataImage() throws SQLException, IOException {
            InputStream in = null;
            Connection conn = Koneksi.getKoneksi();
            String sql = "SELECT*FROM setting";
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                Blob imageBlob = resultSet.getBlob("file_gambar");
                in = imageBlob.getBinaryStream();
            }
            return in;
        }