将文本添加到图像并下载 PHP-GD

Add Text to Image and download PHP-GD

代码中存在一些小错误,我无法下载在图像上添加文本后动态创建的生成图像。我有一张图片,我只是在图片中添加随机数字并下载,使用相同的随机数字名称。

<?php


  function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
  }

  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-image');
  header('Content-type: image/jpeg');

  $jpg_image = imagecreatefromjpeg('voucher.jpg');
  $white = imagecolorallocate($jpg_image, 20, 16, 6);
  $font_path = 'font.TTF';
  $text = "Voucher No: ".generateRandomString(10);
  imagettftext($jpg_image, 15, 0, 85, 680, $white, $font_path, $text);
  imagejpeg($jpg_image);

   header("Content-disposition: attachment; filename=".$jpg_image."");  
   readfile($jpg_image);

  imagedestroy($jpg_image);





?>

我解决了这个问题,稍微调整一下代码。

 function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
  }

  $vnum=generateRandomString(10);
  $jpg_image = imagecreatefromjpeg('voucher.jpg');
  $white = imagecolorallocate($jpg_image, 20, 16, 6);
  $font_path = 'font.TTF';
  $text = "Voucher No: ".$vnum;
  imagettftext($jpg_image, 15, 0, 85, 680, $white, $font_path, $text);

  header('Content-type: image/jpeg');
  imagejpeg($jpg_image,"".$vnum.".jpg");
  header("Content-disposition: attachment; filename=".$vnum.".jpg");
  header('Content-Description: File Transfer');
  readfile("".$vnum.".jpg");
  imagedestroy($jpg_image);