调整图片大小可让用户设置宽度或高度,javascript计算并填充宽度或高度

时间:2019-03-03 06:06:09

标签: javascript image-processing

我已经在网上搜寻并发现了部分解决方案,但大部分都不完整。

我希望用户能够将图像重新缩放到选定的尺寸。这将使用带有2个文本框的表单,其中一个文本框表示宽度,一个文本框表示高度。

可以说图像为1000Wx2000H,用户想将其缩放到100Wx200H,这很容易,但是如果他想缩放到125W x A,其中A是“高度”的未知值。因此,用户将在宽度文本框中输入125,而javascript将计算出H文本框,反之亦然,则用户会计算高度和宽度。

也非常有一个忽略宽高比的复选框,可以选择宽度和高度来选择自身!

我可以很容易地用PHP获取图像尺寸变化,实际上我需要将结果发布回页面,以php格式将其发送给imagemagick。

我想我不是第一个想要这样的东西的人,但没有找到对搜索有用的东西。

我并没有声称自己是JS专家,但是有时这是必要的。另一方面,PHP似乎更自然。

2 个答案:

答案 0 :(得分:0)

为了使其有效,我们必须首先计算实际图像的纵横比,然后根据给定值计算widthheight。我们可以利用naturalHeight元素的naturalHeightImage属性来计算纵横比。

let naturalHeight = $img.naturalHeight;
let naturalWidth = $img.naturalWidth;
let aspectRatio = naturalHeight/naturalWidth;

let height = width*aspectRatio;
$heightInput.value = height;

以上解决方案将基于给定的宽度值计算高度。这是完整的解决方案-

<input type="number" id="h" placeholder="Enter height..." onblur="calculateWidth(this.value)">

<input type="number" id="w" placeholder="Enter width..." onblur="calculateHeight(this.value)">


<button onclick="apply()">
  Apply
</button>

<p>
<img id="img" src="https://images.pexels.com/photos/707194/pexels-photo-707194.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260">
</p>
let $img = document.getElementById('img');
let $heightInput = document.getElementById('h');
let $widthInput = document.getElementById('w');

function calculateHeight(width){
  let naturalHeight = $img.naturalHeight;
  let naturalWidth = $img.naturalWidth;
  let aspectRatio = naturalHeight/naturalWidth;

  let height = width*aspectRatio;
  $heightInput.value = height;
}

function calculateWidth(height){
  let naturalHeight = $img.naturalHeight;
  let naturalWidth = $img.naturalWidth;
  let aspectRatio = naturalWidth/naturalHeight;

  let width = height*aspectRatio;
  $widthInput.value = width;
}

function apply(){

  let height = $heightInput.value;
  let width = $widthInput.value;

  if(height > 0){
    $img.style.height = `${height}px`;
  } else {
    $img.style.height = `auto`;
  }

  if(width > 0){
    $img.style.width = `${width}px`;
  } else {
    $img.style.width = `auto`;
  }
}

现场直播-https://jsitor.com/tFBo8_F1V

答案 1 :(得分:0)

根据Ashvin777的帖子进行工作

更改为

$("#crop_x").val(Math.round(cropbox.x));
$("#crop_y").val(Math.round(cropbox.y));
$("#width").val(Math.round(cropbox.w));
$("#height").val(Math.round(cropbox.h));

我还发现我不需要JavaScript POST或任何特殊的东西。普通的HTML POST完美地传递了jcrop的变量

我还添加了高度和宽度大小(我将它们设置为PHP变量,然后如果我希望可以为每个图像计算它们并从php设置它们)

$(function() {
    $('#cropbox').Jcrop({ boxWidth: <?php echo $boxwidth;?>, boxHeight: <?php echo $boxheight;?> });
});

用户已经可以覆盖计算出的外观。如果用户设置了宽度和高度,则可以覆盖高度,因此我选择始终使用“!”忽略imagemagick中的Aspect选项,因为javascript已经在计算正确的宽高比,因此可以覆盖它,并且用户看到的值正是最终图像中出现的值。

我看到的唯一问题是,如果我在第一次加载时将图像加载到jcrop中就可以了。但是在紧接的后续加载中,有时我会看到两个图像,首先是原始大小,然后是设置大小。如果我在第二次或第三次加载之间加载另一张图像,问题就消失了。听起来有些东西没有清除或冲洗掉。这种情况发生在Chrome和Firefox中。但是,我看到其他人也有同样的问题。

相关问题