Convert svg to png php

Convert SVG image to PNG with PHP

That’s funny you asked this, I just did this recently for my work’s site and I was thinking I should write a tutorial. Here is how to do it with PHP/Imagick, which uses ImageMagick:

$usmap = '/path/to/blank/us-map.svg'; $im = new Imagick(); $svg = file_get_contents($usmap); /*loop to color each state as needed, something like*/ $idColorArray = array( "AL" => "339966" ,"AK" => "0099FF" . ,"WI" => "FF4B00" ,"WY" => "A3609B" ); foreach($idColorArray as $state => $color)< //Where $color is a RRGGBB hex value $svg = preg_replace( '/id="'.$state.'" style="fill:#([0-9a-f])/' , 'id="'.$state.'" style="fill:#'.$color , $svg ); > $im->readImageBlob($svg); /*png settings*/ $im->setImageFormat("png24"); $im->resizeImage(720, 445, imagick::FILTER_LANCZOS, 1); /*Optional, if you need to resize*/ /*jpeg*/ $im->setImageFormat("jpeg"); $im->adaptiveResizeImage(720, 445); /*Optional, if you need to resize*/ $im->writeImage('/path/to/colored/us-map.png');/*(or .jpg)*/ $im->clear(); $im->destroy(); 

the steps regex color replacement may vary depending on the svg path xml and how you id & color values are stored. If you don’t want to store a file on the server, you can output the image as base 64 like

(before you use clear/destroy) but ie has issues with PNG as base64 so you’d probably have to output base64 as jpeg

you can see an example here I did for a former employer’s sales territory map:

enter image description here

Finish:

Since writing the above, I’ve come up with 2 improved techniques:

1) instead of a regex loop to change the fill on state , use CSS to make style rules like

and then you can do a single text replace to inject your css rules into the svg before proceeding with the imagick jpeg/png creation. If the colors don’t change, check to make sure you don’t have any inline fill styles in your path tags overriding the css.

2) If you don’t have to actually create a jpeg/png image file (and don’t need to support outdated browsers), you can manipulate the svg directly with jQuery. You can’t access the svg paths when embedding the svg using img or object tags, so you’ll have to directly include the svg xml in your webpage html like:

then changing the colors is as easy as:

  

Read More

You can use Raphaël—JavaScript Library and achieve it easily. It will work in IE also.

$command = 'convert -density 300 '; if(Input::Post('height')!='' && Input::Post('width')!='') < $command.='-resize '.Input::Post('width').'x'.Input::Post('height').' '; >$command.=$svg.' '.$source; exec($command); @unlink($svg); 

Similar Question and Answer

I would like to share my answer too it might help someone.

This it is more for simple case when you svg dose not contain fill style and by default black and you want to convert it to png and add color to result png.

function convertSvgToPng($svgPath, $fillColor, $outPath) < $im = new Imagick(); $svg = file_get_contents($svgPath); // . THIS is the trick part - just appending to all readImageBlob($svg); $im->setImageFormat("png24"); $im->writeImage($outPath); $im->clear(); $im->destroy(); > 

Armen 3968

Читайте также:  Python отступы между функциями

I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I’m not sure such a library exists — I don’t know any.

ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it’s still the most promising way to go, it’s the first thing I would look into if I were you.

Pekka 434029

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); 

This is v. easy, have been doing work on this for the past few weeks.

You need the Batik SVG Toolkit. Download, and place the files in the same directory as the SVG you want to convert to a JPEG, also make sure you unzip it first.

Open the terminal, and run this command:

java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 NAME_OF_SVG_FILE.svg 

That should output a JPEG of the SVG file. Really easy. You can even just place it in a loop and convert loads of SVGs,

import os svgs = ('test1.svg', 'test2.svg', 'etc.svg') for svg in svgs: os.system('java -jar batik-rasterizer.jar -m image/jpeg -q 0.8 '+str(svg)+'.svg') 

You mention that you are doing this because IE doesn’t support SVG.

The good news is that IE does support vector graphics. Okay, so it’s in the form of a language called VML which only IE supports, rather than SVG, but it is there, and you can use it.

Читайте также:  Http fs jalauto ru 8080 index php

Google Maps, among others, will detect the browser capabilities to determine whether to serve SVG or VML.

Then there’s the Raphael library, which is a Javascript browswer-based graphics library, which supports either SVG or VML, again depending on the browser.

Another one which may help: SVGWeb.

All of which means that you can support your IE users without having to resort to bitmap graphics.

See also the top answer to this question, for example: XSL Transform SVG to VML

When converting SVG to transparent PNG, don’t forget to put this BEFORE $imagick->readImageBlob() :

