png转svg生成svg+xml

淳于飞鸾
2023-12-01

将png图片转测svg+xml

data:image/svg+xml,<svg viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg"><path d="M5.99017859,36 L34.0098214,36 C35.1085737,36 36,35.1062037 36,34.0000567 L36,29 C36,26.7520887 28.9203674,24 20,24 C11.0796326,24 4,26.7520887 4,29 L4,34.0000567 C4,35.1005941 4.89584612,36 5.99017859,36 Z M5.99017859,38 C3.7864638,38 2,36.2003465 2,34.0000567 L2,29 C2,25.13 10.059,22 20,22 C29.941,22 38,25.13 38,29 L38,34.0000567 C38,36.2091644 36.2147544,38 34.0098214,38 L5.99017859,38 Z M20,18 C23.8659932,18 27,14.8659932 27,11 C27,7.13400675 23.8659932,4 20,4 C16.1340068,4 13,7.13400675 13,11 C13,14.8659932 16.1340068,18 20,18 Z M11,11 C11,6.02943725 15.0294373,2 20,2 C24.9705627,2 29,6.02943725 29,11 C29,15.9705627 24.9705627,20 20,20 C15.0294373,20 11,15.9705627 11,11 Z" fill="%23E93B3D"></path></svg>

使用如下mixin引入,用sass编译即可

//  Function to create an optimized svg url
//  Version: 1.0.0
@function svg-url($svg){
    //
    //  Add missing namespace
    //
    @if not str-index($svg,xmlns) {
        $svg: str-replace($svg, '<svg','<svg xmlns="http://www.w3.org/2000/svg"');
    }
    //
    //  Chunk up string in order to avoid
    //  "stack level too deep" error
    //
    $encoded:'';
    $slice: 2000;
    $index: 0;
    $loops: ceil(str-length($svg)/$slice);
    @for $i from 1 through $loops {
        $chunk: str-slice($svg, $index, $index + $slice - 1);
        //
        //   Encode
        //
        $chunk: str-replace($chunk, '%', '%25');
        $chunk: str-replace($chunk, '"', '%22');
        $chunk: str-replace($chunk, "'", '%27');
        $chunk: str-replace($chunk, '&', '%26');
        $chunk: str-replace($chunk, '#', '%23');
        $chunk: str-replace($chunk, '{', '%7B');
        $chunk: str-replace($chunk, '}', '%7D');
        $chunk: str-replace($chunk, '<', '%3C');
        $chunk: str-replace($chunk, '>', '%3E');

        $encoded: #{$encoded}#{$chunk};
        $index: $index + $slice;
    }
    @return url("data:image/svg+xml,#{$encoded}");
}

//  Background svg mixin
@mixin background-svg($svg){
    background-image: svg-url($svg);
}

@mixin background-mask($svg){
    -webkit-mask: svg-url($svg);
}


//  Helper function to replace characters in a string
@function str-replace($string, $search, $replace: '') {
    $index: str-index($string, $search);
    @return if($index,
        str-slice($string, 1, $index - 1) + $replace +
        str-replace(str-slice($string, $index +
        str-length($search)), $search, $replace),
        $string);
}

 

 类似资料: