Created
May 28, 2025 07:54
-
-
Save EmilHvitfeldt/f774de0508a30558fc310fc11d420090 to your computer and use it in GitHub Desktop.
turn embedded pngs in svg to webps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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