我想知道一旦选择了照片文件,如何使imgareaselect自动进行选择?以便用户知道到目前为止,我可以对照片中的内容进行裁剪:
我要实现的是,当我选择图像文件时,要使imgareaselect自动选择照片的一部分。
imgareaselect文档:http://odyniec.net/projects/imgareaselect/usage.html
jQuery代码:
// set info for cropping image using hidden fields
function setInfo(i, e) {
// Get on screen image
var screenImage = $("#uploadPreview");
// Create new offscreen image to test
var theImage = new Image();
theImage.src = screenImage.attr("src");
// Get accurate measurements from that.
var imageWidth = theImage.width;
//Get width of resized image
var scaledimagewidth = document.getElementById("uploadPreview").width;
if ( imageWidth > scaledimagewidth){ var ar = imageWidth/scaledimagewidth;}
else { var ar = 1;}
$('#x').val(e.x1*ar);
$('#y').val(e.y1*ar);
$('#w').val(e.width*ar);
$('#h').val(e.height*ar);
}
$(document).ready(function () {
var p = $("#uploadPreview");
// prepare instant preview
$("#uploadImage").change(function () {
// fadeOut or hide preview
p.fadeOut();
// prepare HTML5 FileReader
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var image = new Image();
image.src = oFREvent.target.result;
image.onload = function () {
if ((this.width >= 4500) || (this.height >= 4500)) {
alert("Picture Has to Be Lower Than 4500 by 4500, choose another file");
}
else {
p.attr('src', oFREvent.target.result).fadeIn();
}
// access image size here & do further implementation
};
};
});
// implement imgAreaSelect plug in (http://odyniec.net/projects/imgareaselect/)
$('img#uploadPreview').imgAreaSelect({
aspectRatio: '1.33:1',
onSelectEnd: setInfo
});
});
HTML标记:
<div class="wrap">
<!-- image preview area-->
<img id="uploadPreview" style="display:none;"/>
<!-- image uploading form -->
<form action="upload.php" method="post" enctype="multipart/form-data">
<input id="uploadImage" type="file" accept="image/jpeg" name="image" />
<input type="submit" value="Upload">
<!-- hidden inputs -->
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
</form>
</div>
最佳答案
这个答案似乎通过(jQuery imgAreaSelect set initial selection with aspect ratio)起作用
// adds an image area select instance
function addImgAreaSelect( img ){
img.addClass( 'imgAreaSelect' ).imgAreaSelect({
handles : true,
aspectRatio : '16:9',
fadeSpeed : 1,
show : true
});
img.load(function(){ // display initial image selection 16:9
var height = ( this.width / 16 ) * 9;
if( height <= this.height ){
var diff = ( this.height - height ) / 2;
var coords = { x1 : 0, y1 : diff, x2 : this.width, y2 : height + diff };
}
else{ // if new height out of bounds, scale width instead
var width = ( this.height / 9 ) * 16;
var diff = ( this.width - width ) / 2;
var coords = { x1 : diff, y1 : 0, x2 : width + diff, y2: this.height };
}
$( this ).imgAreaSelect( coords );
});
}