简体   繁体   English

如何从 java(或 groovy)中的 postgres-db 读取字节格式的二进制数据并保存为 jpeg 文件?

[英]How to read binary data which is in bytea-format from postgres-db in java (or groovy) and save as jpeg-file?

We have a postgres-DB-dump where all kinds of files (png, jpg, pdf etc..) are stored as binary data in bytea format.我们有一个 postgres-DB-dump,其中各种文件(png、jpg、pdf 等)都以字节茶格式存储为二进制数据。 We'd have to read them out and store them as a file (eg .jpg) on the server using grooy or java.我们必须使用 grooy 或 java 将它们读出并作为文件(例如 .jpg)存储在服务器上。

The problem is at the moment that the files, whichare are created, are corrupted (altough the same code worked in an earlier db-dump on another server).问题在于创建的文件已损坏(尽管在另一台服务器上的早期 db-dump 中工作的代码相同)。 No valid files are created.未创建有效文件。

data in db-column with sql-query looks like this: \x1f8b0800000000000000ed5adb6edb38107ddfaf10f45a14be245d20852320698316089214a9fb2c50d2d8264c912e49b5f57ecffec9fed892badf68c9 ... 2048 bytes per row.带有 sql-query 的 db-column 中的数据如下所示: \x1f8b0800000000000000ed5adb6edb38107ddfaf10f45a14be245d20852320698316089214a9fb2c50d2d8264c912e49b5f57ecffec9fed892badf68c9 ...9fed8982badf 每行 28 个字节。 some files spread over multiple rows..一些文件分布在多行..

//Get data from DB: binary data, mime_type, file_ID
    GroovyRowResult[] data = sql.rows("""
      SELECT lo.loid loid, lo.pageno pageno, lo.data d, nb.hash  hash, nb.size size, nb.mime_type mime_type,
      nb.data nb_loid, nb.file_extension ext FROM <tablename containing binary data> lo
      LEFT JOIN <tablename helptable metainfo> nb ON lo.loid = nb.data
      WHERE lo.loid = $loid
      """)

    def fileId = data[0].loid.toString()
    def mimeType = data[0].mime_type.toString()
    def temp = []

    //read out binary data into a byte array
    data.each { GroovyRowResult row ->
      temp << row.d
    }
    //read the byte array into an input stream
    InputStream inputStream = new ByteArrayInputStream((byte[]) temp.flatten(), 0, temp.flatten().size())

    def systemSettings = SystemSettings.getInstance(application)

    def newFileId = FileInBinaryFormat.detectTypeAndSave(<folderID on Server>, application.getRealPath(systemSettings.getDocumentPath()), fileId, mimeType, inputStream)

which calls the following method, after having identified the mime-type from metainformation in db: FileEntry represents an uploaded document on our server.在从 db 中的元信息中识别出 mime 类型之后,它调用以下方法: FileEntry 表示我们服务器上上传的文档。

  static String saveAsImage(InputStream inputStream, String fileName, Folder folder, String path, Connection conn, String fileExtension) {

    BufferedImage bufferedImage = null
    try {
      bufferedImage = ImageIO.read(inputStream)
   } catch (IOException e){
      ...
    }

    try{ 
      def newFile = new File(path,"${UniqueID.createHexId()}"+fileExtension)
      ImageIO.write(bufferedImage, fileExtension, newFile)
        def fileEntry = FileEntry.createNewEntry(newFile, conn, folder, Customer.getCustomer(<CustomerNumber>),
        "", fileName + fileExtension)
      return fileEntry.id   
    } catch (IOException e) {
      ...
    } 
  }

Does anybody see some obvious mistakes causing the Problem or can help me in any way?是否有人看到导致问题的一些明显错误或可以以任何方式帮助我? Many thanks in Advance!提前谢谢了!

EDIT: Some more information:编辑:更多信息:

When one logs "newFile", it shows a path to a file.当一个人记录“newFile”时,它会显示一个文件的路径。 However there is no file found on the server in the directory.但是,在目录中的服务器上找不到文件。 so no file is created.所以没有文件被创建。

The log of the buffered image looks like this:缓冲图像的日志如下所示:

[Date:Time] BufferedImage@57c0c3cb: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@6bcd3bb4 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 277 height = 368 #numDataElements 3 dataOff[0] = 2

The byte array is an array in the form: [-1, 125, 5, 6, ..., ] (signed 2 complement of hex values in DB column).字节数组是以下形式的数组:[-1, 125, 5, 6, ..., ](DB 列中十六进制值的有符号 2 补码)。 So this seems to work.所以这似乎有效。

I added "Order BY pageno" in the query in order to make sure the ordering of the rows is correct.我在查询中添加了“Order BY pageno”,以确保行的顺序正确。

I found the solution.我找到了解决方案。 The Problem was in the ImageIO.write(bufferedImage, fileExtension, newFile) secion.问题出在ImageIO.write(bufferedImage, fileExtension, newFile)部分。 the variable 'fileExtension' included a dot: ".jpeg", ".png" etc. It need to be without a dot.变量“fileExtension”包括一个点:“.jpeg”、“.png”等。它需要没有点。 So after changeing that and changeing the row above to: def newFile = new File(path,UniqueID.createHexId()+"."+fileExtension) did the job.所以在改变它并将上面的行更改为: def newFile = new File(path,UniqueID.createHexId()+"."+fileExtension)完成了这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM