Hello! I have a form, and in it a button:

<input type="image" src="<?=$a_img_s?>"> 

Every time I load different url images into it. I need this image to always fit proportionally in width:200 , height:300 . That is, it may be less, but cannot exceed these values. The image should not be distorted, that is, you can not just determine the values ​​of width and height .

I tried to do this:

 <input type="image" src="<?=$a_img_s?>"><?if(imagesy($a_img_s)>300){return "height=300;";}?>> 

However, this did not work, and not at all in proportion. Images may have more height and width. Help something. Thank :)

    2 answers 2

    I recommend to do this through JS. Arguments:

    1. It will take a lot of time to output a page with hundreds of such pictures, because for this you need at least a request to the server for the pictures
    2. Without caching, this is wrong ideologically, although this is an extension of 1 point.
    3. In JS there is img.onload, which solves this problem, imho, better.

    Here is my option (debugged, working)

     <script type="text/javascript"> function correctImageSize(img) { var was = { w: img.offsetWidth, h: img.offsetHeight } var max = { w: 300, h: 200 } if (!was.w || !was.h) return false; // anti DBZ var rK = { w: max.w/was.w, h: max.h/was.h } var resizeK = (rK.w > rK.h) ? rK.h : rK.w; img.width = Math.floor(resizeK * was.w); img.height = Math.floor(resizeK * was.h); return true; } </script> <div style="width: 300px;height: 200px;border: #0f0 1px dashed;text-align: center;"> <img src="http://www.google.ru/images/nav_logo89.png" onload="correctImageSize(this);" /> </div> 
       <? function insertScales($imgx,$imgy,$maxx=200,$maxy=300){ if($imgy<=0 || $maxy<=0 || $imgx<=0 || $maxx<=0){ return; } $ratio = $imgx/$imgy; if($ratio>($maxx/$maxy)){ if($imgx>$maxx){ $imgx = $maxx; $imgy = $imgx/$ratio; } }else{ if($imgy>$maxy){ $imgy = $maxy; $imgx = $imgy*$ratio; } } return 'width="'.$imgx.'px" height="'.$imgy.'px"'; } ?> <input type="image" src="<?=$a_img_s?>" <?=insertScales(imagesx(imagecreatefromjpg($a_img_s)),imagesy(imagecreatefromjpg($a_img_s)))?> /> 
      • When calling the error function (Warning: imagesx () expects parameter 1, there is a resource, the string is given in z: \ home \ elo \ www \ form.php on line 74 Z: \ home \ elo \ www \ form.php on line 74 "/> line 74, this is the same input - JL
      • imagesy (imagecreatefromjpg ($ a_img_s)) - so try. Strange what worked for you - knes
      • and imagecreatefromjpg does the URL work? o_O - Sh4dow
      • Fatal error: Call to undefined function imagecreatefromjpg () something is not installed? - JL
      • To determine if GD is supported, execute the following script! <? php if (function_exists ('imagetypes')) echo 'GD supports'; else echo 'GD does not support'; ?> - Palmervan