Monday, 1 July 2019

R export raster to png without margin


I want to export a raster as a PNG image. I don't want borders, labels, legends, axis... all I want is the map covering the whole image.


The data come from here (vegetation cover) and here (administrative boundaries).


library(raster)

library(rgdal)
r <- raster('gm_lc_v3.tif')
p <- readOGR('ne_10m_admin_0_countries','ne_10m_admin_0_countries')
i <- 66 # Dominican Republic
country <- crop(r,p[i,])
png(paste(p$GEOUNIT[i],'.png',sep=''),width=country@ncols,height=country@nrows)
par(mar=c(0,0,0,0))
plot(country,maxpixels=country@ncols*country@nrows)
dev.off()


It saves the file, but adds an undesirable margin to it. I've seen people suggesting other commands, like raster::spplot or rasterVis::levelplot. I tried spplot, but still didn't work. I don't want to install a new package to do what should (in theory?) be very simple.


country@ncols = 883 and country@nrows = 574. That's the size of the final PNG. But since the margins are being added, my image is not representing the raster correctly. I want each pixel in the raster to become a pixel in the image.


That's the image I'm getting (I added a black border to make the white margin visible).


map



Answer



Well, I had to do it in the most bizarre way I found, which was creating a 3D array, and saving it to PNG:


m <- array(NA,c(nrow(country),ncol(country),3))
m[,,1] <- matrix(strtoi(paste('0x',substr(country@legend@colortable[country@data@values+1],2,3),sep=''))/255,ncol=ncol(country),nrow=nrow(country),byrow=T)
m[,,2] <- matrix(strtoi(paste('0x',substr(country@legend@colortable[country@data@values+1],4,5),sep=''))/255,ncol=ncol(country),nrow=nrow(country),byrow=T)
m[,,3] <- matrix(strtoi(paste('0x',substr(country@legend@colortable[country@data@values+1],6,7),sep=''))/255,ncol=ncol(country),nrow=nrow(country),byrow=T)

writePNG(m,paste(p$GEOUNIT[i],'.png',sep=''))

Jeffrey Evans suggested the use of writeRaster, but that can only save a TIFF, and I wanted a PNG.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...