Dropify图片预览上传,加入等比压缩改造,并附Ajax上传base64到后台代码

引入图片预览上传js文件


Html主体部分



javascript部分

修改dropify.js文件,

在 Dropify.prototype.setPreview = function(previewable, src)方法里,

找到 var imgTag = $('').attr('src', src);

改成 var imgTag = $('').attr('src', src);

加上一个ID方便从元素中取出src属性,里面存储的是压缩后图片的base64。

然后找到 image.onload = function()  方法,在里面添加等比压缩图片的方法

reader.onload = function(_file) {
    srcBase64 = _file.target.result;
    image.src = _file.target.result;
    image.onload = function() {                	
    	canvas = document.createElement('canvas'),   
        context = canvas.getContext('2d'),  
        imageWidth = this.width,  
        imageHeight = this.height,
        maxWidth = 800,
	maxHeight = 800,
	targetWidth = '',
	targetHeight = '',
        data = '';
    	if(imageWidth > maxWidth || imageHeight > maxHeight) {
		if(imageWidth / imageHeight > maxWidth / maxHeight) {        
		targetWidth = maxWidth;
		targetHeight = Math.round(maxWidth * (imageHeight / imageWidth));
		} else {
			targetHeight = maxHeight;
			targetWidth = Math.round(maxHeight * (imageWidth / imageHeight));
		}
	} else {
                targetWidth = imageWidth;
		targetHeight = imageHeight;
        }
	canvas.width = targetWidth;
	canvas.height = targetHeight;
        context.drawImage(this, 0, 0, imageWidth, imageHeight, 0, 0, canvas.width, canvas.height);    
        var data = canvas.toDataURL('image/jpeg');
        _this.setFileDimensions(canvas.width, canvas.height);
        _this.validateImage();
        _this.input.trigger(eventFileReady, [true, data]);
    };




你可能感兴趣的:(Dropify图片预览上传,加入等比压缩改造,并附Ajax上传base64到后台代码)