Convert SVG image to PNG with PHP

后端 未结 8 2193
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 14:46

I\'m working on a web project that involves a dynamically generated map of the US coloring different states based on a set of data.

This SVG file gives me a good b

8条回答
  •  再見小時候
    2020-11-22 15:34

    This is a method for converting a svg picture to a gif using standard php GD tools

    1) You put the image into a canvas element in the browser:

    
    
        
    

    And then convert it at the server (ProcessPicture.php) from (default) png to gif and save it. (you could have saved as png too then use imagepng instead of image gif):

    //receive the posted data in php
    $pic=$_POST['image'];
    $Key=$_POST['TheKey'];
    $height=$_POST['h'];
    $width=$_POST['w'];
    $dir='../gif/'
    $gifName=$dir.$Key.'.gif';
     $pngName=$dir.$Key.'.png';
    
    //split the generated base64 string before the comma. to remove the 'data:image/png;base64, header  created by and get the image data
    $data = explode(',', $pic);
    $base64img = base64_decode($data[1]);
    $dimg=imagecreatefromstring($base64img); 
    
    //in order to avoid copying a black figure into a (default) black background you must create a white background
    
    $im_out = ImageCreateTrueColor($width,$height);
    $bgfill = imagecolorallocate( $im_out, 255, 255, 255 );
    imagefill( $im_out, 0,0, $bgfill );
    
    //Copy the uploaded picture in on the white background
    ImageCopyResampled($im_out, $dimg ,0, 0, 0, 0, $width, $height,$width, $height);
    
    //Make the gif and png file 
    imagegif($im_out, $gifName);
    imagepng($im_out, $pngName);
    

提交回复
热议问题