1. <input id="file" type="file" accept=".png,.jpg,.jpeg,.gif">
    1. // 使用
    2. compressImage(input.files[0], (file) => {
    3. // 这里可以就对压缩后的文件 file 一顿操作了(上传还是咋地,你高兴就好)
    4. // handleUpload(file);
    5. }, (msg) => {
    6. console.error(msg);
    7. });
    8. /*
    9. 参数说明:
    10. file: 要压缩的图片文件
    11. success: 成功回调
    12. error: 错误回调
    13. */
    14. function compressImage(file, success, error) {
    15. // 压缩图片需要的一些元素和对象
    16. var reader = new FileReader(),
    17. img = new Image();
    18. // 缩放图片需要的canvas
    19. var canvas = document.createElement('canvas');
    20. var context = canvas.getContext('2d');
    21. // base64 地址图片加载完毕后
    22. img.onload = function () {
    23. // 图片原始尺寸
    24. var originWidth = this.width;
    25. var originHeight = this.height;
    26. // 最大尺寸限制
    27. var maxWidth = 1080, maxHeight = 1080;
    28. // 目标尺寸
    29. var targetWidth = originWidth, targetHeight = originHeight;
    30. // 图片尺寸超过1080x1080的限制
    31. if (originWidth > maxWidth || originHeight > maxHeight) {
    32. if (originWidth / originHeight > maxWidth / maxHeight) {
    33. // 更宽,按照宽度限定尺寸
    34. targetWidth = maxWidth;
    35. targetHeight = Math.round(maxWidth * (originHeight / originWidth));
    36. } else {
    37. targetHeight = maxHeight;
    38. targetWidth = Math.round(maxHeight * (originWidth / originHeight));
    39. }
    40. }
    41. // canvas对图片进行缩放
    42. canvas.width = targetWidth;
    43. canvas.height = targetHeight;
    44. // 清除画布
    45. context.clearRect(0, 0, targetWidth, targetHeight);
    46. // 图片压缩
    47. context.drawImage(img, 0, 0, targetWidth, targetHeight);
    48. // canvas转为blob并执行success回调
    49. canvas.toBlob(function (blob) {
    50. var result = new File([blob], file.name, {
    51. type: "image/png",
    52. });
    53. success(result);
    54. }, file.type || 'image/png');
    55. };
    56. // 文件base64化,以便获知图片原始尺寸
    57. reader.onload = function (e) {
    58. img.src = e.target.result;
    59. };
    60. reader.onerror = (e) => {
    61. error(e);
    62. }
    63. // 选择的文件是图片
    64. if (file.type.indexOf("image") == 0) {
    65. reader.readAsDataURL(file);
    66. } else {
    67. error("请选择图片文件");
    68. }
    69. }

    HTML5 file API加canvas实现图片前端JS压缩并上传