简体   繁体   中英

Add Text to Image and download PHP-GD

There is some minor error in the code, I can't able to download the generated image which is creating dynamically after adding text on image. I have a image, I am just adding random digit to the image and download, with the same random number name.

<?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);





?>

I solved this, Little tweak on code.

 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM