Wrox Programmer Forums

Need to download code?

View our list of code downloads.

| FAQ | Members List | Search | Today's Posts | Mark Forums Read
BOOK: Professional Ajax ISBN: 978-0-471-77778-6
This is the forum to discuss the Wrox book Professional Ajax by Nicholas C. Zakas, Jeremy McPeak, Joe Fawcett; ISBN: 9780471777786
Important: For the new 2nd edition of this book, please post here instead: [url="http://p2p.wrox.com/forum.asp?FORUM_ID=307"]http://p2p.wrox.com/forum.asp?FORUM_ID=307[/url]
Welcome to the p2p.wrox.com Forums.

You are currently viewing the BOOK: Professional Ajax ISBN: 978-0-471-77778-6 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
DRM-free e-books 300x50
Reply
 
Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old September 26th, 2006, 10:08 PM
Registered User
 
Join Date: Sep 2006
Location: , , .
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default AJAX to get dynamic images

Hi there,

I have a small problem with AJAX for displaying a dynamically created image from a php file. I have a page where the user types a text in the textbox and when he submits a images file is generated with the text in it. Now what i need is get the image directly below the submit button.

The PHP code (img.php) is below

<?php
Header("Content-type: image/png");

$name = $_GET['letter'];
$img_handle = ImageCreate (350, 100) or die ("Cannot Create image");
$back_color = ImageColorAllocate ($img_handle, 50, 50, 50);
$txt_color = ImageColorAllocate ($img_handle, 255, 255, 255);
ImageString ($img_handle, 3, 5, 5, $name, $txt_color);
ImagePng ($img_handle);
?>


So to display the image what i normally do is <img src="img.php?letter=texttodisplay"> , but now i want to use ajax to get image dynamically updated when submit is clicked. I tried using xmlHTTPrequest, but it works only for text. I want to use AJAX for images.

Can any give me any ideas for this.
Reply With Quote
  #2 (permalink)  
Old September 27th, 2006, 03:25 AM
joefawcett's Avatar
Wrox Author
Points: 9,763, Level: 42
Points: 9,763, Level: 42 Points: 9,763, Level: 42 Points: 9,763, Level: 42
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Exeter, , United Kingdom.
Posts: 3,074
Thanks: 1
Thanked 38 Times in 37 Posts
Default

You can't embed images in an HTML page therefore, although you can retrieve the image data, you can't use it. The solution is simple though, just dynamically alter the img's src attribute when the submit is called.

Show a bit more of the client-side code, such as form and any code that executes onsubmit if you can't get it to work.

--

Joe (Microsoft MVP - XML)
Reply With Quote
  #3 (permalink)  
Old October 2nd, 2006, 01:22 AM
Registered User
 
Join Date: Oct 2006
Location: Christchurch, , New Zealand.
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Your basic technique of creating an image dynamically on the server and then telling the browser where to find it still applies.

Instead of generating the entire page including a link to the new image (the 'old way') you want to recieve the name of the new image file using AJAX.

If you can succesfully submit the form data using an AJAX post, then you should be able to create a javascript call-back function to update the image's SRC attribute with the name of the newly created image on the server.

Your PHP example simply needs to create a new file somewhere in your site, possibly using a unique file name if necessary, and send this back to the browser. THis is TEXT data, not image data, so drop the "Header" statement.

Good luck!

Reply With Quote
  #4 (permalink)  
Old May 19th, 2007, 09:48 PM
Registered User
 
Join Date: May 2007
Location: Aguascalientes, Aguascalientes, Mexico.
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to darkscripter
Default

badcop666 needs more experience...

sometimes, in a enterprise environment, it needs a big.. big URL to get an image, probably a chart image, IE (stupid Micro$oft guys) has limits with is URL GET lenght.. its limit its around 2ks, others browsers doesnt have any problem..

lets see an example...

if you have the next URL at the "source" attribute in a IMG TAG:

