[英]resize image respecting a min width / height and max width / height in javascript
[英]Resize image have user set width or height javascript calculate and fill width or height
我已经在网上搜寻过,发现只有部分解决方案能够解决大部分不完整的问题。
我希望用户能够将图像重新缩放到选定的尺寸。 这将使用带有2个文本框的窗体,其中一个文本框表示宽度,一个文本框表示高度。
可以说图像为1000Wx2000H,用户想要缩放到100Wx200H,这很容易,但是如果他想缩放到125W x A,其中A是“高度”的未知值。 因此,用户将在宽度文本框中输入125,而javascript将计算出H文本框,反之亦然,用户将填写高度和宽度。
也有一个忽略宽高比复选框的超级好,它会自行选择宽度和高度!
我可以很容易地用PHP获取图像尺寸,实际上,我需要将结果发布回页面,以便用php将其发送给imagemagick。
我想我不是第一个想要这样的东西的人,但没有找到对搜索有用的东西。
我并没有声称自己是JS专家,但是有时这是必要的。 另一方面,PHP似乎更自然。
为了使其有效,我们必须首先计算实际图像的纵横比,然后根据给定值计算width
或height
。 我们可以利用Image
元素的naturalHeight
和naturalHeight
属性来计算纵横比。
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
从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中。 但是,我看到其他人也有同样的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.