如何使用PHP将文本和图像写入jpg文件

时间:2014-02-15 06:10:25

标签: php

嗨朋友我想从mysql中获取一些文本和图像,并希望将它们写入php中的jpg文件。我的意思是文本和图像应该合并在一个jpg文件中。如果您有任何建议,请帮忙。感谢

2 个答案:

答案 0 :(得分:1)

您应该使用PHP的GD function library在图像上书写文字。 imagettftext()就是您在这里所需要的。

代码段..

<?php
header('Content-Type: image/png');
$im = imagecreatetruecolor(400, 30);
$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);
$text = 'Testing...';
$font = 'arial.ttf';
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
imagepng($im);
imagedestroy($im);

答案 1 :(得分:1)

<?php

/*** set the header for the image ***/
header("Content-type: image/jpeg");

/*** specify an image and text ***/
$im = writeToImage('test.jpg', 'PHPRO rules again');

/*** spit the image out the other end ***/
imagejpeg($im);

/**
 *
 * @Write text to an existing image
 *
 * @Author Kevin Waterson
 *
 * @access public
 *
 * @param string The image path
 *
 * @param string The text string
 *
 * @return resource
 *
 */
function writeToImage($imagefile, $text){
/*** make sure the file exists ***/
if(file_exists($imagefile))
    {    
    /*** create image ***/
    $im = @imagecreatefromjpeg($imagefile);

    /*** create the text color ***/
    $text_color = imagecolorallocate($im, 233, 14, 91);

    /*** splatter the image with text ***/
    imagestring($im, 6, 25, 150,  "$text", $text_color);
    }
else
    {
    /*** if the file does not exist we will create our own image ***/
    /*** Create a black image ***/
    $im  = imagecreatetruecolor(150, 30); /* Create a black image */

    /*** the background color ***/
    $bgc = imagecolorallocate($im, 255, 255, 255);

    /*** the text color ***/
    $tc  = imagecolorallocate($im, 0, 0, 0);

    /*** a little rectangle ***/
    imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

    /*** output and error message ***/
    imagestring($im, 1, 5, 5, "Error loading $imagefile", $tc);
    }
return $im;
}

?>