# file: Transparency_JPEG.R

# purpose: add transparency to jpeg

# author: kay cichini

require(jpeg)

require(png)

myimg <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"))

# create new array with 4 dimensions, the new dimension

# representing alpha:

# add alpha channel:

alpha = 0.5

newimg <- array(data = c(as.vector(myimg),

                    rep(alpha, dim(myimg)[1]*dim(myimg)[2])),

                    dim = c(dim(myimg)[1], dim(myimg)[2], 4))

# assign output file name:

mynewimg <- paste(tempfile(),".png", sep = "")

png(mynewimg, width = dim(myimg)[2]*5,

                  height = dim(myimg)[1]*5)

# print test img to plot region:

par(mar = rep(2, 4), oma = rep(0, 4), new = F)

plot(x = sample(100), y = sample(100),

         xlim = c(0, 100), ylim = c(0, 100),

         xlab = "", ylab = "",

         yaxs ="i", xaxs = "i")

rasterImage(newimg, 0, 0, 100, 100)

dev.off()

shell.exec(mynewimg)

# print img to plot region, producing img similar as input,

# but with transparency:

# assign new output file name..

mynewimg <- paste(tempfile(),".png", sep = "")

png(mynewimg, width = dim(myimg)[2]*5,

                  height = dim(myimg)[1]*5)

par(mar = rep(0, 4), oma = rep(0, 4), new = F)

plot(x = sample(100), y = sample(100),

         xlim = c(0, 100), ylim = c(0, 100),

         xlab = "", ylab = "", type = "n",

         yaxs ="i", xaxs = "i")

rasterImage(newimg, 0, 0, 100, 100)

dev.off()

shell.exec(mynewimg)