Convert SVG image to jpg with PHP

Convert SVG image to jpg with PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Convert SVG image to jpg with PHP

Rendering a dynamic US map where state colors shift based on real-time data is a common requirement for dashboards and reporting tools. While Scalable Vector Graphics (SVG) offer an excellent canvas for this because you can manipulate individual paths via CSS or JavaScript, Internet Explorer has historically lacked native SVG support. To maintain cross-browser compatibility without relying on polyfills like smil.js or complex fallback strategies, converting the SVG to a raster format like JPG is a pragmatic solution.

This conversion process typically happens on the server side using PHP and Apache. The two primary libraries available for this task are GD2 and ImageMagick. Both can handle the conversion, but they operate very differently regarding how they interpret the source image and how you control the output quality.

Using the GD Library

The built-in GD library is often the first choice because it requires no external dependencies beyond the standard PHP installation. However, converting an SVG with GD comes with a specific limitation: GD treats the SVG as a single bitmap image rather than a vector document.

To perform the conversion, you need to pass the SVG string or file path into imagecreatefromstring() or imagecreatefromsvg(). The critical detail here is that GD will rasterize the entire image at once. You cannot selectively change the color of just one state within the JPG output because, once converted to a JPG, the vector paths are gone; you are left with a flat grid of pixels.

<?php
// Load the SVG content from a file or string
$svgContent = file_get_contents('us_map.svg');

// Convert SVG to an image resource
$imageResource = imagecreatefromstring($svgContent);

if ($imageResource) {
    // Define your output dimensions and quality (0.9 is high quality for JPG)
    $width = 800;
    $height = 600;
    $quality = 0.9;
    
    // Create a new JPG resource with specific dimensions if needed, 
    // or use the original size from GD if it preserved aspect ratio correctly
    $destImage = imagecreatetruecolor($width, $height);
    
    // Copy pixels from the SVG source to the new JPG destination
    imagecopyresampled(
        $destImage, 
        $imageResource, 
        0, 0, 0, 0, 
        $width, $height, 
        imagesx($imageResource), imagesy($imageResource)
    );
    
    // Output the result as a JPG
    imagejpeg($destImage, 'output_map.jpg', $quality);
    
    // Free memory
    imagedestroy($destImage);
    imagedestroy($imageResource);
}
?>

The trade-off here is significant. While GD is lightweight, it offers zero control over the vector properties after conversion. If your application logic requires updating a specific state's color after rasterization, you would have to use a pixel manipulation loop (e.g., imagecolorat and imagesetpixel) to scan the entire image for a specific region. This is computationally expensive and prone to errors regarding exact coordinate mapping, especially if the SVG was not rendered at 1:1 pixel density.

Leveraging ImageMagick

If your requirement includes dynamically changing colors on the fly after conversion, ImageMagick is generally the superior tool. Unlike GD, which flattens everything immediately, ImageMagick can parse SVGs while retaining a degree of vector awareness or allow for more sophisticated compositing operations before rasterization.

You can invoke ImageMagick from PHP using the system command line interface. This approach allows you to construct complex filter chains. For instance, you might want to render the map with default colors first, then apply a specific color overlay to a state identified by its ID or coordinate range before saving the final JPG.

# Example command structure for ImageMagick
convert input.svg -resize 800x600 output.jpg

In a PHP context, you would execute this via exec() or shell_exec(), capturing the output or writing directly to a file path. This method ensures that the conversion respects the aspect ratio and resolution settings defined in your SVG's <style> or viewbox attributes more faithfully than GD's basic resampling.

Choosing the Right Approach for Dynamic Maps

The decision between these two libraries often comes down to post-conversion manipulation. If your workflow is strictly "load data -> generate map -> serve static JPG," GD is perfectly adequate and avoids the overhead of installing ImageMagick binaries on every server. However, if you need to inject dynamic color changes into specific states after the conversion step, the flat nature of a GD-generated JPG makes that task extremely difficult without complex pixel manipulation scripts.

With ImageMagick, you can chain operations. You could theoretically convert the SVG to a temporary PNG (preserving transparency and paths if possible) or render it directly to JPG while applying filters. This flexibility is crucial for interactive dashboards where the visual state of the map changes frequently based on user interactions or live data streams.

Ultimately, both solutions run natively on Apache with PHP, ensuring broad compatibility. The choice depends on whether your "dynamic" requirement involves changing colors after the fact (favoring ImageMagick) or simply rendering a static representation that matches current database values at the time of request (where GD suffices).

Our network