Need GD Library Imagecreate to display on same page

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kip1790
    New Member
    • Jun 2009
    • 13

    Need GD Library Imagecreate to display on same page

    See example here

    Ultimately I want the image created to display next to the update button in the same browser window instead of loading into a new window. Then every time I input text and click 'update' the image is regenerated. As if you're customizing the image with whatever text the user inputs.

    A similar example I've found online is here.

    I'm simply just posting the text input variable to a PHP file to generate the image in the following PHP file:

    Code:
    <?php
    $my_img = imagecreate( 200, 80 );
    $background = imagecolorallocate( $my_img, 0, 0, 255 );
    $text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
    $line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
    $input_text = $_REQUEST['name'] ;
    imagestring( $my_img, 4, 30, 25, $input_text,
      $text_colour );
    imagesetthickness ( $my_img, 5 );
    imageline( $my_img, 30, 45, 165, 45, $line_colour );
    
    header( "Content-type: image/png" );
    imagepng( $my_img );
    imagecolordeallocate( $line_color );
    imagecolordeallocate( $text_color );
    imagecolordeallocate( $background );
    imagedestroy( $my_img );
    ?>
    I've searched high and low to resolve this but had no luck - hoping somebody can help...
  • dgreenhouse
    Recognized Expert Contributor
    • May 2008
    • 250

    #2
    You should look into using Ajax or you could have the display portion embedded in an iFrame. Regardless, you'll have to use JavaScript to do the interactions with the server and then perform DOM manipulations to display the returned results. If you go the simpler iFrame route, you'd only have to tell the iframe to load itself with the correct url and params on your server.

    Comment

    • kip1790
      New Member
      • Jun 2009
      • 13

      #3
      Thanks for the prompt response. How can I modify the PHP output file to target an iframe?

      Comment

      • kovik
        Recognized Expert Top Contributor
        • Jun 2007
        • 1044

        #4
        Hmm? You'll want to add JavaScript to communicate with the iframe. I find that it's easier to simply alter the DOM, though. Is this image created in image.php? Then, you could allow image.php to take a string as a query string variable. Then, you could just alter the "src" attribute of an <img> element.

        Basically, you'd use JavaScript to access the <img> element and the <input> element and, when the update button is pressed for, then change the "src" attribute of the <img> element to something like "http://website.tld/image.php?name= ***" where you'd replace "***" with the value of the <input> element.

        Comment

        • dgreenhouse
          Recognized Expert Contributor
          • May 2008
          • 250

          #5
          kovik's suggestion would be the simplest and most expedient...

          Here's a basic html page that will hopefully get you going:
          Code:
          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
          <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
              <title>Untitled Document</title>
              <script type="text/javascript">
                function getImage()
                {
                  var img_text = document.getElementById("inp_img_text").value;
                  var img_obj = document.getElementById("img_2_change");
                  img_obj.src = "image_change.php?name=" + img_text;
                }
              </script>
            </head>
            <body>
              <form onsubmit="return false;">
                Name: <input type="text" id="inp_img_text" name="name"  />
                <input type="submit" value="Update" onclick="getImage()"; /><br />
                <img src="image_change.php?name=Image%20Text%20Here" id="img_2_change" style="width:200px;height:80px;" alt="Image created by a PHP script" /> 
              </form>
            </body>
          </html>
          Note: The value "return false;" on the form's onsubmit attribute ensures that the default form action is short circuited and doesn't fire. All we want to do is to change the source attribute (src) of the image; not make a call on a a server page.

          Comment

          • kip1790
            New Member
            • Jun 2009
            • 13

            #6
            That worked perfectly. There's one more step I'm looking for your help on and hopefully this is a minor change. I've added a drop down with 2 options for a background - Teal/Red - instead of the pre-defined color that was there before. I added a var for this value in the JS and added the drop down to the form. I also added the value that was passed to image.php to be defined as $input_bg as you can see below. So I'm looking for the bg to update with the text when I press 'update'. Can you see what is wrong with the bolded text I've added below?

            Code:
            <script type="text/javascript">
                  function getImage()
                  {
                    var img_text = document.getElementById("inp_img_text").value;
            		[B]var img_bg = document.getElementById("inp_img_bg").value;[/B]
                    var img_obj = document.getElementById("btn_img_change");
                    img_obj.src = "myimage.php?name=" + img_text + img_bg;
                  }
                </script>
              </head>
             
              <body>
                <form onsubmit="return false;">
                  Name: <input type="text" id="inp_img_text" name="name"  />
                  [B]Background: <select size="1" id="inp_img_bg" name="background" />
                  <option value="template.jpg">Teal</option>
                  <option value="semplate.jpg">Red</option>
                  </select>[/B]
                  <input type="submit" value="Update" onclick="getImage()"; />
                  <img src="" id="btn_img_change" style="width:200px;height:80px;" alt="Image created by a PHP script" /> 
             </form>
            Code:
            <?php
            [B]$input_bg = $_REQUEST['background'] ;[/B]
            [B]$my_img = imagecreatefromjpeg( $input_bg);[/B]
            $background = imagecolorallocate( $my_img, 0, 0, 255 );
            $text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
            $line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
            $input_text = $_REQUEST['name'] ;

            Comment

            • dgreenhouse
              Recognized Expert Contributor
              • May 2008
              • 250

              #7
              Here are the modified files...
              (Also, here's a great site I found while searching for hex color values.)
              Web design resources - named colours / colors. Includes rgb and hex values for html and css.


              image_change.ht ml
              Code:
              <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
              <html xmlns="http://www.w3.org/1999/xhtml">
                <head>
                  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                  <title>Untitled Document</title>
                  <script type="text/javascript">
                    function getImage()
                    {
                      var inp_text = document.getElementById("inp_img_text");
                      var img_bg = document.getElementById("inp_img_bg").value;
                      var img_obj = document.getElementById("img_2_change");
                      img_obj.src = "image_change.php?name=" + inp_text.value + "&bg=" + img_bg;
                      //inp_text.value = ""; // Clear the text box
                    }
                  </script>
                </head>
                <body>
                  <form onsubmit="return false;">
                    Name: <input type="text" id="inp_img_text" name="name"  />
                    Background: 
                    <select size="1" id="inp_img_bg" name="bg" />
                      <option value="008080">Teal</option>
                      <option value="FF0000">Red</option>
                      <option value="FF">Blue</option>
                      <option value="FF00">Green</option>
                    </select>
                    <input type="submit" value="Update" onclick="getImage()"; /><br />
                    <img src="image_change.php?name=Image Text Here&bg=0" id="img_2_change" style="width:200px;height:80px;" alt="Image created by a PHP script" /> 
                  </form>
                </body>
              </html>
              image_change.ph p
              Code:
              <?php
              // Validate & cleanse inputs first..
              $input_text = 
                isset($_GET['name']) && strlen($_GET['name']) < 20 
                ? strip_tags($_GET['name']) 
                : NULL;
              
              // initialize variables for: R,G,B, and valid_color check
              $r = $g = $b = $is_valid_color = 0;
              
              if ( isset($_GET['bg']) && preg_match('/^[0-9A-F]{1,6}$/i',$_GET['bg']) ) {
                $is_valid_color = hex2rgb($_GET['bg'],$r,$g,$b);
              	// Could just set $is_valid_color
              	// instead of having the
              	// function return a value,
              	// but it helps to have a return
              	// value when the function (hex2rgb) 
              	// gets refactored.
              }
              
              // End of validation...
              
              if (!$input_text || !$is_valid_color) {
                exit; // exit if bad values provided
              
                // Fix to actually send an image with an error message
                // I'll leave that up to you... :D
              }
              
              
              $my_img = imagecreate( 200, 80 );
              $background = imagecolorallocate( $my_img, $r, $g, $b);
              $text_colour = imagecolorallocate( $my_img, 255, 255, 0 );
              $line_colour = imagecolorallocate( $my_img, 128, 255, 0 );
              
              imagestring( $my_img, 4, 30, 25, $input_text, $text_colour );
              imagesetthickness ( $my_img, 5 );
              imageline( $my_img, 30, 45, 165, 45, $line_colour );
              
              header( "Content-type: image/png" );
              imagepng( $my_img );
              imagecolordeallocate( $line_color );
              imagecolordeallocate( $text_color );
              imagecolordeallocate( $background );
              imagedestroy( $my_img );
              
              /**
               * Return r,b,g values from hex(string) input
               *
               * @copyright Copyright (c) <February, 1 2010> <Darrell C. Greenhouse>
               * @link http://www.linfo.org/mitlicense.html
               *
               * @param string $hexval The hex value to convert
               * @param int $r The converted rgb values
               * @param int $g ""
               * @param int $b ""
               * @return int|boolean
               */
              function hex2rgb($hexval, &$r, &$g, &$b)
              {
              	// Ensure it's a full 6 nibble hex value
                $hexval = str_pad($hexval, 6, "0", STR_PAD_LEFT);  
              
                $colors = array("b","g","r"); // Note how they're reversed
                
                for ($i = 4, $j=0; $i > -1; $i-=2) {
                  ${$colors[$j++]} = hexdec(substr($hexval,$i,2));
                }
                return 1;
              }
              
              ?>

              Comment

              • kip1790
                New Member
                • Jun 2009
                • 13

                #8
                This is great, thanks. I'm trying to use images as backgrounds instead of RGB colors, I've tried to modify what you've provided but the logic isn't clear to me with the extra code - apologies! - Bg like this for example...

                Comment

                • kovik
                  Recognized Expert Top Contributor
                  • Jun 2007
                  • 1044

                  #9
                  PHP's GD library requires you to make an image resource out of image files. So, you'd simply make a resource out of that image, and copy/merge it into the main resource.

                  Comment

                  • dgreenhouse
                    Recognized Expert Contributor
                    • May 2008
                    • 250

                    #10
                    Originally posted by kip1790
                    This is great, thanks. I'm trying to use images as backgrounds instead of RGB colors, I've tried to modify what you've provided but the logic isn't clear to me with the extra code - apologies! - Bg like this for example...

                    Are you trying to create an image background with an upper and lower differential color region as show in your last post?

                    Comment

                    • kip1790
                      New Member
                      • Jun 2009
                      • 13

                      #11
                      As I understand it you can use an image as background template and just write the text to it to create a new image by replacing imagecreate () with imagecreatefrom jpeg ( "template.j pg"). I did this with my original code here.

                      I'm just looking to select one of two backgrounds from a drop down and pass the bg file value to the$background variable in the PHP.

                      $input_backgrou nd = $_REQUEST['background'] ;
                      $my_img = imagecreatefrom jpeg( $_REQUEST['background']);

                      There is a brief outline of this capability here under Modifying an Existing Image.

                      Comment

                      • dgreenhouse
                        Recognized Expert Contributor
                        • May 2008
                        • 250

                        #12
                        Update!: Try also using the imagettftext or the imagechar functions...
                        It'll probably save you a lot of time versus using that which I describe at the bottom of this post..

                        =============== =============== =============== =============== ===

                        Chris,

                        I got your private message...

                        I've thought about your issue, but I haven't had the time to really write anything up...
                        I've been really swamped and still am...

                        I also for the 1st time suffered a "Trojan" after 32 years in the computer industry!

                        I've finally been christened! Yippee! :D

                        I'm really surprised that I'm not depressed over it... Slowed me down to smell the roses...

                        Criminal hackers should be dragged through the streets like Mussolini!

                        It's my understanding that you want to use an existing background image that's selected from the drop-down, so you'll probably need to use PHP's imagecopymerge command in your script to merge two images into one.

                        i.e.
                        1- Generate image from text
                        2- Pass into the imagecopymerge function as parameters the generated image resource, a resource based on the background image, the coordinates of where to place the background image in the merged image, the coordinates in the background image to copy over, and the source width & height values of the background image

                        It'll still be a day or so before I can really get to this, but if you play around with the concepts above, you might figure it out before then...
                        (Which of course would be the most satisfying, rewarding, and educational experience.)

                        All the best
                        Last edited by dgreenhouse; Feb 3 '10, 06:51 PM. Reason: Thought of a possible easier way to implement the desired functionality

                        Comment

                        • kip1790
                          New Member
                          • Jun 2009
                          • 13

                          #13
                          I wasn't sure why I required imagecopymerge when you can write text to a background image using imagecreatefrom jpeg. Anyway I tried again to pass the background value based on dropdown selection and it worked fine. See here. Do you see any problems doing it this way?

                          One of the last issues I've faced is using imagettftext to write a particular font to the image, and trust me it's not through lack of effort.

                          My host supports freetype and it's compiled with 4.4.9.
                          '../configure' '--with-pear=/usr/lib/php' '--prefix=/usr' '--with-mysql=/usr/' '--with-zlib' '--enable-debug=no' '--enable-safe-mode=no' '--enable-discard-path=no' '--with-gd' '--with-png-dir' '--enable-track-vars' '--with-db' '--with-gdbm' '--enable-force-cgi-redirect' '--with-ttf' '--enable-ftp' '--with-mcrypt' '--enable-dbase' '--enable-memory-limit' '--enable-calendar' '--enable-wddx' '--with-jpeg-dir' '--enable-bcmath' '--enable-gd-imgstrttf' '--enable-shmop' '--enable-mhash' '--with-mhash' '--with-openssl' '--enable-xslt' '--with-xslt-sablot' '--with-dom' '--with-dom-xslt' '--with-dom-exslt' '--with-imap' '--with-curl' '--with-iconv' '--with-freetype-dir' '--with-bz2' '--with-gettext' '--enable-exif' '--with-idn' '--enable-mbstring=all' '--with-kerberos' '--with-imap-ssl' '--with-sqlite' '--with-zip'

                          I changed my FTP settings to upload text files as ASCII instead of binary and tried it with a number of basic ttfs in the same folder but still did not work.
                          I added this to my PHP file, with all variables assigned a value:
                          $font = 'arial.ttf';
                          imagettftext ($my_img, 10, 15, 30, 40, $txt_colour, $font, $input_text);
                          Also tried it with:
                          putenv('GDFONTP ATH=' . realpath('.'));
                          $font = 'arial.ttf';
                          I even tried using the imagefttext function but to no avail. It just generates an image with no text at all. I can't find any other method of troubleshooting this issue, so anything that I haven't tried here....??

                          Comment

                          • Markus
                            Recognized Expert Expert
                            • Jun 2007
                            • 6092

                            #14
                            The problem may be that your switch for freetype does not point to the directory containing the freetype library.

                            Comment

                            • kip1790
                              New Member
                              • Jun 2009
                              • 13

                              #15
                              I spoke with my web host (1and1) and they assured me that, providing my code was correct and the font was uploaded to the folder my script was running from, it should work. I'm truly stumped on this one...

                              Comment

                              Working...