- R : readBin and writeBin ( for storing/retrieving MySQL BLOBs or LONGBLOBs )
- plot_binary <- paste(readBin("temp.png", what="raw", n=1e6), collapse="")
- > f = file ( "backIntoFile.png", "wb")
- > writeBin(object = plot_binary, con = f )
- > close(f)
- plot_binary <- readBin("temp.png", what="raw", n=1e6)
- > f = file ( "backIntoFile.png", "wb")
- > writeBin(object = plot_binary, con = f )
- > close(f)
- binary.string <- paste(readBin("temp.png", what="raw", n=1e6), collapse="-")
- > split = strsplit ( binaryString, split = "-" )
- > split = unlist ( split )
- > back.to.binary = as.raw ( as.hexmode ( split ) )
- > f = file ( "backIntoFile.png", "wb")
- > writeBin(object = back.to.binary, con = f )
- > close(f)
- sz <- as.integer(system("stat --format %s temp.png", intern=T))
- plot_binary <- paste(readBin("temp.png", what="raw", n=1e6), collapse="")
- theBinary <- unlist(lapply((1:(nchar(plot_binary)/2))*2, function(i)return(as.raw(as.hexmode(substr(plot_binary,i-1,i))))))
- # 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)
- }