Reputation: 47
I am trying to overlay two PNG images (which are not transparent) using R. To do this, my logic is as follows: I read both images using readPNG()
. Then, I add an alpha channel using abind()
which I set to, for example, 0.5
in order to make the images semi-transparent. All of this works well so far, my problem is that when I then overlay the images using png()
the ouput image has a white margin. This always happens, even though I have set the margins to 0
using par()
. What am I missing?
Please find a minimal working example below:
library("png")
library("abind")
# Download two random pictures
pngURL1 <- "https://imgur.com/download/0ljEVEW"
pngURL2 <- "https://imgur.com/download/oShoMag"
download.file(pngURL1, "temp1.png", mode = "wb")
download.file(pngURL2, "temp2.png", mode = "wb")
# Load downloaded images and add alpha channel
img1 = readPNG("temp1.png")
img1 = abind::abind(img1, img1[,,1]) # add an alpha channel
img2 = readPNG("temp2.png")
img2 = abind::abind(img2, img2[,,1]) # add an alpha channel
# Make semi-transparent
img1[,,4] <- 0.5
img2[,,4] <- 0.5
# Create output image
png('test.png', width = 480, height = 360)
par(mar = c(0,0,0,0))
plot.new()
rasterImage(img1, 0, 0, 1, 1)
rasterImage(img2, 0, 0, 1, 1)
dev.off()
This creates the following output: Example image with unwanted margin I'd like to get rid of the margin, so that I only get a PNG image that has the exact same dimensions as the input images I used.
Thank you very much in advance for your help!
Upvotes: 3
Views: 1142
Reputation: 2588
Unwanted margins are a result of the axis range calculation. By default, axis range extends by 4% beyond data range. To solve this you can set xaxs
and yaxs
paramters in par
to i
-- internal style.
For your example it will be:
par(mar = c(0,0,0,0), xaxs="i", yaxs="i")
Upvotes: 2