我需要在上传之前打开图片并以图形和动态方式对其进行编辑。首先,用户应该选择图像文件和界面返回文件路径,然后用户应该看到预览,如果他/她想要选择全部或一部分图像进行上传。
javascript或jquery中是否有任何可以为我执行此操作的函数,或者我是否必须使用插件,如果有,哪些插件?
答案 0 :(得分:2)
There are many good jQuery plugins are available to crop image on the fly,
HTML图片上传表单
<!-- 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>
jQuery和JavaScript
// set info for cropping image using hidden fields
function setInfo(i, e) {
$('#x').val(e.x1);
$('#y').val(e.y1);
$('#w').val(e.width);
$('#h').val(e.height);
}
$(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) {
p.attr('src', oFREvent.target.result).fadeIn();
};
});
// implement imgAreaSelect plug in (http://odyniec.net/projects/imgareaselect/)
$('img#uploadPreview').imgAreaSelect({
// set crop ratio (optional)
aspectRatio: '1:1',
onSelectEnd: setInfo
});
});
PHP:
<?php
$valid_exts = array('jpeg', 'jpg', 'png', 'gif');
$max_file_size = 200 * 1024; #200kb
$nw = $nh = 200; # image with & height
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if ( isset($_FILES['image']) ) {
if (! $_FILES['image']['error'] && $_FILES['image']['size'] < $max_file_size) {
# get file extension
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
# file type validity
if (in_array($ext, $valid_exts)) {
$path = 'uploads/' . uniqid() . '.' . $ext;
$size = getimagesize($_FILES['image']['tmp_name']);
# grab data form post request
$x = (int) $_POST['x'];
$y = (int) $_POST['y'];
$w = (int) $_POST['w'] ? $_POST['w'] : $size[0];
$h = (int) $_POST['h'] ? $_POST['h'] : $size[1];
# read image binary data
$data = file_get_contents($_FILES['image']['tmp_name']);
# create v image form binary data
$vImg = imagecreatefromstring($data);
$dstImg = imagecreatetruecolor($nw, $nh);
# copy image
imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);
# save image
imagejpeg($dstImg, $path);
# clean memory
imagedestroy($dstImg);
echo "<img src='$path' />";
} else {
echo 'unknown problem!';
}
} else {
echo 'file is too small or large';
}
} else {
echo 'file not set';
}
} else {
echo 'bad request!';
}
?>
参考网址:http://www.w3bees.com/2013/08/image-upload-and-crop-with-jquery-and.html