$imagick->setBackgroundColor(new ImagickPixel('transparent')); 

More Answer

  • Image not being saved with PHP script
  • JSON to PHP sending/ receiving variables with image data
  • Convert each row in a txt file into JSON with PHP
  • Display PNG image in php webpage from API result
  • PHP displaying JPG image from PNG source on server?
  • PHP PNG Image Upload losing transparency
  • php to convert CSV to JSON with nested objects
  • Image generated with PHP GD -How to align to the center of browser?
  • Save image from one format to another with php gd2
  • PHP Imagick breaks SVG on conversion to PNG
  • How to convert iso date time with milliseconds to date time format in php so that milliseconds don’t go away?
  • Just Grab image URL on json with php
  • Image Upload doesn’t work with swift alamofire and php
  • Extract image URLs from Instagram media feed with JSON and PHP
  • Convert a date into a date with day of the week php native
  • can’t get image using php CURL with SSL
  • Replace a color with another color in an image with PHP
  • Consistent PNG Bit output with PHP Imagick
  • convert image 64X64 px after decoding base64 image in php
  • html textearea with multiple lines. Want to convert to php array, each line is one element of array
  • Php convert seconds to readable format with only required values
  • png image copied to another image php
  • Convert RBG to CMYK with use of ICC profile in PHP
  • PHP regex for image name with numbers
  • embedded image in svg disappear on converting svg to png
  • Image cropping with PHP (GD)
  • PHP Image resize with all types
  • PHP Random Array with Text, Image and Image Alt attribute
  • Unable to get correct image when converting SVG to PNG using Imagick
  • Output a PNG image from a PHP include file
  • PHP display png image from binary file
  • Crop Image with jWindowCrop — PHP
  • Convert html with image to ms.word
  • PHP image resize with GD
  • how to re size a image with php before showing it to the browser?
  • how to crop svg image with imagick in php?
Читайте также:  Как сбросить кэш css

More answer with same ag

  • How can I conditionally replace tokens in a config file with Capistrano or Phing?
  • Check Current URL + filename for a Letters/Numbers
  • Editing PHAR files
  • Loop over past dates and remove in php
  • trouble with non-latin characters
  • how to replace result urls using regex php
  • filter_input( INPUT_SERVER, ‘REQUEST_URI’ ) returning NULL
  • How to get multiple option of select box array in form
  • PSR-12 and assigning same value to multiple variables
  • Paypal is not letting me to login
  • Passing a value to ajax with anchor.
  • Problems adding cURL to OAuth request engine support
  • magento programatically update sort_order on option dropdown labels
  • Validating fields based on label class
  • $_SERVER[‘http_referer’] vs .htaccess deny all allow 1
  • Multi-dimensional Array — mysql_fetch_assoc to Json
  • PHP object _construct function
  • How to fix Authentication required error 401 when using curl with http authentication
  • Add an entity to a doctrine PersistentCollection on a ManytoMany without causing Duplicate Entry Integrity Constraint violations
  • issues with sending php variable to another page
  • Putting a comma and space in a mixed HTML/PHP variable
  • line breaks inside of a textarea
  • php code to extract all text links not image link
  • Inject second array randomly inside the first
  • time() with clearTime — just today at 12:00 AM
  • Performance: Using try (statement) and catch (output error) instead of checking if email already exist
  • how to retrieve all product from the db using an id’s list?
  • Apache 2.4 mod_rewrite and RewriteCond % empty
  • PHP rename Permission denied (WAMP)
  • PHP / HTML textarea string regexp (regular expression)
  • Sorting arrays: second last
  • How do I make a progress bar get the value of a text-type input?
  • Interpreting multiples of the same form elements through PHP in a concise way?
  • How should I go about exporting MYSQL data into Excel using PHP Excel
  • Sending Stock Update Email Magento
  • PHP: Throw exception with multiple original/previous exceptions?
  • open_basedir error, but path is in open_basedir. PHP
  • Session already started error in PHP
  • Maintain all values of duplicate keys when parsing .ini file
  • Alexa api in php
  • Kohana 3: Auth module
  • php looping through stdClass objects and arrays
  • xDebug installation issue on Mac
  • How to add a while loop to a variable to display and if — else if result?
  • how to do negative filtering on jquery plugin data tables?
  • .htaccess — after redirect from non-www to www, removed .php file extension appears
  • CSS Break Long Text with «. «
  • Using $.Ajax to GET, Update & PUT JSON back on the server when button clicked
  • PHP / jQuery / AJAX form update best practices
  • How to remove this error in FPDF?

Источник

Оцените статью