如何在PHP中使用imagecreatefrompng()函数从PNG文件或URL创建一个新图像?


在PHP中,imagecreatefrompng()是一个内置函数,用于从PNG文件或URL创建一个新图像。imagecreatefrompng()返回一个图像标识符,代表从给定文件名获得的图像。

语法

resource imagecreatefrompng(string $filename)

参数

imagecreatefrompng()只接受一个参数,$filename。此参数包含图像名称或PNG图像的路径。

返回值

imagecreatefrompng() 函数成功时返回图像资源标识符,失败时返回错误。

示例1 - 在浏览器中显示加载的PNG图像

<?php
   // Load an image from local drive/file
   $img = imagecreatefrompng('C:\xampp\htdocs\Images\img29.png');
   // It will show the loaded PNG image in the browser
   header('Content-type: image/png');
   imagejpeg($img);
   imagedestroy($img);
?>

输出

示例2 - 加载并将PNG图像保存到本地驱动器路径

<?php
   // Load an image from local drive/file
   $img = imagecreatefrompng('C:\xampp\htdocs\Images\img29.png');

   // Flip the image
   // imageflip($img,1);

   // Save the GIF image into the given local drive folder path.
   imagejpeg($img,'C:\xampp\htdocs\pic.gif');
   imagedestroy($img);
?>

输出

说明 - 在示例2中,使用imagecreatefrompng()函数从本地路径加载png图像。然后,我们将png图像转换为gif图像,并通过提供保存gif图像的路径将其保存到本地驱动器。

我们也可以在浏览器中查看图像(参见示例1)。

更新于:2021年8月9日

2K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.