简体   繁体   中英

Creating multiple images with imagejpeg loop

I'm building the loop below to generate multiple images using an existing image, and text collect from a user inputed form field. One of the variables is an array that was made by parsing a csv file with names.

The problem I'm running into is that the code only outputs the first image, but not any others. The array has 9 values, but that number can change based off the user's csv.

<?php
$school = $_POST["school"];
$educator1 = $_POST["educator1"];
$educator2 = $_POST["educator2"];     
$students = $_FILES["csv"]["tmp_name"];
$csvAsArray = array_map("str_getcsv", file($students));

foreach ($csvAsArray as $value) {

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

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

    // Allocate A Color For The Text
    $black = imagecolorallocate($jpg_image, 0, 0, 0);
    $grey = imagecolorallocate($jpg_image, 63, 63, 63);

    // Set Path to Font File
    $font_path = 'GothamRounded-Bold.otf';

    // Print Text On Image
    imagettftext($jpg_image, 90, 0, 90, 920, $black, $font_path, $value[0]);
    imagettftext($jpg_image, 50, 0, 850, 1120, $black, $font_path, $school);
    imagettftext($jpg_image, 50, 0, 90, 1480, $grey, $font_path, $educator1);
    imagettftext($jpg_image, 50, 0, 1050, 1475, $grey, $font_path, $educator2);

    // Send Image to Browser
    // $name = $value[0] .'.jpg';
    imagejpeg($jpg_image);   

    // Clear Memory
    imagedestroy($jpg_image);
}

Instead of pushing straight to the browser, I tried to save the image file using the $name variable to create the following, but this did not work either.

$name = $value[0] .'.jpg';    
imagejpeg($jpg_image, $name);

You cannot return several images at once in this way. Here is the options I can suggest you:

  1. Pack them all into zip or something and then return as single file
  2. Glue them up and return as single picture
  3. Save them on server in a public directory, and provide direct links in response to end-user

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