Fit the size of a remote image

Hello! I have a form with a button:

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

Each time I load a different image into it by url. I want this image to always fit proportionally into width:200, height:300.
That is, it can be less, but cannot exceed these values. The image must not be distorted, that is, you cannot simply define the widthand heightvalues.

I tried this:

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

It didn’t work, though, and it’s not proportionate at all. Images can have more than both heightand width.Please help. Thank you 🙂

Answer 1, authority 100%

function insertScales($imgx,$imgy,$maxx=200,$maxy=300){
if($imgy<=0 || $maxy<=0 || $imgx<=0 || $maxx<=0){
$ratio = $imgx/$imgy;
    $imgx = $maxx;
    $imgy = $imgx/$ratio;
    $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)))?> />

Answer 2

I recommend doing this via JS. Arguments:

  1. It will take a lot of time to display a page with hundreds of such images, because this requires at least a request to the image server
  2. Without caching, this is conceptually wrong, although it is a 1 point extension
  3. JS has img.onload, which will solve this problem, IMHO, better.

Here is my version (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;
<div style="width: 300px;height: 200px;border: #0f0 1px dashed;text-align: center;">
<img src="" onload="correctImageSize(this);" />