如何邮寄使用php创建的图像


How to mail an image created using php

我有下面的代码,它将名字和姓氏添加到预定义的图像中。

function create_image($fname, $lname)
{
 $image = imagecreatefromjpeg('sample.jpg');
 $color = imagecolorallocate($image, 255, 255, 255);
 $font_path = '../fonts/GSMT.TTF';
 $font_size = 18;
 $first_name = $name;
 $last_name = $lname;
 $name = $fname." ". $lname;
// Print Text On Image
imagettftext($image, $font_size, 0, 100, 160, $color, $font_path, $name);
header('Content-type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
}

我使用以下电子邮件脚本;

function mailer($email_adrress, $registration_id)
{
$mail = new PHPMailer;
$mail->isSMTP(); // set mailer to use SMTP
$mail->Host = 'mail.server.com'; // set mail server
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Username = 'email@address.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->Port = 587; // TCP port to connect to
$mail->IsHTML(true);      
$mail->From = 'johndoe@gmail.com';
$mail->FromName = 'John Doe'; // from name     
$mail->addAddress($email_adrress); // recipient                            
$mail->Subject = 'emailer';
$mail->Body    = "Congratulations you have been Successfully registered.   
if(!$mail->send()) 
{
    die("error mail not sent);
} 
}

调用create_image函数时,会成功创建图像。但我的问题是,与其把图片打印到浏览器上,我该如何邮寄。我应该暂时保存图像,直到邮件发送,然后删除它,还是有其他方法?

我认为应该使用输出缓冲,将图像编码为base64,并在src标记中使用

ob_start();
// output jpeg (or any other chosen) format & quality
imagejpeg($image);
$contents = ob_get_contents();
ob_end_clean();

现在您需要base64内容

$base64 = base64_encode($contents);

现在您可以在您的消息HTML内容中使用它

<img src="data:image/jpeg;base64,$base64">

是的,正如您所说,您需要保存它,发送它,然后删除它。直接使用php来显示它是不可能的。但是,您可以使用iframe。但我认为第一个解决方案是最好的。