2014-09-27 57 views
3

为文字添加到我使用下面的代码从一个站点如何保存图像添加文本后为图像

<?php 
    //Set the Content Type 
    header('Content-type: image/jpeg'); 

    // Create Image From Existing File 
    $jpg_image = imagecreatefromjpeg('sunset.jpg'); 

    // Allocate A Color For The Text 
    $white = imagecolorallocate($jpg_image, 255, 255, 255); 

    // Set Path to Font File 
    $font_path = 'font.TTF'; 

    // Set Text to Be Printed On Image 
    $text = "This is a sunset!"; 

    // Print Text On Image 
    imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text); 

    // Send Image to Browser 
    imagejpeg($jpg_image); 

    // Clear Memory 
    imagedestroy($jpg_image); 
?> 

它运作良好的图像,但我无法在PIC以保存文本文件保存我用这 功能

function write($post,$myFile){ 
    $fh = fopen($myFile, 'a+') or die("can't open file"); 
    fwrite($fh, $post); 
    fclose($fh); 
} 

有没有什么方法可以让我能保存图像JPG?

回答

2

这是我自己的代码,运行良好!只要改变name.jpg的名字到文件名,你想要什么

<?php 
    header('Content-type: image/jpeg'); 

    // Create Image From Existing File 
    $jpg_image = imagecreatefromjpeg('sunset.jpg'); 
//$jpg_image=imagecreatetruecolor(100,100); 

    // Allocate A Color For The Text 
$white = imagecolorallocate($jpg_image, 255, 255, 255); 


    // Set Path to Font File 
    $font_path = 'font1.TTF'; 

    // Set Text to Be Printed On Image 
    $text = "This is a sunset!"; 

    // Print Text On Image 
    $x=20; 
    for($i=0;$i<=strlen($text);$i++){ 
    $print_text=substr($text,$i,1); 
    $x+=20; 
    imagettftext($jpg_image, 30, 0, $x, 200, $white, $font_path, $print_text); 
    } 


    // Send Image to Browser 
    imagejpeg($jpg_image,'name.jpg'); 

    // Clear Memory 
    imagedestroy($jpg_image); 
?> 

我的代码是与你有一点不同,不同的一个是你没有改变指针的位置,你是打算把你的性格我的意思是$ X的地方:

imagettftext($jpg_image, 30, 0, $x, 200, $white, $font_path, $print_text); 

而另一个不同的是性格,你给字符串(不是字符)imagettftext功能,但我给一个字符。我认为角色比字符串更好,特别是创建验证码。

0

要将图像保存在文件中而不是输出它,只需将行imagejpeg($jpg_image);更改为imagejpeg($jpg_image, 'yourfile.jpg');(在这种情况下,也可以删除header('Content-type: image/jpeg');)。

+0

不行我做你指导! – Yaldram 2014-09-27 11:26:20

0

检查此代码。这是与您的代码,唯一的区别是

imagejpeg($jpg_image,"imagefolderpath/image.jpg");

,而不是imagejpeg($jpg_image);
也许这是对您有所帮助。

<?php 
 
    header('Content-type: image/jpeg'); 
 
    $jpg_image = imagecreatefromjpeg('sunset.jpg'); 
 
    $white = imagecolorallocate($jpg_image, 255, 255, 255); 
 
    $font_path = 'font.TTF'; 
 
    $text = "This is a sunset!"; 
 
    imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text); 
 
    imagejpeg($jpg_image,"imagefolderpath/image.jpg"); 
 
    imagedestroy($jpg_image); 
 
?>