Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 12 of 12
  1. #1
    New to the CF scene
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Javascript display image

    Hello,

    First, I'm new to the Javascript (and to this forum).

    I am trying to use a Javascript to display a randomly selected image located in a folder of my site. I need to fit these images (which may have quite diverse dimensions) into a frame of 280x280 px.

    Here is the code of the current script which does not currently work:
    Code:
    // JavaScript Document
    <script language="JavaScript"><!--
    
    
    function random_imglink(){
      var myimages=new Array()
      var imagetitle=new Array()
    urlimage="http://www.mysite.fr/Images/RandomPictures/"
    
    
    var i=0
    //specify here the total number of random images which should be names 1.jpg, 2.jpg etc
    nbrandompic=140
    for (i=0;i<= nbrandompic;i++)
       {
      myimages[i]=urlimage + i +".jpg"
      imagetitle[i]=urlimage + i +".txt"
       }
    
      
    //Randomly select an image
    
      var ry=Math.floor(Math.random()*myimages.length)
    
      if (ry==0)
         ry=1
      var reduction = 1
      var maxWidth=280
      var maxHeight=280
    
    //Calculate the reduction that should be applied
    
    
             if(myimages[ry].width > maxWidth || image.height > maxHeight)
                reduction = Math.max(myimages[ry].width/maxWidth,myimages[ry].height/maxHeight)
     
     // New dimensions     
          iw = Math.round(myimages[ry].width / reduction)
          ih = Math.round(myimages[ry].height / reduction)
    	 
    
    //Display image	 
    	 
        document.write('<a><img src="'myimages[ry]'" title="" border=0 width='+iw+' height='+ih+'></a>')
    	
    
    }
    
      random_imglink()
     
    
    //-->
    </script>
    I am sure that you guys can help me solve this problem. Many thanks in advance!!

    Antonino

  • #2
    Regular Coder
    Join Date
    Mar 2011
    Posts
    148
    Thanks
    0
    Thanked 20 Times in 20 Posts
    At this line code is missing the +
    document.write('<a><img src="' + myimages[ry] + '" title="" border=0 width='+iw+' height='+ih+'></a>')
    but i'm not shure bthat was the main problem.

  • #3
    New to the CF scene
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by MarPlo View Post
    At this line code is missing the +
    document.write('<a><img src="' + myimages[ry] + '" title="" border=0 width='+iw+' height='+ih+'></a>')
    but i'm not shure bthat was the main problem.
    Even with the missing '+', this is still not working :-(

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    You can't get the width and height of an image until it has actually been loaded into the browser.

    You *certainly* can't do this:
    Code:
    myimages[i]=urlimage + i +".jpg"
    ...
    myimages[ry].width ...
    ALL of those array elements are NOTHING BUT STRINGS. None of them have a ".width" property. (Even if they did, it would be the width of the string, not the width of any image.)

    So...

    So your code is both overly complicated and non-working.

    Here's one way to do it:
    Code:
    <html>
    <head>
    <script type="text/javascript">
    function fixImage( image )
    {
        var show = document.getElementById("showImage");
        if ( image.height > image.width )
        {
            show.style.height = "280px";
            show.style.width = Math.round( (image.width / image.height) * 280 ) + "px";
        } else {
            show.style.width = "280px";
            show.style.height = Math.round( (image.height / image.width) * 280 ) + "px";
        }
        show.src = image.src;
        show.style.visibility = "visible";
    }
    </script>
    </head>
    <body>
    ...
         <img id="showImage" style="height: 280px; width: 280px; visibility: hidden;"/>
    ...
    <script style="text/javascript">
    var MAXPICTURENUMBER = 140; // or whatever you choose
    var rn = 1 + Math.floor( MAXPICTURENUMBER * Math.random() );
    var url ="http://www.mysite.fr/Images/RandomPictures/" + rn + ".jpg";
    
    document.write( '<img src="' + url + '" style="position: absolute; top: 0px; left: 0px; visibility: hidden;" onload="fixImage(this)" />' );
    </script>
    I don't happen to have something to test that with right now, but I think it's right.

    The "trick" is to load a full-size image into a hidden <img> on the page and then, when it is loaded, it copies itself to a properly sized image that is not hidden.

    We use visibility: hidden; instead of display: none; because images with display:none do not *have* any height or width so you can't discover it.

    The full size image is positioned at 0,0 on the page because it's never going to be made visible and that's the least likely position to be obtrusive.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Totoleheros (03-20-2011)

  • #5
    Banned
    Join Date
    Feb 2011
    Posts
    2,699
    Thanks
    13
    Thanked 395 Times in 395 Posts
    Maybe use this demo as a guide.

    When you click the button, a random pic from picData is displayed.

    The random pic is resized to fit within a box of imgMaxWidth and imgMaxHeightt while maintaining the image's original aspect ratio.

    The images are also preloaded.
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title></title>
            <script type="text/javascript">
                var imgMaxWidth = 280;
                var imgMaxHeightt = 280;
                //preload the images
                var picData = ['num1.jpg','num2.jpg','num3.jpg','num4.jpg','num5.jpg'];
                picO = new Array();
                for(i=0; i < picData.length; i++){
                    picO[i] = new Image();
                    picO[i].src = picData[i];
                }
                var curPic = -99;
                function showRandomPic(){
                    var newPicNum = Math.floor(Math.random()*picData.length);
                    while(newPicNum == curPic){
                        newPicNum = Math.floor(Math.random()*picData.length);
                    }
                    curPic = newPicNum;
                    var newDims = calcNewDimensions(picO[curPic].width, picO[curPic].height, imgMaxWidth, imgMaxHeightt);
                    oImg.width = newDims['width'];
                    oImg.height = newDims['height'];
                    oImg.src = picO[curPic].src
                }
                window.onload=function(){
                    oImg = document.getElementById('imgContainer');
                    document.getElementById('btnRandPic').onclick=showRandomPic;
                    showRandomPic();
                }
                //-------------------------------------------
                function calcNewDimensions(width, height, maxWidth, maxHeight){
                    newDims = new Array();
                    var xRatio = maxWidth / width;
                    var yRatio = maxHeight / height;
                    //calculate the new width and height
                    if(width <= maxWidth && height <= maxHeight)  {    //image does not need resizing
                        newDims["width"]     = width;
                        newDims["height"]     = height;
                    } else if(xRatio * height < maxHeight) {
                        newDims["height"] = Math.round(xRatio * height);
                        newDims["width"]  = maxWidth;
                    } else {
                        newDims["width"]  = Math.round(yRatio * width);
                        newDims["height"] = maxHeight;
                    }
                    return newDims;
                }
            </script>
        </head>
        <body>
            <div>
                <img id="imgContainer" src="" alt="" />
            </div>
            <div>
                <button id="btnRandPic">Show random pic</button>
            </div>
        </body>
    </html>

  • Users who have thanked bullant for this post:

    Totoleheros (03-20-2011)

  • #6
    New to the CF scene
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    You can't get the width and height of an image until it has actually been loaded into the browser.

    You *certainly* can't do this:
    Code:
    myimages[i]=urlimage + i +".jpg"
    ...
    myimages[ry].width ...
    ALL of those array elements are NOTHING BUT STRINGS. None of them have a ".width" property. (Even if they did, it would be the width of the string, not the width of any image.)

    So...

    So your code is both overly complicated and non-working.

    Here's one way to do it:
    Code:
    <html>
    <head>
    <script type="text/javascript">
    function fixImage( image )
    {
        var show = document.getElementById("showImage");
        if ( image.height > image.width )
        {
            show.style.height = "280px";
            show.style.width = Math.round( (image.width / image.height) * 280 ) + "px";
        } else {
            show.style.width = "280px";
            show.style.height = Math.round( (image.height / image.width) * 280 ) + "px";
        }
        show.src = image.src;
        show.style.visibility = "visible";
    }
    </script>
    </head>
    <body>
    ...
         <img id="showImage" style="height: 280px; width: 280px; visibility: hidden;"/>
    ...
    <script style="text/javascript">
    var MAXPICTURENUMBER = 140; // or whatever you choose
    var rn = 1 + Math.floor( MAXPICTURENUMBER * Math.random() );
    var url ="http://www.mysite.fr/Images/RandomPictures/" + rn + ".jpg";
    
    document.write( '<img src="' + url + '" style="position: absolute; top: 0px; left: 0px; visibility: hidden;" onload="fixImage(this)" />' );
    </script>
    I don't happen to have something to test that with right now, but I think it's right.

    The "trick" is to load a full-size image into a hidden <img> on the page and then, when it is loaded, it copies itself to a properly sized image that is not hidden.

    We use visibility: hidden; instead of display: none; because images with display:none do not *have* any height or width so you can't discover it.

    The full size image is positioned at 0,0 on the page because it's never going to be made visible and that's the least likely position to be obtrusive.
    Old Pedant, many many thanks, this is exactly what I needed!! May I ask you an additional help? I'd like to overlay at the bottom of the image a caption text that is stored in a text file the name of which is paired with the image name. 1.jpg <-> 1.txt; 2.jpg <-> 2.txt etc. The variable is named 'caption'.

    My code is now as follows:

    Code:
    <div align=" center" >
    <img id="showImage" style="height: 240px; width: 260px; visibility: hidden;"/>
    </div>
    
    <script language="JavaScript"><!--
    
    var MAXPICTURENUMBER = 140; // or whatever you choose
    var rn = 1 + Math.floor( MAXPICTURENUMBER * Math.random() );
    var url ="http://www.u698.fr/Images/RandomPictures/" + rn + ".jpg";
    
    var caption ="http://www.mysite.fr/Images/RandomPictures/" + rn + ".txt";
    
    document.write( '<img src="' + url + '" style="position: absolute; top: 0px; left: 0px; visibility: hidden;" onload="fixImage(this)" />' );
    
    document.write('<iframe name="textfram"  border="0" width="280" height="50" frameborder="0" scrolling="no" class="iframe" src="'+caption+'">');
    
    //-->
    </script>
    The problem is that with solution, the text is below the image, not on an overlay. I would love to have this caption in a semi-transparent grey-color frame floating over the bottom of the image. Once again, many thanks for your help and I will greatly appreciate for further help!!

    Antonino

  • #7
    New to the CF scene
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by bullant View Post
    Maybe use this demo as a guide.

    When you click the button, a random pic from picData is displayed.

    The random pic is resized to fit within a box of imgMaxWidth and imgMaxHeightt while maintaining the image's original aspect ratio.

    The images are also preloaded.
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <title></title>
            <script type="text/javascript">
                var imgMaxWidth = 280;
                var imgMaxHeightt = 280;
                //preload the images
                var picData = ['num1.jpg','num2.jpg','num3.jpg','num4.jpg','num5.jpg'];
                picO = new Array();
                for(i=0; i < picData.length; i++){
                    picO[i] = new Image();
                    picO[i].src = picData[i];
                }
                var curPic = -99;
                function showRandomPic(){
                    var newPicNum = Math.floor(Math.random()*picData.length);
                    while(newPicNum == curPic){
                        newPicNum = Math.floor(Math.random()*picData.length);
                    }
                    curPic = newPicNum;
                    var newDims = calcNewDimensions(picO[curPic].width, picO[curPic].height, imgMaxWidth, imgMaxHeightt);
                    oImg.width = newDims['width'];
                    oImg.height = newDims['height'];
                    oImg.src = picO[curPic].src
                }
                window.onload=function(){
                    oImg = document.getElementById('imgContainer');
                    document.getElementById('btnRandPic').onclick=showRandomPic;
                    showRandomPic();
                }
                //-------------------------------------------
                function calcNewDimensions(width, height, maxWidth, maxHeight){
                    newDims = new Array();
                    var xRatio = maxWidth / width;
                    var yRatio = maxHeight / height;
                    //calculate the new width and height
                    if(width <= maxWidth && height <= maxHeight)  {    //image does not need resizing
                        newDims["width"]     = width;
                        newDims["height"]     = height;
                    } else if(xRatio * height < maxHeight) {
                        newDims["height"] = Math.round(xRatio * height);
                        newDims["width"]  = maxWidth;
                    } else {
                        newDims["width"]  = Math.round(yRatio * width);
                        newDims["height"] = maxHeight;
                    }
                    return newDims;
                }
            </script>
        </head>
        <body>
            <div>
                <img id="imgContainer" src="" alt="" />
            </div>
            <div>
                <button id="btnRandPic">Show random pic</button>
            </div>
        </body>
    </html>
    Bullant,

    Many thanks for your reply. I have started with the solution of Old Pedant that has posted before you and it worked perfectly. I'm sure that your solution would be OK too...

    Best regards,

    Antonino
    Last edited by Totoleheros; 03-20-2011 at 04:22 PM.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Hmmm...completely untested, but I would think something like this would work:
    Code:
    <div align=" center" style="position: relative;">
    <img id="showImage" 
             style="position: absolute; top: 0px; left: 0px; height: 240px; width: 260px; visibility: hidden; z-index: 1;"/>
    <iframe id="textframe" frameborder="0" scrolling="no" 
      style="position: absolute; top: 190px; left: 0px; border: none; width: 280px; height: 50px; z-index: 10;">
    </iframe> 
    </div>
    
    <script type="text/javascript">
    var MAXPICTURENUMBER = 140; // or whatever you choose
    var rn = 1 + Math.floor( MAXPICTURENUMBER * Math.random() );
    var url ="http://www.u698.fr/Images/RandomPictures/" + rn + ".jpg";
    
    var caption ="http://www.mysite.fr/Images/RandomPictures/" + rn + ".txt";
    
    document.getElementById("textFrame").src = caption;
    
    document.write( '<img src="' + url + '" style="position: absolute; top: 0px; left: 0px; visibility: hidden;" onload="fixImage(this)" />' );
    </script>
    You see it? By positioning the "wrapper" <div> that is around the img and iframe as "position: relative", then the "position: absolute" of the img and iframe are relative to that <div>. So we can indeed position the iframe on top of the bottom part of the img.

    Addenda: Just tried it on a static page and it worked great.

    Note: <script language=".."> is obsolete. Stop using it. Use <script type="text/javascript">

    Note: The need to use <!--- and //--> in <script> blocks became unnecessary when MS released MSIE...back in 1997. If you see code using those, it indicates that it is such ancient code that you probably should avoid it. (Does not apply to the use of CDATA and similar tag usage which is needed with XHTML pages.)
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Banned
    Join Date
    Feb 2011
    Posts
    2,699
    Thanks
    13
    Thanked 395 Times in 395 Posts
    Quote Originally Posted by Totoleheros View Post
    Bullant,

    Many thanks for your reply. I have started with the solution of Old Pedant that has posted before you and it worked perfectly. I'm sure that your solution would be OK too...

    Best regards,

    Antonino
    No problem

    Just use what works best for you.

  • #10
    New to the CF scene
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    Hmmm...completely untested, but I would think something like this would work:
    Code:
    <div align=" center" style="position: relative;">
    <img id="showImage" 
             style="position: absolute; top: 0px; left: 0px; height: 240px; width: 260px; visibility: hidden; z-index: 1;"/>
    <iframe id="textframe" frameborder="0" scrolling="no" 
      style="position: absolute; top: 190px; left: 0px; border: none; width: 280px; height: 50px; z-index: 10;">
    </iframe> 
    </div>
    
    <script type="text/javascript">
    var MAXPICTURENUMBER = 140; // or whatever you choose
    var rn = 1 + Math.floor( MAXPICTURENUMBER * Math.random() );
    var url ="http://www.u698.fr/Images/RandomPictures/" + rn + ".jpg";
    
    var caption ="http://www.mysite.fr/Images/RandomPictures/" + rn + ".txt";
    
    document.getElementById("textFrame").src = caption;
    
    document.write( '<img src="' + url + '" style="position: absolute; top: 0px; left: 0px; visibility: hidden;" onload="fixImage(this)" />' );
    </script>
    You see it? By positioning the "wrapper" <div> that is around the img and iframe as "position: relative", then the "position: absolute" of the img and iframe are relative to that <div>. So we can indeed position the iframe on top of the bottom part of the img.

    Addenda: Just tried it on a static page and it worked great.

    Note: <script language=".."> is obsolete. Stop using it. Use <script type="text/javascript">

    Note: The need to use <!--- and //--> in <script> blocks became unnecessary when MS released MSIE...back in 1997. If you see code using those, it indicates that it is such ancient code that you probably should avoid it. (Does not apply to the use of CDATA and similar tag usage which is needed with XHTML pages.)
    Thank you so much. It is almost as in my dreams. How do you apply formatting to the text displayed in the iframe? I have tried all day long to apply a style without any success??? Can you call a CSS style?

  • #11
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,020
    Thanks
    75
    Thanked 4,323 Times in 4,289 Posts
    Ahhh...with a lot of difficulty.

    So if you really need to do that, I wouldn't do it like this, at all.

    Instead, I'd read the text file using JavaScript and plop it into a <div>.

    Here's a start at it. I see you changed your image to be non-square, so I assume you also changed my "fixImage()" function. I'll leave that to you to muck with.
    Code:
    <html>
    <head>
    <script type="text/javascript">
    function fixImage( image )
    {
        // change calculations to match your needs
        var show = document.getElementById("showImage");
        if ( image.height > image.width )
        {
            show.style.height = "260px";
            show.style.width = Math.round( (image.width / image.height) * 260 ) + "px";
        } else {
            show.style.width = "260px";
            show.style.height = Math.round( (image.height / image.width) * 260 ) + "px";
        }
        show.src = image.src;
        show.style.visibility = "visible";
    }
    
    var MAXPICTURENUMBER = 140; // or whatever you choose
    var rn = 1 + Math.floor( MAXPICTURENUMBER * Math.random() );
    var url ="http://www.mysite.fr/Images/RandomPictures/" + rn + ".jpg";
    var caption ="http://www.mysite.fr/Images/RandomPictures/" + rn + ".txt";
    
    var xmlhttp;
    if (window.XMLHttpRequest)
    {   
       xmlhttp = new XMLHttpRequest();
    } else { 
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open( "GET", caption, false );
    xmlhttp.send( );
    captionText = xmlhttp.responseText;
    
    window.onload = 
       function() { 
          document.getElementById("fullSize").src = url;
          document.getElementById("theCaption").innerHTML = captionText;
    }
    
    </script>
    
    <style type="text/css">
    div#HOLDER { 
        position: relative;
    }
    img#showImage {
        position: absolute; 
        top: 0px; left: 0px; 
        height: 260px; width: 260px; 
        visibility: hidden; 
        z-index: 1;
    }
    div#theCaption {
        position: absolute; 
        top: 210px; left: 0px; 
        border: none; 
        width: 260px; height: 50px; 
        background-color: #eeeeee; color: red;
        overflow: hidden;
        font-size: large; font-family: arial; font-weight: bold;
        z-index: 10;
    }
    img#fullSize {
        position: absolute; 
        top: 0px; left: 0px; 
        visibility: hidden;
    }
    </style>
    </head>
    <body>
    <img id="fullSize" onload="fixImage(this)" />
    <div id="HOLDER">
        <img id="showImage" alt="my image" />
        <div id="theCaption"></div>
    </div>
    
    </body>
    </html>
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    Totoleheros (03-22-2011)

  • #12
    New to the CF scene
    Join Date
    Mar 2011
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Smile

    Dear Old Pedant,

    Thank you so much, your help has been really great and your solution fits perfectly my need. I just have to struggle a little bit more with CSS styles to adapt them to my site. Many many thanks!!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •