符号2以图像格式(png、jpg、.)显示文本


Symfony2 display text in image format (png,jpg,..)

有没有一种方法(bundle或其他方法)可以以图像格式显示(转换)文本。

from a text .txt input => output : display it on .png

您可以使用php本机函数imagestringimagettftext甚至imagik(需要激活GD php扩展),例如imagettftext(来自php帮助页面):

<?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;
  }