String to png php

Convert Text to Image in PHP

In many cases, we need to create a dynamic image on the fly and write text on the image in our web application. If you have a requirement like this, don’t worry we’ll provide a simple PHP script to convert text to image and save it as PNG or JPG format.

In this tutorial, we are going to show you the easiest way to create an image from text using PHP. To control the text to image creation process, a PHP class will be created. By using this PHP class you can easily create an image and add multiple line text string to the image.

GD library will be used to create and manipulate image file in our PHP script. So before you get started, make sure PHP GD is installed on your server.

Are you want to get the step-by-step guide to installing PHP GD library on the server? Go through the following tutorial links.

TextToImage Class

The TextToImage PHP class helps to generate an image and add text to image. TextToImage class contains 4 functions and the functions will do following.

  • createImage() – Creates image from text. The text string needs to be provided that want to write on the image. Also, you can specify the text font size, image width, and image height.
  • showImage() – Returns an image that created by the createImage() function.
  • saveAsPng() – Save image file as .png format. You can specify the filename and the location to save the image.
  • saveAsJpg() – Save image file as .jpg format. You can specify the filename and the location to save the image.
/** 
* TextToImage class
* This class converts text to image
*
* @author CodexWorld Dev Team
* @link http://www.codexworld.com
* @license http://www.codexworld.com/license/
*/
class TextToImage private $img;

/**
* Create image from text
* @param string text to convert into image
* @param int font size of text
* @param int width of the image
* @param int height of the image
*/
function createImage($text, $fontSize = 20, $imgWidth = 400, $imgHeight = 80)
//text font path
$font = 'fonts/the_unseen.ttf';

//create the image
$this->img = imagecreatetruecolor($imgWidth, $imgHeight);

//create some colors
$white = imagecolorallocate($this->img, 255, 255, 255);
$grey = imagecolorallocate($this->img, 128, 128, 128);
$black = imagecolorallocate($this->img, 0, 0, 0);
imagefilledrectangle($this->img, 0, 0, $imgWidth - 1, $imgHeight - 1, $white);

//break lines
$splitText = explode ( "\\n" , $text );
$lines = count($splitText);

foreach(
$splitText as $txt) $textBox = imagettfbbox($fontSize,$angle,$font,$txt);
$textWidth = abs(max($textBox[2], $textBox[4]));
$textHeight = abs(max($textBox[5], $textBox[7]));
$x = (imagesx($this->img) - $textWidth)/2;
$y = ((imagesy($this->img) + $textHeight)/2)-($lines-2)*$textHeight;
$lines = $lines-1;

//add some shadow to the text
imagettftext($this->img, $fontSize, $angle, $x, $y, $grey, $font, $txt);

//add the text
imagettftext($this->img, $fontSize, $angle, $x, $y, $black, $font, $txt);
> return true;
>

/**
* Display image
*/
function showImage() header('Content-Type: image/png');
return
imagepng($this->img);
>

/**
* Save image as png format
* @param string file name to save
* @param string location to save image file
*/
function saveAsPng($fileName = 'text-image', $location = '') $fileName = $fileName.".png";
$fileName = !empty($location)?$location.$fileName:$fileName;
return
imagepng($this->img, $fileName);
>

/**
* Save image as jpg format
* @param string file name to save
* @param string location to save image file
*/
function saveAsJpg($fileName = 'text-image', $location = '') $fileName = $fileName.".jpg";
$fileName = !empty($location)?$location.$fileName:$fileName;
return
imagejpeg($this->img, $fileName);
>
>

Convert Text String to Image in PHP

Include TextToImage.php file (TextToImage class) and create an object. Call the createImage() function and provide the text string. If you want to add multiple lines to the image, add “\n” before the new line.

//include TextToImage class
require_once 'TextToImage.php';

//create img object
$img = new TextToImage;

//create image from text
$text = 'Welcome to CodexWorld.\nThe World of Programming.';
$img->createImage($text);

To display image use showImage() function.

//display image
$img->showImage();

To save the image file as PNG or JPG format use saveAsPng() or saveAsJpg() function. Specify the file name and location to save the image, otherwise, the image will be saved with the default name to the same directory where the script is located.

//save image as png format
$img->saveAsPng('codex-text-to-image','images/');

//save image as jpg format
$img->saveAsJpg('codex-text-to-image','images/');

Conclusion

In TextToImage class we’ve used THE UNSEEN font as the text font. If you wish to change the text font, place the font file in the fonts/ directory and specify the font path in createImage() function ( $font ) of TextToImage class.

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

Читайте также:  Sql server authentication php

If you have any questions about this script, submit it to our QA community — Ask Question

Источник

imagecreatefromstring

imagecreatefromstring() возвращает идентификатор изображения, представляющего изображение полученное из потока image . Эти типы будут автоматически определяться, если сборка PHP их поддерживает: JPEG, PNG, GIF, WBMP и GD2.

Список параметров

