将SVG转换为PNG图像

时间:2016-10-07 12:27:45

标签: php

我试图将svg转换为png图像。我使用下面的PHP代码。

$image = new Imagick();
$image->readImageBlob(file_get_contents('image.svg'));
$image->setImageFormat("png24");
$image->resizeImage(1024, 768, imagick::FILTER_LANCZOS, 1); 
$image->writeImage('image.png');

发现以下错误

Fatal error: Uncaught exception 'ImagickException' with message 'WriteBlob Failed `image.png' @ error/png.c/MagickPNGErrorHandler/1645' in /var/www/html/image.php:8 Stack trace: #0 /var/www/html/image.php(8): Imagick->writeimage('image.png') #1 {main} thrown in /var/www/html/image.php on line 8

我做错了什么?

2 个答案:

答案 0 :(得分:0)

可能的解决方案:

检查路径是否正确以及是否有' image.png'

的文件写入权限

请参阅this question

使用writeImageFile而不是writeImage

请参阅this post

答案 1 :(得分:0)

所以我问你imgs是否已经存在或你是否已经上传它们,你说它们已经存在,但是我们将继续研究你正在上传,然后转换它们的想法。

首先,就像上传图片一样:

<form action="test.php" method="post">
    <input type="file" name="img">
    <input type="submit" name="submit">
</form> 

其次,创建2个文件夹,一个用于主图像,第二个用于转换后的图像。

  • 第一个文件夹名称是“原始”
  • 第二个文件夹名称为“已转换”

现在在与html页面相同的文件夹中创建一个名为test.php的页面。

在这里,我们将拍摄原始图像并将其上传到第一个文件夹,然后将其调回并转换并将新图像存储在第二个文件夹中。

<?php

    if(isset($_POST['submit']))
    {

        $filename = $_FILES['file']['name']; // getting the name of the uploaded img 
        $file_loc = $_FILES['file']['tmp_name'];

        $folder1="original/"; 
        $folder2="converted/";

        if(move_uploaded_file($file_loc,$folder1.$filename)) // moving the uploaded or the original img to the folder 1 
            {
                rename($folder1.$filename,$folder1.$filename.".SVG"); // adding SVG ext to the file name 
                $newext =  substr($filename,0, -3);  // taking the .SVG string from the file name 
                imagepng(imagecreatefromstring(file_get_contents($folder1.$filename)),$folder2.$newext."png"); // Bring the file from folder 1 and add .png to its file name and then moving it to folder 2

            }
        else
        {
            echo "Something wrong with moving the file ";
        }
    else
    {
        echo "submit did not done ";
    }
?>
相关问题