http://www.theweb.net/thecaMonitoringWeb/GraficaPie?typeGraph=cmPorcentajeModelos&width=800 &height=500&totalModelos=40&modelo0=DCM245&totalMo delo0=255&modelo1=SB5120&totalModelo1=10&modelo2=D OCSIS+1.1+Touchstone+Cable+Modem+Model+CM450A&tota lModelo2=851&modelo3=EtherFast+Cable+Modem+(BEFCMU 10)&totalModelo3=83&modelo4=ARRIS+DOCSIS+2.0+%2f+P acketCable+1.0+Touchstone+Telephony+Modem+MODEL%3a +TM402G&totalModelo4=224&modelo5=SBG900&totalModel o5=5&modelo6=SB4200&totalModelo6=13&modelo7=Terayo n+TJ%7cECM+715X&totalModelo7=3&modelo8=DOCSIS+1.1+ Touchstone+Cable+Modem+Model+CM300A&totalModelo8=3 78&modelo9=DCM305&totalModelo9=271&modelo10=D-Link+DOCSIS+2.0+Cable+Modem+MODEL%3a+DCM-202&totalModelo10=5&modelo11=PCX2200&totalModelo11 =4&modelo12=SB4100&totalModelo12=9&modelo13=Ambit+ DOCSIS+Cable+Modem+Model%3a+60194E&totalModelo13=1 1&modelo14=DCM235&totalModelo14=55&modelo15=(Gener al+Instrument)+Motorola+SB2100%2fD%2fi&totalModelo 15=1&modelo16=(General+Instrument)+Motorola+SB3100 &totalModelo16=40&modelo17=WebSTAR+Series+DPC2100& totalModelo17=1109&modelo18=ARRIS+DOCSIS+2.0+%2f+P acketCable+1.0+Touchstone+Telephony+Modem+MODEL%3a +TM502G&totalModelo18=362&modelo19=Com21+DOCSIS+1. 0+Cable+Modem+Model%3a+DP111&totalModelo19=1&model o20=CMX2940%2f3CR29210+MCNS+DOCSIS+1.0+external+2-way+Cable+Modem&totalModelo20=35&modelo21=Belkin+M ODEL%3a+F5D5530-W&totalModelo21=1&modelo22=D-Link+DOCSIS+1.1+Cable+Modem+MODEL%3a+DCM-201+(discontinued%2c+replace+with+DC&totalModelo22 =1&modelo23=Modelo+desconocido&totalModelo23=4&mod elo24=Tollgrade+Cheetah+HFC+Service+Assurance&tota lModelo24=1&modelo25=PCX1100U%2fDAZ8813&totalModel o25=4&modelo26=DCM226&totalModelo26=1&modelo27=SB5 101&totalModelo27=5&modelo28=DCM225&totalModelo28= 25&modelo29=SB5100&totalModelo29=10&modelo30=DOCSI S+1.1+Touchstone+Cable+Modem+MODEL+CM550A&totalMod elo30=1386&modelo31=WebSTAR+Series+DPX2100&totalMo delo31=1&modelo32=Com21+Model%3a+DP1110&totalModel o32=21&modelo33=PipeRider+HM200c&totalModelo33=2&m odelo34=PCX2600&totalModelo34=3&modelo35=Thomson+D OCSIS+Cable+Modem+MODEL%3a+DCM315&totalModelo35=20 &modelo36=Thomson+DCM425&totalModelo36=1&modelo37= PCX2500&totalModelo37=1&modelo38=UBR925-K9O3SV9Y5-M&totalModelo38=1&modelo39=ARRIS+DOCSIS+1.1+%2f+Pa cketCable+1.0+Touchstone+Telephony+Modem+MODEL%3a+ TTM202&totalModelo39=2&sumaTotal=5215


IE all current versions (7 included) will truncate and the GET method failures:

