4

I am trying to output an image to a browser and then output HTML (not directly related to the image) on the same page. Is this possible? I am having a heck of a time figuring it out. Here is my code I have been messing with:

<?php
    function LoadJpeg($imgname){
        /* Attempt to open */
        $im = @imagecreatefromjpeg($imgname);
        /* See if it failed */
        if(!$im){
            /* Create a black image */
            $im  = imagecreatetruecolor(150, 30);
            $bgc = imagecolorallocate($im, 255, 255, 255);
            $tc  = imagecolorallocate($im, 0, 0, 0);
            imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
            /* Output an error message */
            imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
        }
        return $im;
    }

    header('Content-Type: image/jpeg');
    $img = LoadJpeg('images/Ball.jpg');
    imagejpeg($img);
    imagedestroy($img);
    //trying to start my text here
    header('Content-Type text/html; charset=utf-8');
    echo "<br /><h2>ross</h2>";
?>

Right near the bottom of my code is where I try to add in my html. when I run it, I only get the image, then no text after. If I try to move it to the top before the function, right after the opening php tag, the text works correctly, and then I get an error:

Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/newimage.php:4) in /Applications/MAMP/htdocs/newimage.php on line 28

Any help would be greatly appreciated, thanks.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
user1075004
  • 131
  • 1
  • 3
  • 9

4 Answers4

11

Stop and think for a moment. How would you normally embed an image in a HTML file? You create two files: text.html and image.jpg. Same here, you will create two scrips, one that outputs the HTML and one that generates the image. The HTML would look like:

<img src="generateimage.php" alt="generated image"/>
<br/>
<h2>ross</h2>

The generateimage.php script only generates the image.

Lets take for example a form that allows the user to create a digital Christmas card: he can select the image and write a personal note beneath it.

form.html:

<html><body>
<form action="view_card.php" method="post">
    Select an image:
    <select name="imgname">
        <option value="tree">Picture of Christmas tree</option>
        <option value="santa">Picture of Santa</option>
    </select><br/>

    Write a message:
    <textarea name="message"></textarea>
    <br/>

    <input type="submit" value="View Christmas card"/>
</form>
</body></html>

view_card.php:

<html>
  <body>
    Here is your Christmas card:
    <hr/>

    <!-- sending the requested image to the generateimage.php script
         as a GET parameter -->
    <img src="generateimage.php?imgname=<?php echo(urlencode($_POST['imgname'])); ?>"/>
    <?php echo(htmlspecialchars($_POST['message'])); ?>
  </body>
</html>

generateimage.php:

<?php
/* Stop evil hackers from accessing files they are not supposed to */
$allowed_files = array('tree' => 'tree.jpg', 'santa' => 'santa.jpg');
if( !isset($allowed_files[$_GET['imgname']])) {
    exit; // Thank you for playing...
}

/* Attempt to open */
$im = @imagecreatefromjpeg($allowed_files[$_GET['imgname']]);

/* See if it failed */
if(!$im){
    /* Create a black image */
    $im  = imagecreatetruecolor(150, 30);
    $bgc = imagecolorallocate($im, 255, 255, 255);
    $tc  = imagecolorallocate($im, 0, 0, 0);
    imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

    /* Output an error message */
    imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}

header('Content-Type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
?>
Leopoldo Sanczyk
  • 1,529
  • 1
  • 26
  • 28
Marijn van Vliet
  • 5,239
  • 2
  • 33
  • 45
  • 2
    You do not have to create separate file for generating image itself. You can encode it using base64 and output within HTML. It really works, eg. Facebook uses it. See [this jsfiddle](http://jsfiddle.net/nmq6t/) for a proof. – Tadeck Dec 01 '11 at 09:13
  • I am using a form to have the user input text, and write that input on an image. Both image and text are user defined on the form, so don't think it's as easy as the above example you provided.
    is the html form info I am using. So, on selection.php, I output the image with imagejpeg($img); once image has been output, that kills the ability to write any html on the page. Any more help?
    – user1075004 Dec 08 '11 at 06:37
  • I see, you need to pass on the form info to the generateimage.php script as well then. I'll modify my answer accordingly. – Marijn van Vliet Dec 09 '11 at 10:12
9

Including image in HTML

See the following question and answers: Base64 Encoding Image.

You have to can encode your image using base64_encode() and then output it within <img> tag like that:

<img src="data:image/x-icon;base64,<?php echo base64_encode($img); ?>"></img>

(see this jsfiddle for a proof).

Generating image in different file

You can generate image outside of the script that generates HTML. In such case you will need to generate HTML here and set src attribute of <img> tag to the location of the script generating the image. See @Rodin's answer for a slightly more detailed answer regarding this solution.

Did it work? Do you need any more help?

Community
  • 1
  • 1
Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • I doubt he needs this at all :) – Your Common Sense Dec 01 '11 at 09:13
  • 2
    @Col.Shrapnel: He tried to output image along with HTML and in contrary to what other people say, I say it is possible and I have proven it ;) I am just curious, why I was down voted for showing working solution being the nearest to the one OP tried to implement :) – Tadeck Dec 01 '11 at 09:17
  • 1
    Never knew this was possible, +1! – Marijn van Vliet Dec 01 '11 at 09:22
  • Because not every "working solution" deserves implementation just because "it works" and because not every OP really knows what to ask. – Your Common Sense Dec 01 '11 at 09:25
  • 3
    @Col.Shrapnel: Agreed on that not every OP knows how to ask. But leave it to him to decide which solution he chooses. When it comes to implementing solutions, it is of course more complex question involving many different aspects. My solution has pros & cons. Pros are: 1) code is stored in one place, 2) 2x less requests to the server, 3) you can not hotlink to such image, 4) you are less vulnerable to attacks (ok, maybe the last one is not always true, but you do not show the structure of your application / location of the scripts accessing files on the server) etc. – Tadeck Dec 01 '11 at 09:33
1

you can't set the header once output has been sent to the browser. Instead send everything as text/html and insert the raw image data into an img tag

<?php


function LoadJpeg($imgname)
{
/* Attempt to open */
$im = @imagecreatefromjpeg($imgname);

/* See if it failed */
if(!$im)
{
    /* Create a black image */
    $im  = imagecreatetruecolor(150, 30);
    $bgc = imagecolorallocate($im, 255, 255, 255);
    $tc  = imagecolorallocate($im, 0, 0, 0);

    imagefilledrectangle($im, 0, 0, 150, 30, $bgc);

    /* Output an error message */
    imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}

  // Changed the following line to return the output 
  // of imagejpeg() instead of the image object
  return imagejpeg($im);
}

$img = LoadJpeg('images/Ball.jpg');

//trying to start my text here
header('Content-Type text/html; charset=utf-8');

// img tag with image raw data set as source
echo '<img src="data:image/jpeg;base64,'.base64_encode($img).'" alt="photo">';

echo "<br /><h2>ross</h2>";


?>
Pastor Bones
  • 7,183
  • 3
  • 36
  • 56
0

Store only your image creation code in its own php script. Then you call the script in your HTML as if it were a regular image with the img tag like this:

<img src="jpegscript.php" alt="image"/>
Chris C
  • 2,003
  • 15
  • 18