Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save infotroph/7ff919906d370c1173fa34f982cf18ae to your computer and use it in GitHub Desktop.
Save infotroph/7ff919906d370c1173fa34f982cf18ae to your computer and use it in GitHub Desktop.
Stacking PNGs in R
# Stack two PNGs on top of each other,
# filling any leftover pixels with white
#
# N.B. I'm assuming the alpha channel is always 1;
# I *think* this will handle transparency with no changes, but haven't tested
library("png")
# these are plain R arrays with 3 dimensions (row, col, rgba)
# -- not even wrapped in a class
a = readPNG("some_figure.png")
b = readPNG("other_figure.png")
adim = dim(a)
bdim = dim(b)
# channels should be RGBA, encoded as 0-1 not 0-255
# Might be unnecessary -- should check if readPNG guarantees this already
stopifnot(
adim[3] == 4,
bdim[3] == 4,
all(a >= 0 & a <= 1),
all(b >= 0 & b <= 1))
outdim=c(adim[1]+bdim[1], max(adim[2], bdim[2]), adim[3])
out = array(NA, dim=outdim)
out[1:adim[1], 1:adim[2], 1:adim[3]] = a
out[(adim[1]+1):outdim[1], 1:bdim[2], 1:bdim[3]] = b
if(adim[2] < bdim[2]){ # ==> need to fill pixels to the right of a
out[1:adim[1], (adim[2]+1):outdim[2], 1:outdim[3]] = 1
# Or `out[...] = c(1,1,1,0)` to fill transparent, etc
}
# if adim[2] == bdim[2] ==> no need to fill anything
if(adim[2] > bdim[2]){ # ==> need to fill pixels to the right of b
out[(adim[1]+1):outdim[1], (bdim[2]+1):outdim[2], 1:outdim[3]] = 1
}
writePNG(out, "joined_figure.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment