You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter在线考试项目:如何在成绩单图片指定位置添加内容?

Hey there! Let's work through this problem together. I've run into similar image manipulation issues when moving code between WAMP/XAMPP and integrating it into CodeIgniter, so here's a step-by-step solution to get your transcript generation working smoothly.

First: Fix the Black Background Issue in XAMPP

The black background usually stems from one of two problems: missing files (due to relative path discrepancies) or failed image resource initialization. Here's how to fix it:

  • Use absolute paths instead of relative ones: WAMP and XAMPP have different default working directories, so relative paths like "cmimage/studentphoto.jpg" might not resolve correctly. Always use absolute paths to your template, photos, and fonts.
  • Verify GD Library setup: Check if XAMPP's PHP has GD enabled (it usually does, but sometimes it's disabled). Create a phpinfo.php file in your root directory with <?php phpinfo(); ?>, run it, and look for the GD section to confirm JPEG and TrueType font support is enabled.
  • Validate image loading: Always check if imagecreatefromjpeg() returns a valid resource. If it fails (e.g., template file not found), PHP will implicitly create a black image, causing your text to render on a black background.

Integrating the Feature into CodeIgniter

CodeIgniter has strict path conventions, so we'll structure the code to fit its architecture—using helpers/libraries and built-in path constants.

Step 1: Create a Custom Helper

Helpers are perfect for reusable functions like image manipulation. Create application/helpers/transcript_helper.php with this code:

if (!function_exists('generate_transcript')) {
    function generate_transcript($student_data) {
        // Use CodeIgniter path constants for absolute paths
        $template_path = FCPATH . 'assets/images/transcript-template.jpg'; // Replace with your template path
        $font_path = FCPATH . 'assets/fonts/arial.ttf'; // Replace with your font file path
        $photo_path = FCPATH . 'cmimage/' . $student_data['photo'];
        $output_dir = FCPATH . 'cmimage/generated-transcripts/';

        // Ensure output directory exists and is writable
        if (!is_dir($output_dir)) {
            mkdir($output_dir, 0755, true);
        }

        // Load the transcript template
        $our_image = imagecreatefromjpeg($template_path);
        if (!$our_image) {
            throw new Exception("Failed to load transcript template at: $template_path");
        }

        // Define text color (white) and font settings
        $white_color = imagecolorallocate($our_image, 255, 255, 255);
        $font_size = 16;
        $font_angle = 0;

        // Replace these coordinates with your actual template positions
        $coords = [
            'exam_code' => ['x' => 100, 'y' => 200],
            'total_score' => ['x' => 100, 'y' => 250],
            'obtained_score' => ['x' => 100, 'y' => 300],
            'grade' => ['x' => 100, 'y' => 350],
            'another_total' => ['x' => 100, 'y' => 400],
            'another_obtained' => ['x' => 100, 'y' => 450],
            'another_grade' => ['x' => 100, 'y' => 500],
            'date' => ['x' => 100, 'y' => 550],
        ];

        // Add student data to the template
        imagettftext($our_image, $font_size, $font_angle, $coords['exam_code']['x'], $coords['exam_code']['y'], $white_color, $font_path, $student_data['exam_code']);
        imagettftext($our_image, $font_size, $font_angle, $coords['total_score']['x'], $coords['total_score']['y'], $white_color, $font_path, $student_data['total_score']);
        imagettftext($our_image, $font_size, $font_angle, $coords['obtained_score']['x'], $coords['obtained_score']['y'], $white_color, $font_path, $student_data['obtained_score']);
        imagettftext($our_image, $font_size, $font_angle, $coords['grade']['x'], $coords['grade']['y'], $white_color, $font_path, $student_data['grade']);
        imagettftext($our_image, $font_size, $font_angle, $coords['another_total']['x'], $coords['another_total']['y'], $white_color, $font_path, $student_data['another_total']);
        imagettftext($our_image, $font_size, $font_angle, $coords['another_obtained']['x'], $coords['another_obtained']['y'], $white_color, $font_path, $student_data['another_obtained']);
        imagettftext($our_image, $font_size, $font_angle, $coords['another_grade']['x'], $coords['another_grade']['y'], $white_color, $font_path, $student_data['another_grade']);
        imagettftext($our_image, $font_size, $font_angle, $coords['date']['x'], $coords['date']['y'], $white_color, $font_path, date('d/m/Y'));

        // Add student photo
        $student_photo = imagecreatefromjpeg($photo_path);
        if ($student_photo) {
            // Adjust the coordinates and size to match your template
            imagecopy($our_image, $student_photo, 1900, 1140, -80, -80, 360, 400);
            imagedestroy($student_photo);
        } else {
            // Fallback to default photo if student photo is missing
            $default_photo = imagecreatefromjpeg(FCPATH . 'assets/images/default-student.jpg');
            imagecopy($our_image, $default_photo, 1900, 1140, 0, 0, 360, 400);
            imagedestroy($default_photo);
        }

        // Save the generated transcript
        $output_path = $output_dir . $student_data['exam_id'] . '_transcript.jpg';
        imagejpeg($our_image, $output_path, 90); // 90 = image quality (0-100)

        // Clean up resources
        imagedestroy($our_image);

        return $output_path;
    }
}

Step 2: Call the Helper from a Controller

In your exam controller (e.g., application/controllers/Exam.php), load the helper and use the function:

class Exam extends CI_Controller {
    public function generate_student_transcript($student_id) {
        // Load the custom helper
        $this->load->helper('transcript');

        // Fetch student data from your database (replace with your actual query)
        $student_data = $this->db->get_where('students', ['id' => $student_id])->row_array();
        // Add exam-specific data (scores, grade, etc.)
        $student_data['exam_code'] = 'MSO';
        $student_data['total_score'] = '100';
        $student_data['obtained_score'] = '70';
        $student_data['grade'] = '70% A';
        $student_data['another_total'] = '100';
        $student_data['another_obtained'] = '70';
        $student_data['another_grade'] = '70% A';
        $student_data['exam_id'] = 'EXAM_' . $student_id;

        try {
            $transcript_path = generate_transcript($student_data);
            // Option 1: Redirect to download the transcript
            redirect(base_url(str_replace(FCPATH, '', $transcript_path)));
            // Option 2: Output the image directly to the browser
            // header('Content-Type: image/jpeg');
            // readfile($transcript_path);
        } catch (Exception $e) {
            echo "Error generating transcript: " . $e->getMessage();
        }
    }
}

Key CodeIgniter-Specific Tips

  • Path Constants: Use FCPATH (path to your CodeIgniter root), APPPATH (path to application folder), or WRITEPATH (path to writable directory) instead of relative paths to avoid file not found errors.
  • Permissions: Ensure folders like cmimage/ and cmimage/generated-transcripts/ have write permissions (set to 755 or 777 for development).
  • Resource Cleanup: Always call imagedestroy() on image resources to free memory, especially if generating multiple transcripts.

Final Checks

  1. Test the XAMPP setup first: Run the helper function in a standalone PHP file (using absolute paths) to confirm the black background is gone.
  2. Verify all file paths (template, font, photos) are correct in the helper.
  3. Ensure CodeIgniter's base_url is set correctly in application/config/config.php if you're redirecting to the generated transcript.

内容的提问来源于stack exchange,提问作者Alice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:01:35