<script src="jquery-1.7.2.min.js"></script>
<body>
<input type="file" id="img" name="img" />
<img id="test" src="" />
<input type="button" id="submit" value="确定" onclick="submit()" />
<script>
function submit() {
var f = document.getElementById("img").files[0];
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
var i = document.getElementById("test");
i.src = event.target.result;
var data = compress(i, 50);
var fd = new FormData();
fd.append("img", data);
$.ajax({
url: "webform1.aspx?type=upload",
type: "POST",
data: fd,
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
success: function (data) {
$(".loadingbox").hide();
if (data == 0)
myalert("提示", "保存失败");
else
myalerttoone("提示", "保存成功", "share.html");
}
});
};
})(f);
reader.readAsDataURL(f);
}
function compress(source_img_obj, quality, output_format){
var mime_type = "image/jpeg";
if(output_format!=undefined && output_format=="png"){
mime_type = "image/png";
}
var cvs = document.createElement('canvas');
//naturalWidth真实图片的宽度
cvs.width = source_img_obj.naturalWidth;
cvs.height = source_img_obj.naturalHeight;
var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0);
return cvs.toDataURL(mime_type, quality/100);
}
</script>
</body>