Convert SVG to transparent PNG with antialiasing, using ImageMagick

后端 未结 8 883
耶瑟儿~
耶瑟儿~ 2020-12-07 13:06

I want to convert SVG images to PNG files with transparent background and anti-aliased edges (using semi-transparent pixels). Unfortunately I can\'t get ImageMagick to do th

相关标签:
8条回答
  • 2020-12-07 14:01

    I add a rect as background. The embed CSS hide the background. Then I catch its color for setting the transparent attribute of ImageMagick.


    SVG file:

    <?xml version="1.0" ?>
    <!DOCTYPE svg  PUBLIC '-//W3C//DTD SVG 1.1//EN'  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>
    <svg 
        version="1.1" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
        width="500px" height="500px"
        viewBox="0 0 500 500" 
        enable-background="new 0 0 500 500" 
        >
    <defs>
        <style>
            #background { display: none; }
        </style>
    </defs>
    <rect id="background" x="0" y="0" width="500" height="500" fill="#e8e437"/>
    <!-- beginning of the sketch -->
    <g fill="#000" text-anchor="middle"font-size="112">
        <text y="350" x="192">OK</text>
    </g>
    <!-- end of the sketch -->
    </svg>
    

    bash script

    #!/bin/bash
    
    
    BASE_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )
    SVG_DIR="$BASE_DIR/import"
    PNG_DIR="$BASE_DIR/export"
    
    for f in `ls $SVG_DIR/*.svg`
    do
        g="$PNG_DIR/$(basename "$f" .svg).png"
        BGCOLOR=`grep 'id="background"' $f \
            | sed 's/.* fill="\([^"]*\)".*/\1/'`
    
        convert $f -transparent "$BGCOLOR" $g
    done
    
    0 讨论(0)
  • 2020-12-07 14:02

    The way I learned how to do this was from the methodology found here: How to convert a .eps file to a high quality 1024x1024 .jpg?

    It is the same idea as @halfer's solution with inkscape--to jack up the DPI first--but you can accomplish the same thing in just imagemagick using the -density option.

    convert -density 200 in.svg -resize 25x25 -transparent white out.png
    
    0 讨论(0)
提交回复
热议问题