(009)PHP 技巧 * SVG 保存爲圖片(分享圖生成)

一、準備

  1. 準備 svg 文件:這一步驟通常由設計完成,而案例是通過 SVG 在線編輯器 生成的;
  2. 確保你的環境支持使用 Imagick 擴展;
  3. 如果是Linux服務器,可能需要安裝必要字體,否則中文可能無法正常顯示;

二、過程:

test.svg

<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
 <!-- Created with Method Draw - http://github.com/duopixel/Method-Draw/ -->
 <g>
  <title>background</title>
  <rect fill="#fff" id="canvas_background" height="302" width="502" y="-1" x="-1"/>
  <g display="none" overflow="visible" y="0" x="0" height="100%" width="100%" id="canvasGrid">
   <rect fill="url(#gridpattern)" stroke-width="0" y="0" x="0" height="100%" width="100%"/>
  </g>
 </g>
 <g>
  <title>Layer 1</title>
  <text stroke="#000" transform="matrix(1.2316112832302093,0,0,1.6103224566703835,-34.94758717722778,-66.61220433762628) " xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_1" y="119.89815" x="101.417837" stroke-width="0" fill="#000000">ATONG</text>
  <rect id="svg_2" height="4" width="414" y="139.8375" x="85.25" stroke-width="1.5" stroke="#000" fill="#000000"/>
  <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_3" y="179.8375" x="124.5" stroke-width="0" stroke="#000" fill="#000000">Tel: 8888-8888-8888</text>
  <text xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_4" y="209.8375" x="98.5" stroke-width="0" stroke="#000" fill="#000000">email: [email protected]</text>
  <rect stroke="#000" id="svg_5" height="31.999999" width="33.999999" y="0.75" x="0.75" stroke-width="1.5" fill="#000000"/>
  <rect id="svg_6" height="26" width="26" y="37.8375" x="16.5" fill-opacity="null" stroke-opacity="null" stroke-width="1.5" stroke="#000" fill="#000000"/>
  <rect id="svg_7" height="24" width="25" y="11.8375" x="42.5" fill-opacity="null" stroke-opacity="null" stroke-width="1.5" stroke="#000" fill="#000000"/>
  <rect id="svg_8" height="12" width="12" y="42.8375" x="50.5" fill-opacity="null" stroke-opacity="null" stroke-width="1.5" stroke="#000" fill="#000000"/>
  <text stroke="#000" transform="matrix(0.7079451420430161,0,0,0.43161633610725403,65.21588988354182,166.3232696466148) " xml:space="preserve" text-anchor="start" font-family="Helvetica, Arial, sans-serif" font-size="24" id="svg_9" y="299.75941" x="163.544496" fill-opacity="null" stroke-opacity="null" stroke-width="0" fill="#000000">https://wp.kder.top</text>
 </g>
</svg>

 test.php:

<?php

$svg = file_get_contents("./test.svg");
// todo:: 替換svg的內容
// $svg = str_replace("ATONG","YOUR NAME",$svg);

$im = new \Imagick();

$im->readImageBlob($svg);
$im->setImageFormat("jpeg");
$im->writeImage('./test.jpg');

$im->clear();
$im->destroy();

echo "<img src='./test.jpg'>";

三、結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章