http://www.theweb.net/thecaMonitoringWeb/GraficaPie?typeGraph=cmPorcentajeModelos&width=800 &height=500&totalModelos=40&modelo0=DCM245&totalMo delo0=255&modelo1=SB5120&totalModelo1=10&modelo2=D OCSIS+1.1+Touchstone+Cable+Modem+Model+CM450A&tota lModelo2=851&modelo3=EtherFast+Cable+Modem+(BEFCMU 10)&totalModelo3=83&modelo4=ARRIS+DOCSIS+2.0+%2f+P acketCable+1.0+Touchstone+Telephony+Modem+MODEL%3a +TM402G&totalModelo4=224&modelo5=SBG900&totalModel o5=5&modelo6=SB4200&totalModelo6=13&modelo7=Terayo n+TJ%7cECM+715X&totalModelo7=3&modelo8=DOCSIS+1.1+ Touchstone+Cable+Modem+Model+CM300A&totalModelo8=3 78&modelo9=DCM305&totalModelo9=271&modelo10=D-Link+DOCSIS+2.0+Cable+Modem+MODEL%3a+DCM-202&totalModelo10=5&modelo11=PCX2200&totalModelo11 =4&modelo12=SB4100&totalModelo12=9&modelo13=Ambit+ DOCSIS+Cable+Modem+Model%3a+60194E&totalModelo13=1 1&modelo14=DCM235&totalModelo14=55&modelo15=(Gener al+Instrument)+Motorola+SB2100%2fD%2fi&totalModelo 15=1&modelo16=(General+Instrument)+Motorola+SB3100 &totalModelo16=40&modelo17=WebSTAR+Series+DPC2100& totalModelo17=1109&modelo18=ARRIS+DOCSIS+2.0+%2f+P acketCable+1.0+Touchstone+Telephony+Modem+MODEL%3a +TM502G&totalModelo18=362&modelo19=Com21+DOCSIS+1. 0+Cable+Modem+Model%3a+DP111&totalModelo19=1&model o20=CMX2940%2f3CR29210+MCNS+DOCSIS+1.0+external+2-way+Cable+Modem&totalModelo20=35&modelo21=Belkin+M ODEL%3a+F5D5530-W&totalModelo21=1&modelo22=D-Link+DOCSIS+1.1+Cable+Modem+MODEL%3a+DCM-201+(discontinued%2c+replace+with+DC&totalModelo22 =1&modelo23=Modelo+desconocido&totalModelo23=4&mod elo24=Tollgrade+Cheetah+HFC+Service+Assurance&tota lModelo24=1&modelo25=PCX1100U%2fDAZ8813&totalModel o25=4&modelo26=DCM226&totalModelo26=1&modelo27=SB5 101&totalModelo27=5&modelo28=DCM225&totalModelo28= 25&modelo29=SB5100&totalModelo29=10&modelo30=DOCSI S+1.1+Touchstone+Cable+Modem+MODEL+CM550A&totalMod elo30=1386&modelo31=WebSTAR+Series+DPX2100&totalMo delo31=1&modelo32=Com21+Model%3a+DP1110&totalModel o32=21&modelo33=PipeRider+HM200c&totalModelo33=2&m odelo34=PCX2600&totalModelo34=3&modelo35=Thomson+D OCSIS+Cable+Modem+MODEL%3a+DCM315



PROBABLY AJAX, with 'POST' method will solve this.. but I can't found it yet :S
Reply With Quote
  #5 (permalink)  
Old August 7th, 2007, 11:01 AM
Registered User
 
Join Date: Aug 2007
Location: Harrisburg, PA, USA.
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I am having the same problem. you can only send like 2083 characters through the query string which sucks for dynamic image creation.:( Please let me know if anyone knows how to do remote scripting for dynamic images with post variables instead of get.
Right now I may have to actually save the image file on the server instead of just running it in memory.
The only way to load images dynamically that i have found without saving it to the server is to change the src attribute via javascript with your variables in a query string.

Reply With Quote
  #6 (permalink)  
Old August 7th, 2007, 12:57 PM
Registered User
 
Join Date: Aug 2007
Location: Harrisburg, PA, USA.
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Default

oh and btw.. what badcop666 said is very valid. I think darkscripter was assuming that he meant to do it via querystring. The method of passing variables he discussed was to use an ajax post.
I think what he meant was to use an ajax post to a php script which created the image and then saved it to the server like this:

imagejpeg($imageName, 'NameofPic.jpg', 100);

then when the ajax post comes back it would tell the js what "NameofPic.jpg" was. the js would then change the src attribute of the displayed image to "nameofpic.jpg".

This method works very well... but not if your query string is over 2000 characters.

Reply With Quote
  #7 (permalink)  
Old August 8th, 2007, 09:35 AM
Registered User
 
Join Date: Aug 2007
Location: Harrisburg, PA, USA.
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Default

So i've been working on this app all day yesterday and this morning and thought i would share my solution for anyone who needs it. here is my html and javascript:
Code:
<head>
<script language="javascript" type="text/javascript">
function ajaxFunction(){  
    var xmlHttp;
      try{    // Firefox, Opera 8.0+, Safari    
        xmlHttp=new XMLHttpRequest();
    }
      catch (e){    // Internet Explorer    
        try{      
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e){      
            try{
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
              catch (e){
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    xmlHttp.onreadystatechange=function()
      {
      if(xmlHttp.readyState==4)
        {
            document.getElementById("response").innerHTML=xmlHttp.responseText;
            var img = document.createElement('img');
            img.onload = function (e) {
                document.getElementById("imgHolder").width=this.width;
                document.getElementById("imgHolder").height=this.height;
                document.getElementById("imgHolder").src=this.src;
            }
            img.onerror = function(e){
                alert("Error processing Image.  Please try again.")
            }
            img.src = xmlHttp.responseText;
        }
      }
      
    sendVars="tx="+document.forms["myForm"]["txtTxt"].value;
    sendVars+="&fon=ARIAL.TTF";
    sendVars+="&sz="+document.forms["myForm"]["txtSz"].value;
    sendVars+="&fg="+document.forms["myForm"]["txtFG"].value;;
    sendVars+="&bg="+document.forms["myForm"]["txtBG"].value;;

    xmlHttp.open("POST","testAjaxSS.php",true);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //include this for post or it won't work!!!!
    xmlHttp.send(sendVars);  
}
 </script>
</head>
<body>
<form name="myForm">
text: <input type="text" name="txtTxt" /><br/>
size: <input type="text" name="txtSz" /><br/>
fg: <input type="text" name="txtFG" /><br/>
bg: <input type="text" name="txtBG" /><br/>
</form>
<img src="" id="imgHolder"/>
<a href="javascript:ajaxFunction()">Send!</a>
</body>
</html>
then in my php i do this:
Code:
<?php
$id= (WHATEVER ID I GIVE THE IMAGE);
$tx=$_POST["tx"];
$fon=$_POST["fon"];
$sz=$_POST["sz"];
$fg=$_POST["fg"];
$bg=$_POST["bg"];
$pad=0;

$imX=imagettfbbox($sz,0,$fon,$tx); //get bounding box for dimensions
$imDim=imgSize($imX, 0); //run a function to get image size

$im=imagecreate($imDim["w"], $imDim["h"]); //create new image

$bgCol=hex2rgb($bg); //convert bg color from hex to rgb
$bgColor=imagecolorallocate($im,$bgCol['r'],$bgCol['g'],$bgCol['b']); //allocate bg color

$fgCol=hex2rgb($fg); //convert fg color from hex to rgb
$fgColor=imagecolorallocate($im,$fgCol['r'],$fgCol['g'],$fgCol['b']); //allocate fg color

imagettftext ($im, $sz, 0,0, imagesy($im)-$imDim["bl"], $fgColor, $fon, $tx); //print the text

imagejpeg($im,$id.".jpg", 100); //create and save the image
echo $id.".jpg"; //Return Id of pic to javascript

//===============================================================================
function imgSize($bb, $pad){
    //a function to interpret the bounding box info here.

    $imgDim=array("w"=>$w,"h"=>$h,"bl"=>$blOff);
    return($imgDim);
}
function hex2rgb($hex) {
        return array( 'r' => hexdec(substr($hex, 0, 2)), // 1st pair of digits
                      'g' => hexdec(substr($hex, 2, 2)), // 2nd pair
                      'b' => hexdec(substr($hex, 4, 2))  // 3rd pair
                    );
    }


?>
The most important part of the php is the line:
echo $id.".jpg";
since this is what tells the javascript what the image name is.

the most important part of the javascript is this:
sendVars="var1=something&var2=somethingelse";
xmlHttp.open("POST","testAjaxSS.php",true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //include this for post or it won't work!!!!
xmlHttp.send(sendVars);

Note that i didn't include the image dimension function. its just runs a custom function to create a correct bounding box size with offsets for fonts which extend below the baseline, in front of the bounding box and behind it etc. i also didn't include an id for the pic. I just used the session id for it but you should make sure that it is secure if you really use this. Also make sure that you add some error handling since right now it will return an error if any of the fields are blank.
The gd library only lets you have 4500 characters in a imagettf() but that should be more then enough.
Using POST for ajax lets you send an unlimited (????) number of characters to the php script instead of the 2000 max you have with GET.

Hope someone gets some use out of this info. I know it would have saved me a lot of time.
Reply With Quote
  #8 (permalink)  
Old May 27th, 2008, 05:24 PM
Registered User
 
Join Date: May 2008
Location: , , .
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hey dudes, here is a simpler solution using jquery. I tried to get the avobe code working but was unsuccessful. Keep in mind that I have some variables in there that you need to change, as well as whatever you call your php file. Just look at how simple Jquery is! You need to download and include jquery.js in your folder, just google it! Also, you need to include the TTF font files that you refer to in the PHP part, so you'll probably have to change that as well. I think the code is pretty self-explanatory.


HTML File with Script
Code:
<html>
<head>
 <title>Ajax with jQuery Example</title>
 <script type="text/JavaScript" src="jquery.js"></script>
 <script type="text/JavaScript">
 
 
 
 $(document).ready(function(){

$("#generate").click(function() { loadImage(); });

function loadImage(){

    var inputString = $("#inputString").val();

    var inputFont = $("#inputFont option:selected").val();

        $("#image p").load("test2.php?text=" + inputString + "&font=" + inputFont)

}
});

</script>
<style type="text/css">
   #wrapper {
     margin-top: 30px;
     height: 50px;
     width: 600px;
     border: 1px solid black;
     text-align: center;
   }
   #image {
       padding-bottom: 80px;
       border-style: none;
       height: 100px;
       width: 600px;
       text-align: center;
   }
 </style>
</head>
<body>
   <center><div id="image"><p> </p></div>
     <div id="wrapper">
    Engraved Text:<input size="30" id="inputString" type="text" />
    Font:<select id="inputFont">
  <option value="balmo">Balmoral</option>
  <option value="clar">Clarendon</option>
  <option value="curlz">Curlz</option>
  <option value="english">Old English</option>
  <option value="freehand">Freehand</option>
  <option value="greek">Greek</option>
  <option value="interlock">Interlocking Monogram</option>
  <option value="times">Times</option>

<!--   
 <option value="3">Cool Engraving</option>
 <option value="3">Cool Engraving</option>
 <option value="3">Cool Engraving</option>
 <option value="3">Cool Engraving</option>
 <option value="3">Cool Engraving</option>
-->
    </select>
    <input type="submit" id="generate" value="Generate!">
 </div>
</center>
</body>
</html>
PHP

Code:
<?php

// VARIABLES   ############################################################################

// The text to draw
$text = $_GET['text'];
//$text = 'poopie';

// Font File, don't need a slash if file is in same dir as php file
$font = $_GET['font'];
//$font = '1';

//size in PTS
$size = 78;

//Angle
$angle = 0;

//Width of Canvas
$width = 500;

//Height of Canvas
$height = 200;

//Text Bounding Box Dimensions
$tb = imagettfbbox($size, $angle, $font, $text);

/*
Output of imagettfbbox is an array as follows:

Array
(
    [0] => 0 // lower left X coordinate
    [1] => -1 // lower left Y coordinate
    [2] => 198 // lower right X coordinate
    [3] => -1 // lower right Y coordinate
    [4] => 198 // upper right X coordinate
    [5] => -20 // upper right Y coordinate
    [6] => 0 // upper left X coordinate
    [7] => -20 // upper left Y coordinate
)
*/

// Centering Function  #####################################################################

// X Position Calculated by subtracting width of Text Bounding Box from total canvas width
$posx = ceil(($width - $tb[2]) / 2);

// Y Position Calculated by subtracting height of Text Bounding Box from total canvas height
$posy = ceil(($height - $tb[5]) / 2);

// Creating Image File
$im = imagecreatetruecolor($width, $height);

// State Colors available to Image File
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);

imagefilledrectangle($im, 0, $angle, $width, $height, $white);

// Add the text
imagettftext($im, $size, $angle, $posx, $posy, $black, $font, $text);
 
// Usage of imagettftext()
// array imagettftext  ( resource $image  , float $size  , float $angle  , int $x  , int $y  , int $color  , string $fontfile  , string $text  ) //

$file= "$text+$font.png";

imagepng($im, "img/$file");
imagedestroy($im);

$imgloc= "img/$file";

echo "<img src=$imgloc>";

?>
www.sleepyjack.com
Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Ajax to download images in order? BostonMark Ajax 0 May 29th, 2008 08:49 PM
dynamic scripting with AJAX pegasus51 Ajax 0 September 19th, 2006 11:07 AM
Dynamic Images & Go To Detail Page malhyp Dreamweaver (all versions) 1 January 27th, 2006 06:10 AM
dynamic search, images from database , hyperlinks ishh_sh VB How-To 0 December 15th, 2004 08:10 AM
Creating Dynamic Images mvollmer Classic ASP Basics 0 March 4th, 2004 01:31 PM



All times are GMT -4. The time now is 05:57 PM.


Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.