图像编辑功能

时间:2009-11-27 13:06:28

标签: php function image-manipulation

我已经创建了一个将文本叠加到图像上的功能,但是我正在摸索着找到一种输出图像的方式,可以在另一个脚本中使用它或输出到屏幕上。

我可以从php脚本中调用此函数,传递图像和要使用的文本,但是当函数返回数据时 - 由于标题而接管页面 - 我得到的所有输出都是图像。

我怀疑这是一个简单的问题,只是在我的PHP知识中显示了一个漏洞 - 有人能让我直接在这里吗?

谢谢!

function makeimage($ file,$ text){     ob_start();         $ x = getimagesize($ file);         $ width = $ x [0];         $ height = $ x [1];         $ type = $ x [2];

    //header('Content-type: $type');

    if ($type == 1) {
        $im = imagecreatefromgif($file);
    } elseif ($type==2) {
        $im = imagecreatefromjpeg($file);
    } elseif ($type==3) {
        $im = imagecreatefrompng($file);
    }

    // Create some colors
    $white = imagecolorallocate($im, 255, 255, 255);
    $grey = imagecolorallocate($im, 128, 128, 128);
    $black = imagecolorallocate($im, 0, 0, 0);

    // Replace path by your own font path
    $font = 'arial.ttf';

    // Add some shadow to the text
    imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

    // Add the text
    imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

ob_clean(); //to be sure there are no other strings in the output buffer
imagepng($im);
$string = ob_get_contents();
ob_end_clean();
return $string;

}

我想创建这个图像,然后以这样的方式输出它,我可以在屏幕上显示所有其他输出。

3 个答案:

答案 0 :(得分:2)

如果您不想直接输出图像,请不要在功能中发送标题。每个浏览器都会将响应视为图像文件。

此外,返回后的imagedestroy($ im)永远不会被执行!

如果您只想创建图像并将其保存到文件,请检查imagepng() documentation。第二个参数接受文件名:

  

将文件保存到的路径。如果不   设置或NULL,原始图像流将   直接输出。

根据你的编辑:

你应该使用带有filename参数的imagepng来创建图像,然后从你的脚本链接到它。

小例子:

<?php
// ...
imagepng($im, 'foo.png');
?>
<img src="foo.png" />

另一种方法是通过使用包装器脚本传递图像/ png标头和直接输出来实现Davide Gualanos解决方案。

答案 1 :(得分:1)

你可以使用一个临时输出缓冲区来捕获函数的输出,然后用一个字符串填充它

示例:

ob_start();

...你的图像功能代码......

ob_clean(); //确保输出缓冲区中没有其他字符串

imagepng($ IM);

$ string = ob_get_contents();

ob_end_clean();

返回$ string;

$ string从imagepng();

获得所有输出

答案 2 :(得分:1)

您必须将输出图像的脚本放在页面中,然后在html标记中调用该页面以显示它。

例:
image.php

<php
$image = $_GET['image'];
$text = $_GET['text'];
makeimage($image, $text);
?>

page.html中:

<html>
<body>
<img src="image.php?image=foo.jpg&text=hello" />
</body>
</html>
相关问题