Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 10th, 2012  |  syntax: None  |  size: 2.05 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. R : readBin and writeBin ( for storing/retrieving MySQL BLOBs or LONGBLOBs )
  2. plot_binary <- paste(readBin("temp.png", what="raw", n=1e6), collapse="")
  3.        
  4. > f = file ( "backIntoFile.png", "wb")
  5. > writeBin(object = plot_binary, con = f )
  6. > close(f)
  7.        
  8. plot_binary <- readBin("temp.png", what="raw", n=1e6)
  9.  
  10. > f = file ( "backIntoFile.png", "wb")
  11. > writeBin(object = plot_binary, con = f )
  12. > close(f)
  13.        
  14. binary.string <- paste(readBin("temp.png", what="raw", n=1e6), collapse="-")
  15.        
  16. > split = strsplit ( binaryString, split = "-" )
  17. > split = unlist ( split )
  18. > back.to.binary = as.raw ( as.hexmode ( split ) )
  19. > f = file ( "backIntoFile.png", "wb")
  20. > writeBin(object = back.to.binary, con = f )
  21. > close(f)
  22.        
  23. sz <- as.integer(system("stat --format %s temp.png", intern=T))
  24.        
  25. plot_binary <- paste(readBin("temp.png", what="raw", n=1e6), collapse="")
  26. theBinary <- unlist(lapply((1:(nchar(plot_binary)/2))*2, function(i)return(as.raw(as.hexmode(substr(plot_binary,i-1,i))))))
  27.        
  28. # Helper function I use
  29. Paste <- function(string, vals)
  30. {
  31.     string <- gsub(x = string, pattern = '\?', replacement = "%s")
  32.     result <- do.call(sprintf, as.list(c(string,vals)))
  33.     return(result)
  34. }
  35. # conn is a RMySQL connection object
  36. DbInsertImage <- function( conn, link.to.file )
  37. {
  38.  
  39.         binary = readBin ( link.to.file , what = "raw", n = 1e6 )
  40.         binary.str = paste ( binary, collapse = "" )
  41.         statement = Paste ( "CALL InsertImage('?')" , c(binary.str))
  42.         dbSendQuery(conn, statement )
  43.         return(GetIdentity(conn)) # one of my helper functions ;
  44.             # it returns the "LAST INSERT ID"
  45. }
  46.  
  47. #conn is a RMySQL connection object
  48. DbDownloadImage <- function( conn, id, destination)
  49. {
  50.  
  51.     query = "SELECT Data FROM Image WHERE Id = ? LIMIT 1"
  52.     query = Paste( query, c( id ) )
  53.     result = dbGetQuery(conn, query )$Data[1]
  54.  
  55.     sst <- strsplit(result, "")[[1]]
  56.     result <- paste0(sst[c(TRUE, FALSE)], sst[c(FALSE, TRUE)])
  57.     result <- as.raw ( as.hexmode ( result ) )
  58.  
  59.     f = file ( destination, "wb")
  60.  
  61.     writeBin(object = result, con = f )
  62.     close(f)
  63. }