上传图片的本地预览
<input type="file" id='uploadImg'>
<img src="" alt="" class="imgShow">
![这里写图片描述](https://img-blog.csdn.net/20171206111753954?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvQW15X2Nsb3Vk/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
$('#uploadImg').on('change',function(){
var file = $(this)
var fileObj = file[0];
var dataURL;
var windowURL = window.URL;
if(fileObj.files[0]){
dataURL = windowURL.createObjectURL(fileObj.files[0])
$('.imgShow').attr('src',dataURL);
}
else{
dataURL = file.val();
console.log(dataURL)
$('.imgShow').style.filter = 'progid:DXImageTransform.Micsoft.AlphaImageLoader(sizingMethod = scale)'
$('.imgShow').filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = dataURL;
}
$.ajaxFileUpload({
url:"",
fileElementId: "uploadImg",
dataType: "string",
success: function(data) {
$('.imgShow').attr("src",data);
}
});
})
上传图片本地预览 + 压缩上传
<input type="file" accept="image/*" class='file' id='uploadImg' value=''>
<img src="" class='imgShow' />
$('#uploadImg').on('change',function(event){
if(!isCanvasSupported){
return;
}else{
compress(event, function(base64Img){
$(".imgShow").attr("src",base64Img);
console.log(base64Img);
$('.imgShow').click(function(){
var width = $('.imgShow').width();
console.log(width)
if(width == '200'){
$('.mengban').show();
$('.imgShow').addClass('changeImg')
}
$('.mengban').click(function(){
$('.imgShow').removeClass('changeImg')
$('.mengban').hide();
})
})
ajax('qnl_app/tes_ac_img',{'base64Img':base64Img},function(date){
console.log(JSON.stringify(date));
$('.imgShow').attr("src",data);
});
});
}
})
压缩图片用的js方法如下:
function isCanvasSupported() {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
}
function compress(event, callback) {
if ( typeof (FileReader) === 'undefined') {
console.log("当前浏览器内核不支持base64图标压缩");
} else {
try {
var file = event.currentTarget.files[0];
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.onload = function (e) {
var image = $('<img/>');
image.load(function () {
console.log("开始压缩");
var square = 700;
var canvas = document.createElement('canvas');
canvas.width = square;
canvas.height = square;
var context = canvas.getContext('2d');
context.clearRect(0, 0, square, square);
var imageWidth;
var imageHeight;
var offsetX = 0;
var offsetY = 0;
if (this.width > this.height) {
imageWidth = Math.round(square * this.width / this.height);
imageHeight = square;
offsetX = - Math.round((imageWidth - square) / 2);
} else {
imageHeight = Math.round(square * this.height / this.width);
imageWidth = square;
offsetY = - Math.round((imageHeight - square) / 2);
}
context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
var data = canvas.toDataURL('image/jpeg');
callback(data);
});
image.attr('src', e.target.result);
};
reader.readAsDataURL(file);
} catch(e) {
console.log("压缩失败!");
}
}
}