我正在使用 readBin 函数将文件保存为 MySQL BLOB,如本文所述(http://www.r-bloggers.com/save-r-plot-as-a-blob/)
plot_binary <- paste(readBin("temp.png", what="raw", n=1e6), collapse="")
Run Code Online (Sandbox Code Playgroud)
我的问题是:一旦这是在数据库中,我如何将其转储回文件?
> f = file ( "backIntoFile.png", "wb")
> writeBin(object = plot_binary, con = f )
> close(f)
Run Code Online (Sandbox Code Playgroud)
这不起作用;该文件似乎不是有效的 png ;
干杯!
这是迄今为止我找到的最佳解决方案。DbDownloadImages 函数的执行时间非常短(实际上几乎不需要时间)。
# Helper function I use
Paste <- function(string, vals)
{
string <- gsub(x = string, pattern = '\\?', replacement = "%s")
result <- do.call(sprintf, as.list(c(string,vals)))
return(result)
}
# conn is a RMySQL connection object
DbInsertImage <- function( conn, link.to.file )
{
binary = readBin ( link.to.file , what = "raw", n = 1e6 )
binary.str = paste ( binary, collapse = "" )
statement = Paste ( "CALL InsertImage('?')" , c(binary.str))
dbSendQuery(conn, statement )
return(GetIdentity(conn)) # one of my helper functions ;
# it returns the "LAST INSERT ID"
}
#conn is a RMySQL connection object
DbDownloadImage <- function( conn, id, destination)
{
query = "SELECT Data FROM Image WHERE Id = ? LIMIT 1"
query = Paste( query, c( id ) )
result = dbGetQuery(conn, query )$Data[1]
sst <- strsplit(result, "")[[1]]
result <- paste0(sst[c(TRUE, FALSE)], sst[c(FALSE, TRUE)])
result <- as.raw ( as.hexmode ( result ) )
f = file ( destination, "wb")
writeBin(object = result, con = f )
close(f)
}
Run Code Online (Sandbox Code Playgroud)
另请参阅: 如何将字符串拆分为给定长度的子字符串?
| 归档时间: |
|
| 查看次数: |
4286 次 |
| 最近记录: |