Symfony2以图像格式显示文本(png,jpg,..)

时间:2014-10-22 09:47:43

标签: php gdlib

是否有一种方法(捆绑或其他东西)以图像格式显示(转换)文本。

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

2 个答案:

答案 0 :(得分:2)

您可以使用php本机函数imagestringimagettftext甚至imagik(要求您激活GD php扩展名),例如imagettftext(来自{{3 }}):

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

答案 1 :(得分:1)

首先为特定Controller创建路由,然后在该控制器中添加以下代码

/**
   * 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;
  }