( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ HEX
HEX
Server: Apache/2.4.58 (Ubuntu)
System: Linux mail.thebrand.ai 6.8.0-107-generic #107-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 13 19:51:50 UTC 2026 x86_64
User: www-data (33)
PHP: 8.3.6
Disabled: NONE
Upload Files
File: /var/www/html/insights/image.php
<?php

function getRandomFont($fontsDirectory) {
    // Scan the directory for .ttf or .otf files
    $fontFiles = array_merge(glob($fontsDirectory . '/*.ttf'), glob($fontsDirectory . '/*.otf'));

    // Return a random font file from the list
    if (!empty($fontFiles)) {
        return $fontFiles[array_rand($fontFiles)];
    }

    // Fallback: return null or handle the case where no fonts are found
    return null;
}

function getRandomBackgroundImage($backgroundsDirectory) {
    // Scan the directory for common image files
    $imageFiles = array_merge(
        glob($backgroundsDirectory . '/*.jpg'),
        glob($backgroundsDirectory . '/*.jpeg'),
        glob($backgroundsDirectory . '/*.png'),
        glob($backgroundsDirectory . '/*.gif')
    );

    // Return a random image file from the list
    if (!empty($imageFiles)) {
        return $imageFiles[array_rand($imageFiles)];
    }

    // Fallback: return null or handle the case where no images are found
    return null;
}

function wrapText($text, $fontSize, $fontPath, $maxWidth) {
    $wrappedText = '';
    $words = explode(' ', $text);
    $currentLine = '';

    foreach ($words as $word) {
        // Check the width of the current line + the new word
        $testLine = $currentLine ? $currentLine . ' ' . $word : $word;
        $textBox = imagettfbbox($fontSize, 0, $fontPath, $testLine);
        $textWidth = $textBox[2] - $textBox[0];

        if ($textWidth <= $maxWidth) {
            // If the line fits, add the word
            $currentLine = $testLine;
        } else {
            // If the line doesn't fit, start a new line
            $wrappedText .= $currentLine . "\n";
            $currentLine = $word;
        }
    }

    // Add the last line
    $wrappedText .= $currentLine;

    return $wrappedText;
}

function createDynamicHeaderImage($saveDirectory,$headerText, $fontsDirectory, $backgroundsDirectory, $width = 1920, $height = 1080, $textColorHex = '#FFFFFF', $bgColorHex = '#000000') {
    // Get a random font
    $fontPath = getRandomFont($fontsDirectory);

    if (!$fontPath) {
        throw new Exception('No font files found in the specified directory.');
    }

    // Debugging: Check if the font file exists
    if (!file_exists($fontPath)) {
        throw new Exception('Font file does not exist: ' . $fontPath);
    }

    // Get a random background image
    $backgroundImagePath = getRandomBackgroundImage($backgroundsDirectory);

    if (!$backgroundImagePath) {
        throw new Exception('No background images found in the specified directory.');
    }

    // Debugging: Check if the background image file exists
    if (!file_exists($backgroundImagePath)) {
        throw new Exception('Background image file does not exist: ' . $backgroundImagePath);
    }

    // Create a base image
    $baseImage = imagecreatetruecolor($width, $height);
    if (!$baseImage) {
        throw new Exception('Failed to create base image.');
    }

    // Parse hex color to RGB
    list($bgRed, $bgGreen, $bgBlue) = sscanf($bgColorHex, "#%02x%02x%02x");

    // Fill the base image with the background color
    $backgroundColor = imagecolorallocate($baseImage, $bgRed, $bgGreen, $bgBlue);
    imagefilledrectangle($baseImage, 0, 0, $width, $height, $backgroundColor);

    // Load background image
    $bgImage = imagecreatefromstring(file_get_contents($backgroundImagePath));
    if ($bgImage) {
        // Resize and overlay background image
        imagecopyresampled($baseImage, $bgImage, 0, 0, 0, 0, $width, $height, imagesx($bgImage), imagesy($bgImage));
        imagedestroy($bgImage);
    }

    // Allocate a color for text
    list($textRed, $textGreen, $textBlue) = sscanf($textColorHex, "#%02x%02x%02x");
    $textColor = imagecolorallocate($baseImage, $textRed, $textGreen, $textBlue);

    // Define initial font size
    $fontSize = 90;
    $angle = 0;

    // Wrap the text to fit within the image width
    $maxTextWidth = $width * 0.8; // Allow 80% of the image width for text
    $wrappedText = wrapText($headerText, $fontSize, $fontPath, $maxTextWidth);

    // Calculate the total height of the wrapped text
    $lines = explode("\n", $wrappedText);
    $lineHeight = $fontSize * 1.9; // Line height is 1.2 times the font size
    $totalTextHeight = count($lines) * $lineHeight;

    // Adjust font size if the text height exceeds the image height
    while ($totalTextHeight > $height * 0.8 && $fontSize > 10) {
        $fontSize--;
        $wrappedText = wrapText($headerText, $fontSize, $fontPath, $maxTextWidth);
        $lines = explode("\n", $wrappedText);
        $lineHeight = $fontSize * 1.9;
        $totalTextHeight = count($lines) * $lineHeight;
    }

    // Calculate starting Y position to center the text vertically
    $startY = ($height / 2) - ($totalTextHeight / 2);
    $startY = $startY+80;
    // Add each line of text to the image
    foreach ($lines as $line) {
        $textBox = imagettfbbox($fontSize, $angle, $fontPath, $line);
        $textWidth = $textBox[2] - $textBox[0];
        $x = ($width / 2) - ($textWidth / 2); // Center the line horizontally
        imagettftext($baseImage, $fontSize, $angle, $x, $startY, $textColor, $fontPath, $line);
        $startY += $lineHeight; // Move to the next line
    }





    // Set the content type header to display the image
    header('Content-Type: image/png');

    // Output the image directly to the browser
    imagepng($baseImage);


// Save the image to a directory
    $filePath = 'assets/images/filename.png';  // Specify the directory and filename
    imagepng($baseImage, $filePath);



    // Destroy the image
    imagedestroy($baseImage);
}

// Example usage
try {
    $headerText = 'This is  mage dimensions.s is  mage dimensions.';
    $headerText = preg_replace("/[^a-zA-Z0-9 ]/", "", $headerText);

    $words = explode(' ', $headerText);

    // Check if there are more than 10 words
    if (count($words) > 10) {
        // Get the first 10 words and append '...'
        $first10Words = array_slice($words, 0, 10);
        $headerText =  implode(' ', $first10Words) . '...';
    } else {
        // If 10 words or fewer, return the original string
        $headerText = $headerText ;
    }

    $fontsDirectory = __DIR__ . '/assets/fonts'; // Use absolute path
    $backgroundsDirectory = __DIR__ . '/assets/bgs';

    //Use absolute path
    $saveDirectory =  __DIR__ . '/assets/images'; // Directory for background images

    // Generate and display the image
    createDynamicHeaderImage($saveDirectory,$headerText, $fontsDirectory, $backgroundsDirectory);
} catch (Exception $e) {
    die('Error: ' . $e->getMessage());
}
?>