将任何类型的图像转换为PNG并添加到PNG


Convert any type of an image to PNG and add to PNG

我正在尝试为我开发的网站创建员工海报。我的目标是从服务器上任何文件类型(.png、.gif、.jpeg等(的目录中获取图像,并将其复制到另一个生成的映像上,然后将其输出到浏览器。

问题是我使用:

$final_image = imagecreatefrompng("large_background.png");

用于制作最终图像,并且出于某种原因,如果我添加具有 jpeg、gif 等类型的个人资料图像(任何不是 JPEG 的类型(,它不起作用。图像永远不会显示在输出中。但是,如果我使用 png,它确实有效。

为了解决这个问题,我尝试将图像转换为 png,然后从中创建 png,如下面的代码所示。不幸的是,它不起作用。个人资料图片仍然没有显示在背景上。

// get image from database 
$image_from_database = could be a .png, .jpeg, .gif, etc.
// get the image from the profile images directory
$path = "profile_images/".$image_from_database;
// create a png out of the image
$image = imagecreatefrompng(imagepng($path));
// add the $image to my larger $final_image (which is a png)
imagecopy($final_image, $image, $x, $y, 0,0, $height, $width);
imagepng($final_image, $ouput_url);
...

谁能告诉我为什么这行不通?我的个人资料图像未显示在最终图像的输出中。

我的问题,

  • 这条线imagecreatefrompng(imagepng(...));可能吗?本质上,我想将任何类型的图像转换为 png,然后从中创建 png。

我只是在运行一些本地测试...以下作品:

$src = imagecreatefromgif('test.gif');
$dest = imagecreatefrompng('test.png');
imagecopy($dest, $src, 0, 0, 0, 0, 100, 100);
header('Content-Type: image/png');
imagepng($dest);
imagedestroy($src);
imagedestroy($dest);

这样做也是如此:

$src = imagecreatefromstring(file_get_contents('test.gif'));

如果您在尝试后一个示例后仍然遇到问题,请更新您的问题。除了功能代码示例之外,您正在使用的实际图像也会有所帮助。

使用imagecreatefrom*函数读取图像后,原始图像的格式无关紧要。
imagecreatefrom*函数返回图像资源。加载图像时,您使用的是图像的内部表示形式,而不是PNG,JPEG或GIF图像。
如果图像成功加载imagecopy它们应该没有问题。

此代码使用不同格式的图像,并且可以正常工作:

$img = imagecreatefrompng('bg.png');
$png_img = imagecreatefrompng('img.png');
$jpeg_img = imagecreatefromjpeg('img.jpeg');
$gif_img = imagecreatefromgif('img.gif');
/* or use this, so you don't need to figure out which imagecreatefrom* function to use
$img = imagecreatefromstring(file_get_contents('bg.png'));
$png_img = imagecreatefromstring(file_get_contents('img.png'));
$jpeg_img = imagecreatefromstring(file_get_contents('img.jpeg'));
$gif_img = imagecreatefromstring(file_get_contents('img.gif'));
*/
imagecopyresampled($img, $png_img,   10, 10, 0,0, 100, 100, 200, 200);
imagecopyresampled($img, $jpeg_img, 120, 10, 0,0, 100, 100, 200, 200);
imagecopyresampled($img, $gif_img,  230, 10, 0,0, 100, 100, 200, 200);
header('Content-Type: image/png');
imagepng($img);

您的示例

$image = imagecreatefrompng(imagepng($path));

是错误的。
imagepng用于将图像资源输出为 PNG 图像。如果提供路径作为第二个参数,则会创建 PNG 图像文件,否则会像echo一样将其打印到输出中。
imagepng实际返回的是一个布尔值,指示输出是否成功。
然后,您将该布尔值传递给需要文件路径imagecreatefrompng。这显然是错误的。

我怀疑您在加载图像时遇到问题。
imagecreatefrom*函数在失败时返回FALSE,如果您有任何问题,您应该检查。

也许您的图像路径是相对于文档根目录的,并且您的工作目录是不同的。
或者您有权限问题。
或者您的图像只是丢失了。
从你的问题中无法分辨出来。