0

For this project, I'm needing to create dynamic logos for a page based on data from a MySQL database. The table stores an image index, a foreground color, and a background color.

For testing purposes, I've created a small image in Photoshop to simulate the image, and I am using random numbers to create the foreground colors.

I'm wanting to create multiple randomized images per page, but the browser is keeping the resource for the image the same on each call. Is there a way to create multiple random images on the same page?

I have attempted to try to get it to working using random query strings and output buffering, but they haven't given me any luck.

Screenshot:

https://i.stack.imgur.com/h0SLU.png

Directory structure:

index.php
logo.png/
logo.png/circle.png
logo.png/index.php

index.php

<html>
<body style="background-color: #000000; color: #FFFFFF; font-family: 'Segoe UI'">
    <?php
        for ( $i = 0 ; $i <= 10 ; $i++ )
        {
            echo "<img src='logo.png' />";
        }
    ?>
</body>
</html>

logo.png/index.php

<?php
$im = imagecreatefrompng("circle.png");

$white = imagecolorallocate($im, 0xFF, 0xFF, 0xFF);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);

$x = imagecolorexact($im, 0xFF, 0xFF, 0xFF);
$y = imagecolorexact($im, 0xCC, 0xCC, 0xCC);
$z = imagecolorexact($im, 0xAA, 0xAA, 0xAA);

$randx = mt_rand(0, 255);
$randy = mt_rand(0, 255);
$randz = mt_rand(0, 255);

imagecolorset($im, $x, $randx, $randz, $randz);
imagecolorset($im, $y, $randy, $randy, $randx);
imagecolorset($im, $z, $randz, $randx, $randy);

header('Content-Type: image/png');
imagepng($im);
?>
Blake Renton
  • 37
  • 1
  • 7

1 Answers1

0

Chances are that your image is being cached by the browser, so there is only one request being made and the same picture is repeated for all ten calls.

You would need to make each URL look different using a random GET parameter, e.g. like this:

<?php
    for ( $i = 0 ; $i <= 10 ; $i++ )
    {
        $postfix = mt_rand(0, 10000);
        echo "<img src='logo.png?random=$postfix' />";
    }
?>

note however that this makes the images uncacheable: GD will run anew on every request. But it looks like that's the behaviour that you want.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • @tatersalad ah, I didn't see that. Weird - that sounds almost impossible. Can you show the code you used for the random query strings? – Pekka Dec 17 '11 at 21:07
  • 1
    I got it, I had the random outside of my for loop, derp. Thank you. C: – Blake Renton Dec 17 '11 at 21:08