前回のつづきです。前回は rapache の設定と簡単なCGIを作ってみました。今度は画像を出力して表示する CGI を作ります。内容は、乱数を適当に作ってヒストグラムを作画するCGIです。画像はランダムなファイル名で保存します。

# Functions
header <- function(contenttype) {
  setContentType(contenttype)
}
html.head <- function(content) {
  cat("<head>\n")
  cat(content)
  cat("</head>\n")
}
html.body <- function(content) {
  cat("<body>\n")
  cat(content)
  cat("</body></html>\n")
}
randomFileName <- function(prefix, postfix) {
  filename <- paste(
    prefix,
    sprintf("%08d", as.integer(runif(1, 0, 10^7))),
    postfix,
    sep=""
  )
  return(filename)
}                                                                               

# Main
image_dir <- "/var/www/images"
filename  <- randomFileName("hist_", ".png")
filepath  <- paste(image_dir, filename, sep="/")                                

data <- rnorm(1000)                                                             

# output html
header("text/html")
html.head("<title>Test</title>")                                                

png(filepath)
hist(data)
dev.off()                                                                       

html.body(
  paste(
    "<img src="/images/",
    filename,
    '">',
    sep=""
  )
)

リロードすると画像が変わるのがわかると思います。次回はもっと役に立つものを作ってみます。

寧々さんかわいいです。