js手机端上传图片,带压缩图片

时间:2024-10-02 07:01:25

中添加隐藏的input 

  1. <img
  2. class="input-img-wrap"
  3. v-on:click="imgClick()"
  4. :src="fapiao"
  5. v-if="fapiao"
  6. />
  7. <div class="input-img-wrap" @click="imgClick" v-else>
  8. <img src="../../assets/img/common/+_icon.png" alt="" />
  9. <span>上传图片</span>
  10. </div>
  11. <input
  12. style="display: none;"
  13. type="file"
  14. id="uploadFile"
  15. accept="image/png,image/jpeg"
  16. v-on:change="readLocalFile()"
  17. />

2.压缩图片

核心代码:

将input中的图片本地url变为图片Base64编码。

    var localFile = ("uploadFile").files[0];

    var reader = new FileReader();

   

    (localFile , 'UTF-8')

    (function(event) {

         content = ;

     })   

2.通过Image赋值src,计算图片宽高创建同样宽高的canvas,然后将Image绘制到canvas上,通过("image/jpg", rate)获得压缩的图片Base64数据

  1. data() {
  2. return {
  3. fapiao: ""
  4. };
  5. },
  6. mounted() {
  7. vm = this;
  8. },
  9. methods: {
  10. imgClick: function() {
  11. document.getElementById("uploadFile").click();
  12. },
  13. //点击选中图片
  14. async readLocalFile() {
  15. var localFile = document.getElementById("uploadFile").files[0];
  16. var reader = new FileReader();
  17. var content;
  18. var compress = this.compress;
  19. reader.onload = function(event) {
  20. content = event.target.result;
  21. compress(content, 450, function(content0) {
  22. console.log("final=" + content0.length / 1024 + "KB");
  23. vm.fapiao = content0;
  24. });
  25. };
  26. reader.onerror = function() {
  27. alert("error");
  28. };
  29. reader.readAsDataURL(localFile, "UTF-8");
  30. },
  31. // 压缩图片
  32. compress: function(content, size, callback) {
  33. if (content.length <= size * 1024) {
  34. callback(content);
  35. return;
  36. }
  37. let canvas = document.createElement("canvas");
  38. let ctx = canvas.getContext("2d");
  39. let img = new Image();
  40. img.src = content;
  41. img.onload = function() {
  42. let width = img.width;
  43. let height = img.height;
  44. canvas.width = width;
  45. canvas.height = height;
  46. // 铺底色
  47. ctx.fillStyle = "#fff";
  48. ctx.fillRect(0, 0, width, height);
  49. ctx.drawImage(img, 0, 0, width, height);
  50. let rate = (1024 * size) / content.length;
  51. console.log("size=" + size + " rate=" + rate);
  52. console.log("**压缩前**" + content.length / 1024 + "KB");
  53. //进行压缩
  54. content = canvas.toDataURL("image/jpeg", rate);
  55. console.log("**压缩后**" + content.length / 1024 + "KB");
  56. callback(content);
  57. };
  58. }
  59. }