Skip to content

Instantly share code, notes, and snippets.

@EmilHvitfeldt
Created May 28, 2025 07:54
Show Gist options
  • Save EmilHvitfeldt/f774de0508a30558fc310fc11d420090 to your computer and use it in GitHub Desktop.
Save EmilHvitfeldt/f774de0508a30558fc310fc11d420090 to your computer and use it in GitHub Desktop.
turn embedded pngs in svg to webps
library(tidyverse)
library(base64enc)
library(webp)
library(png)
compress_svg <- function(file) {
text <- read_lines(file) |>
paste(collapse = "\n")
# Remove mask
text <- text |>
stringr::str_remove_all("\\s*<mask.*>[\\s\\S]*?</mask>")
# remove mask atribute in <g>
text <- text |>
stringr::str_remove_all(" mask=\"url\\(#\\w*\\)\"")
# turn embedded pngs to webp
base64_png_to_webp <- function(image) {
tmp_png <- tempfile()
tmp_webp <- tempfile()
tmp_base64 <- tempfile()
writeLines(image, tmp_base64)
base64decode(file = tmp_base64, output = tmp_png)
write_webp(readPNG(tmp_png), tmp_webp)
base64encode(tmp_webp)
}
text <- stringr::str_replace_all(text, "(?<=, )(.*?)(?=\")", base64_png_to_webp)
text <- stringr::str_replace_all(text, "png;base64", "webp;base64")
write_lines(text, file)
}
fs::dir_map("assets/", compress_svg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment