I have a batch of SVG images that I need to resize and then save as PNG, and I'd like to use PHP to do it. Similar questions to mine have been asked but none of the solutions work for me. For example:

option A: use PHP to change the width and height attribute of the SVG.

problem with A: this seems to work fine but in fact it only increases the canvas size, not the contents of the canvas. I'm not sure if it's important but my SVGs are small graphics that were created with Illustrator, mostly made up of path elements.

option B: use imagick to resize and resave

example:

$im = new Imagick();
$im->setResolution( $startResolution * ($newWidth / $oldWidth ), $startResolution * ($newHeight / $oldHeight ) );
$im->readImage( $svgSource );
$im->setImageFormat("png32");
echo '<img src="data:image/png;base64,' . base64_encode($im) . '"  />';

problem with B: this also seems to work fine but the resulting png will be blurry

option C: variant of option B, you set the resolution really high, like 5000, then resize.

problem with C: the resulting PNG is still blurry

option D: use exec(convert...) to get around PHP's bugs

problem with D: you guessed it, the resulting PNG is still blurry

Has anyone found a way to make this work?

有帮助吗?

解决方案

For option A:

If the svg expects the coordinate system to be whatever it was when it was created (read: the original width/height), then you will need to add a viewBox attribute (use 0 0 originalwidth originalheight). Then when you set new width and height attributes the svg should rescale itself properly to the new size.

其他提示

I have achived this similar thing using 'batik' library.

I have specifed 'Area of Interest' which need to be converted to Png. here's what i have done.

    public function makeSvgtoPngImages() {
     $tempSVG_filename = $user_folder_path . 'temp.svg';                   
     $tempSVG_handle = fopen($tempSVG_filename, 'w+');
     fwrite($tempSVG_handle, $user_svg_content);
     fclose($tempSVG_handle);

        $mimetype = 'image/png';
        $width =2000;
        $height=2000;                    
        $area_interest = '472,185,555,275'; 
      // in my case i am using area of interest is my viewBox                   

        $result = shell_exec('java  -jar /var/www/batik-1.7/batik-rasterizer.jar -m ' . $mimetype . ' -d ' . $outputfile . ' -w ' . $width . ' -h ' . $height . ' -a ' . $area_interest . ' ' . $tempSVG_filename . ' 2>&1');

         unlink($tempSVG_filename);


}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top