<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>js压缩图片</title> <script src="jquery.js"></script> <!-- <style type="text/css"> input { margin: 10px 0; } textarea { width: 100%; height: 300px; } </style> --> </head> <body> <input type="file" value="image" id="img_input" /> <!-- <textarea id="result"></textarea> --> <p id="img_area"></p> <script> window.onload = function() { var input = document.getElementById("img_input"); var result = document.getElementById("result"); var img_area = document.getElementById("img_area"); if (typeof(FileReader) === 'undefined') { result.innerHTML = "FileReader is not supported..."; input.setAttribute('disabled', 'disabled'); } else { input.addEventListener('change', readFile, false); } }; function readFile() { var file = this.files[0]; if (!/image\/\w+/.test(file.type)) { alert("image only please."); return false; } var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(e) { var img = new Image, width = 640, //image resize quality = 0.8, //image quality canvas = document.createElement("canvas"), drawer = canvas.getContext("2d"); img.src = this.result; img.onload = function() { canvas.width = width; canvas.height = width * (img.height / img.width); drawer.drawImage(img, 0, 0, canvas.width, canvas.height); img.src = canvas.toDataURL("image/jpeg", quality); console.log(img.src); result.innerHTML = '<img src="' + img.src + '" alt=""/>'; img_area.innerHTML = '<div class="sitetip">preview:</div><img src="' + img.src + '" alt=""/>'; } } } </script> </body> </html>