【发布时间】:2020-03-09 18:12:11
【问题描述】:
基本上,我有一个名为“person”的表的本地 postgres 数据库,它有一个名为“image”的列,这是一个包含 .png 图像的 bytea 列。我不使用 postgresql,我想将图像下载为来自另一列的名称,后缀为“.png”
我found 的所有答案都是 postgres 方面的答案,我真的无法接受。 R或python中是否有可以下载图像的正版包?
【问题讨论】:
标签: python r postgresql
基本上,我有一个名为“person”的表的本地 postgres 数据库,它有一个名为“image”的列,这是一个包含 .png 图像的 bytea 列。我不使用 postgresql,我想将图像下载为来自另一列的名称,后缀为“.png”
我found 的所有答案都是 postgres 方面的答案,我真的无法接受。 R或python中是否有可以下载图像的正版包?
【问题讨论】:
标签: python r postgresql
这是使用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