Строка содержащая данные изображения.

Возвращаемые значения

В случае успеха будет возвращен ресурс изображения, FALSE , если тип изображения не поддерживается, данные не распознаются или данные нарушены и не могут быть загружены.

Примеры

Пример #1 Пример использования imagecreatefromstring()

$data = ‘iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl’
. ‘BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr’
. ‘EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r’
. ‘8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==’ ;
$data = base64_decode ( $data );

$im = imagecreatefromstring ( $data );
if ( $im !== false ) header ( ‘Content-Type: image/png’ );
imagepng ( $im );
imagedestroy ( $im );
>
else echo ‘Произошла ошибка.’ ;
>
?>

Результатом выполнения данного примера будет что-то подобное:

Смотрите также

  • imagecreatefromjpeg() — Создает новое изображение из файла или URL
  • imagecreatefrompng() — Создает новое изображение из файла или URL
  • imagecreatefromgif() — Создает новое изображение из файла или URL
  • imagecreatetruecolor() — Создание нового полноцветного изображения

Источник

String to png php

Пример #1 Создание PNG средствами PHP

header ( «Content-type: image/png» );
$string = $_GET [ ‘text’ ];
$im = imagecreatefrompng ( «images/button1.png» );
$orange = imagecolorallocate ( $im , 220 , 210 , 60 );
$px = ( imagesx ( $im ) — 7.5 * strlen ( $string )) / 2 ;
imagestring ( $im , 3 , $px , 9 , $string , $orange );
imagepng ( $im );
imagedestroy ( $im );

Этот пример можно было бы вызвать на странице с тегом: . Приведённый выше скрипт button.php возьмёт строку «text» и наложит её поверх базового изображения, которое является, в данном случае «images/button1.png» и выведет конечное изображение. Это очень удобный способ, чтобы избежать необходимости создания новой кнопки всякий раз, когда вы хотите изменить текст кнопки. С помощью этого метода она генерируются динамически.

Читайте также:  Всплывающее окно input html

User Contributed Notes 1 note

here is create_image.php
$setting = isset( $_GET [ ‘s’ ]) ? $_GET [ ‘s’ ] : «FFF_111_100_100» ;
$setting = explode ( «_» , $setting );
$img = array();

switch ( $n = count ( $setting )) case $n > 4 :
case 3 :
$setting [ 3 ] = $setting [ 2 ];
case 4 :
$img [ ‘width’ ] = (int) $setting [ 2 ];
$img [ ‘height’ ] = (int) $setting [ 3 ];
case 2 :
$img [ ‘color’ ] = $setting [ 1 ];
$img [ ‘background’ ] = $setting [ 0 ];
break;
default:
list( $img [ ‘background’ ], $img [ ‘color’ ], $img [ ‘width’ ], $img [ ‘height’ ]) = array( ‘F’ , ‘0’ , 100 , 100 );
break;
>

$background = explode ( «,» , hex2rgb ( $img [ ‘background’ ]));
$color = explode ( «,» , hex2rgb ( $img [ ‘color’ ]));
$width = empty( $img [ ‘width’ ]) ? 100 : $img [ ‘width’ ];
$height = empty( $img [ ‘height’ ]) ? 100 : $img [ ‘height’ ];
$string = (string) isset( $_GET [ ‘t’ ]) ? $_GET [ ‘t’ ] : $width . «x» . $height ;

header ( «Content-Type: image/png» );
$image = @ imagecreate ( $width , $height )
or die( «Cannot Initialize new GD image stream» );

$background_color = imagecolorallocate ( $image , $background [ 0 ], $background [ 1 ], $background [ 2 ]);
$text_color = imagecolorallocate ( $image , $color [ 0 ], $color [ 1 ], $color [ 2 ]);

imagestring ( $image , 5 , 5 , 5 , $string , $text_color );
imagepng ( $image );
imagedestroy ( $image );

function hex2rgb ( $hex ) // Copied
$hex = str_replace ( «#» , «» , $hex );

switch ( strlen ( $hex )) case 1 :
$hex = $hex . $hex ;
case 2 :
$r = hexdec ( $hex );
$g = hexdec ( $hex );
$b = hexdec ( $hex );
break;

case 3 :
$r = hexdec ( substr ( $hex , 0 , 1 ). substr ( $hex , 0 , 1 ));
$g = hexdec ( substr ( $hex , 1 , 1 ). substr ( $hex , 1 , 1 ));
$b = hexdec ( substr ( $hex , 2 , 1 ). substr ( $hex , 2 , 1 ));
break;

default:
$r = hexdec ( substr ( $hex , 0 , 2 ));
$g = hexdec ( substr ( $hex , 2 , 2 ));
$b = hexdec ( substr ( $hex , 4 , 2 ));
break;
>

$rgb = array( $r , $g , $b );
return implode ( «,» , $rgb );
>

Читайте также:  Регулярное выражение javascript для даты

Источник

Оцените статью