【发布时间】:2014-07-30 00:16:35
【问题描述】:
这可能是一个非常愚蠢的问题。我让用户在使用 imgAreaSelect jQuery 插件上传时裁剪自己的照片。正如许多用户在这里和其他地方发现的那样,当使用 CSS 调整大小时,裁剪部分未被正确选择。值得庆幸的是,imgAreaSelect 可以使用 imageHeight 和 imageWidth 来处理这个问题。这里已经有一个答案让我开始了。可悲的是,我还不能在那里发表评论。
我的问题是找到附加图像的真实高度和宽度。我尝试了各种获取它的方法,但每次控制台输出未定义 originalHeight/originalWidth 时,如下所示。
第一个,这是在这里找到的解决方案,是:
var imageSize = $("#uploadImage");
var originalHeight = imageSize.naturalHeight;
var originalWidth = imageSize.naturalWidth;
第二个是this.width/this.height,可在此处找到:stackoverflow.com/questions/318630:
var imageSize = $("uploadImage")[0];
var originalWidth, originalHeight;
$("<img/>")
.attr("src", $(imageSize).attr("src"))
.load(function() {
originalWidth = this.width;
originalHeight = this.height;
});
我将我的完整代码放在下面,因为我可能只是完全错过了一些东西,因为我显然是一个初学者。图像在预览和裁剪中显示,只是不正确。
function getCoordinates(img, selection) {
var porcX = img.naturalWidth / img.width;
var porcY = img.naturalHeight / img.height;
$('#x1').val(Math.round(selection.x1 * porcX));
$('#y1').val(Math.round(selection.y1 * porcY));
$('#x2').val(Math.round(selection.x2 * porcX));
$('#y2').val(Math.round(selection.y2 * porcY));
$('#w').val(Math.round(selection.width * porcX));
$('#h').val(Math.round(selection.height * porcY));
}
$(document).ready(function() {
var preview = $("#uploadPreview");
$("#uploadImage").change(function(){
preview.fadeOut();
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
preview.attr('src', oFREvent.target.result).fadeIn();
};
});
var imageSize = $("#uploadImage");
var originalHeight = imageSize.naturalHeight;
var originalWidth = imageSize.naturalWidth;
$('#uploadPreview').imgAreaSelect({
aspectRatio: '24:29',
handles: true,
fadeSpeed: 200,
imageHeight: originalHeight,
imageWidth: originalWidth,
onSelectChange: getCoordinates
});
});
【问题讨论】:
-
您可能希望将
$(document).ready(function() {替换为$(window).load(function() { -
感谢您的回复@user3558931。虽然结果相同。就绪/加载不会对获取图像宽度/高度产生影响。至少我不这么认为
-
哪个是哪个?结果相同还是您不这么认为?
-
看起来只是imgAreaSelect和max-width。除非我先调整图像大小,否则这似乎不起作用。