1
有沒有一種方法(捆綁或其他)來顯示(轉換)圖像格式的文本。Symfony2以圖像格式顯示文本(PNG,JPG,..)
from a text .txt input => output : display it on .png
有沒有一種方法(捆綁或其他)來顯示(轉換)圖像格式的文本。Symfony2以圖像格式顯示文本(PNG,JPG,..)
from a text .txt input => output : display it on .png
你可以使用PHP自身的功能imagestring
,imagettftext
甚至imagik
(要求有GD PHP擴展激活),例如用imagettftext
(從the php help page):
<?php
// Set the content-type
header('Content-type: image/png');
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw
$text = 'Testing...';
// 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);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
首先創建一個路由一個特定的控制器然後在該控制器內添加以下代碼
/**
* Action returns an image which is generated from
* given request text input
* @param type $text
* @return \Symfony\Component\HttpFoundation\Response
*/
public function textToImageAction($text) {
$filename = $this->saveTextAsImage($text);
$response = new Response();
// Set headers
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', mime_content_type($filename));
$response->headers->set('Content-Disposition', 'attachment; filename="' . basename($filename) . '";');
$response->headers->set('Content-length', filesize($filename));
// Send headers before outputting anything
$response->sendHeaders();
$response->setContent(readfile($filename));
return $response;
}
/**
* Method convert given text to PNG image and returs
* file name
* @param type $text Text
* @return string File Name
*/
public function saveTextAsImage($text) {
// Create the image
$imageCreator = imagecreatetruecolor(100, 30);
// Create some colors
$white = imagecolorallocate($imageCreator, 255, 255, 255);
$grey = imagecolorallocate($imageCreator, 128, 128, 128);
$black = imagecolorallocate($imageCreator, 0, 0, 0);
imagefilledrectangle($imageCreator, 0, 0, 399, 29, $white);
$font = 'arial.ttf';
// Add some shadow to the text
imagettftext($imageCreator, 20, 0, 11, 21, $grey, $font, $text);
// Add the text
imagettftext($imageCreator, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
$file_name = "upload/text_image.png";
imagepng($imageCreator, $file_name);
imagedestroy($imageCreator);
return $file_name;
}
爲什麼你不只是前在擴展文件上執行str_replace? – Macbernie 2014-10-22 09:58:25
我搜索一個包來做到這一點.. – Mirlo 2014-10-22 10:10:32
與symfony2無關 – DarkBee 2014-10-22 10:55:36