Sunday, September 20, 2015

An Image Crossfader Function

Some project offspin, the jpgfader-function (the jpgfader-function in funny use can be viewed HERE):


# purpose: crossfade 2 jpeg images
# packages: jpeg
# arguments: img1 (path.to.img1), img2 (path.to.img2),
# outpath(defaults to current directory), outname,
# frames
# output: png


require(jpeg)

jpgfader <- function(img1 = NA, img2 = NA, outpath = NA, frames = NA, outname = NA){

if(is.na(outpath)) {outpath <- path.expand("~")}

# stop if images are missing
if(is.na(img1)|is.na(img2)) stop(cat("\nAt least one image is missing!\n"))
if(is.na(outname)) {outname = "img.1.2"}

if(is.na(frames)) {frames = 10}
# read 2 jpegs, assuming same size!
pic.1 <- readJPEG(img1)
pic.2 <- readJPEG(img2)

# warn if images dont have same size:
if(sum(dim(pic.1) != dim(pic.2))>1) warning(cat("\nImages do not have same dimensions!"))

# create new array with 4 dimensions, the new dimension
# representing alpha:

by = 1/(frames-1)
alpha = seq(0, 1, by)
n = length(alpha)

for(j in n:1){

pic.2.a <- array(data = c(as.vector(pic.2),
rep(alpha[j], dim(pic.1)[1]*dim(pic.1)[2])),
dim = c(dim(pic.1)[1], dim(pic.1)[2], 4))

# assign output file name:
pic.out <- paste(outpath, "\\", outname, ".", j ,".png", sep = "")

# and open device:
png(pic.out, width = dim(pic.1)[2], height = dim(pic.1)[1])

# plot-parameters:
par(mar = rep(0, 4), oma = rep(0, 4), new = F)

# print img.a to plot region:
plot(1:2,
xlim = c(0, dim(pic.1)[2]), ylim = c(0, dim(pic.1)[1]),
xlab="", ylab="", type = "n",
yaxs ="i", xaxs = "i")
rasterImage(pic.1, 0, 0, dim(pic.1)[2], dim(pic.1)[1])

# overplotting with new alpha-pic,
# starting with full transparency, decreasing in steps, showing pic.2
# finally:
rasterImage(pic.2.a, 0, 0, dim(pic.1)[2], dim(pic.1)[1])
dev.off()
}
}

# Example, with 2 images, one system.file and one altered
# version of it:

# make black jpg and save to default system folder
Rlogo <- readJPEG(system.file("img", "Rlogo.jpg", package="jpeg"))
Rlogo[] <- 0
jpeg(path.expand("~\\Rlogo_Black.jpg"), dim(Rlogo)[2], dim(Rlogo)[1])
par(mar = rep(0, 4), oma = rep(0, 4))

# save black image:
plot(1:2,
xlim = c(0, 1), ylim = c(0, 1),
xlab="", ylab="", type = "n",
yaxs ="i", xaxs = "i")
rasterImage(Rlogo, 0, 0, 1, 1)
dev.off()

# function call:
jpgfader(img1 = system.file("img", "Rlogo.jpg", package="jpeg"),
img2 = path.expand("~/Rlogo_black.jpg"),
outname = "img12",
outpath = path.expand("~"),
frames = 10)

# see the images:
browseURL(path.expand("~"))

# remove files:
# files <- dir(path.expand("~"), full.names = T)
# file.remove(c(files[grep("img12.", files)],
path.expand("~/Rlogo_black.jpg")))

No comments:

Post a Comment