Home > Net >  Method in R to crop whitespace on svg file
Method in R to crop whitespace on svg file

Time:11-04

Trying to crop the whitespace (in this case, "transparent space") around a SVG. Not really seeing a simple method to do this. Tried both knitr::plot_crop() and magick::image_trim() but to no avail. The output of both of these methods removes the alpha layer and makes it have a white background.

Example SVG for below: original (transparent)

Knitr method:

knitr::plot_crop("~/Downloads/onions-pd.svg")

produces:

after knitr

Imagemagick version:

library(magick)
img = image_read("~/Downloads/onions-pd.svg")
img = image_trim(img)
image_write(img,"~/Downloads/onions-pd.svg",format="svg")

produces:

after magick

CodePudding user response:

It sounds like you want to crop the viewBox of the svg. There are probably many ways to do this, but one is to work out the new viewBox co-ordinates and write them into the svg file.

We can get the limits of the non-transparent parts like this:

library(magick)

img <- image_read_svg("onions-pd.svg")
data   <- image_data(img) 
opaque <- which(data[4,,] != 0, arr.ind = TRUE)
limits <- paste(paste(apply(opaque, 2, min), collapse = ", "), 
                paste(apply(opaque, 2, max), collapse = ", "), sep = ", ")

limits
#> [1] "11, 64, 417, 440"

and write them into a copy of the svg file like this:

library(xml2)

onions_xml <- read_xml("onions-pd.svg")

xml_set_attr(onions_xml, attr = "viewBox", limits)

write_xml(onions_xml, "onions-cropped.svg")
  • Related