Hello,
Is there a package that allows me to convert SVG file to PNG file?
Best,
Hello,
Is there a package that allows me to convert SVG file to PNG file?
Best,
I recently needed a version with fixed pixel size, which you can find here
I put together a slightly more polished version of the example in the readme of the linked package, this time as a function:
using Rsvg
using Cairo
"""
svg2png(filename_in, overwrite=false, dpi::Real=300)
Load an SVG file `filename_in`, use Rsvg.jl to render the image
for cairo, then use Cairo.jl to write that image to a PNG file.
"""
function svg2png(filename_in, overwrite=false, dpi::Real=300)
if !isfile(filename_in)
error("The given filename $filename_in returned `false` when passed to `isfile`. Are you sure that the file exists?")
end
filename_in_noext, input_extension = splitext(filename_in)
if input_extension != ".svg"
error("Extension of given filename $filename_in is $filename_in_ext, where \".svg\" was expected. Aborting.")
end
filename_out = filename_in_noext * ".png"
if isfile(filename_out) && !overwrite
error("Output file $filename_out already exists, and the second positional argument `overwrite` is set to false. Aborting.")
end
r = Rsvg.handle_new_from_file(filename_in)
Rsvg.handle_set_dpi(r, float(dpi)) # Conversion to float due to unnecessary contraints on arguments to Rsvg.handle_set_dpi
d = Rsvg.handle_get_dimensions(r)
cs = Cairo.CairoImageSurface(d.width,d.height,Cairo.FORMAT_ARGB32)
c = Cairo.CairoContext(cs)
Rsvg.handle_render_cairo(c,r)
Cairo.write_to_png(cs,filename_out)
return nothing
end
I then also made this function to convert any svg file in a given directory:
function convert_all_svgs(dir, overwrite=false, dpi::Real=300)
if !isdir(dir)
error("The given directory $dir returned false when passed to `isdir`. Are you sure the directory exists?")
end
map(readdir(dir, join=true)) do filename
if splitext(filename)[2]==".svg"
svg2png(filename, overwrite, dpi)
end
end
end