【问题标题】:How to download images from postgres bytea column using R or python?如何使用 R 或 python 从 postgres bytea 列下载图像?
【发布时间】:2020-03-09 18:12:11
【问题描述】:

基本上,我有一个名为“person”的表的本地 postgres 数据库,它有一个名为“image”的列,这是一个包含 .png 图像的 bytea 列。我不使用 postgresql,我想将图像下载为来自另一列的名称,后缀为“.png”

found 的所有答案都是 postgres 方面的答案,我真的无法接受。 R或python中是否有可以下载图像的正版包?

【问题讨论】:

    标签: python r postgresql


    【解决方案1】:

    这是使用R的解决方案:

    # Packages we need
    require("RPostgreSQL")
    require('jsonlite')
    
    # Create connection to database
    pgConn <- dbConnect(PostgreSQL(), dbname="your_db", host='127.0.0.1')
    
    # Query string - edit this to suit your needs
    # Important thing here is that we're getting Postgres to base64 encode
    #   the image data (converting it from binary to text)
    thisQ = "SELECT encode(imageColumn, 'base64') AS image from test_table WHERE name='image';"
    
    # Execute the SELECT query and fetch the results
    resultSet = dbSendQuery(pgConn, thisQ)
    resultData <- fetch(resultSet, n=-1)
    dbClearResult(resultSet)
    
    # Get the image data as text
    imageData <- resultData$image
    
    # Decode from base64 back to binary
    imageDataDecoded <- jsonlite::base64_dec(imageData)
    
    # Create a file connection and write the binary data to disk using mode "wb".
    write.filename = file("/temp/file.png", "wb")
    writeBin(imageDataDecoded, write.filename)
    close(write.filename)
    

    【讨论】:

    • 这一直有效到使用jsonlite。对我有用的是使用 base64enc::base64decode
    猜你喜欢
    • 2011-10-07
    • 2021-03-25
    • 2020-04-09
    • 2020-07-20
    • 2017-06-05
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多