2009-11-27 83 views
0

我已經創建了一個將文本疊加到圖像上的功能,但我正在摸索着尋找一種輸出圖像的方式,以便可以在另一個腳本中使用它或輸出到屏幕。圖像編輯功能

我可以從一個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; 

}

我想創建該圖像中,然後把它在我可以在屏幕上顯示它在所有其它輸出這樣的方式輸出。

+0

我不明白你所說的 「插回一個字符串」,你要哪個部分是什麼意思作爲一個字符串返回併爲了什麼目的? – 2009-11-27 13:08:45

+0

嗨,對不起 - 我已編輯和澄清:) – MrFidge 2009-11-27 13:17:57

回答

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> 
+0

啊完美 - 這很有道理! – MrFidge 2009-11-27 13:38:55

2

如果你不想直接輸出圖像,只是不要在你的函數中發送標題。每個瀏覽器都會將響應視爲圖像文件。

此外,返回後的imagedestroy($ im)將永遠不會執行!

如果您想創建圖像並將其保存到文件,請檢查imagepng() documentation。第二個參數接受文件名:

將文件保存到的路徑。如果不是 set或NULL,原始圖像流將直接輸出 。

根據您的編輯:

您應該imagepng使用的文件名參數創建圖像,然後從你的腳本鏈接到它。

小例如:

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

其他的方式將是通過使用一個包裝腳本到passtrough圖像/ PNG頭和直接輸出的Davide Gualanos溶液。

1

你可以使用一個臨時輸出緩衝器趕上函數的輸出,然後有一個字符串填充有它

實施例:

ob_start();

...你的圖像功能代碼...

ob_clean(); //確保輸出緩衝區中沒有其他字符串

imagepng($ im);

$ string = ob_get_contents();

ob_end_clean();

return $ string;

$ string從imagepng()獲得所有輸出;

+0

嗨 - 我已經使用過這個,但它仍然返回base64(或其他) - 一堆代碼,而不是圖像,換句話說。至少它是在正確的地方! – MrFidge 2009-11-27 13:22:54

+0

您是否嘗試過$ string = base64_decode($ string)以查看您是否擁有原始圖像? – Ass3mbler 2009-11-27 13:27:44