SoFunction
Updated on 2025-02-28

HTML5 JS compresses images and gets images BASE64 encoding upload

This article shares HTML5 JS compressed images and obtains the BASE64 encoding upload method for your reference. The specific content is as follows

Basic Process

1) Call the (img); method of FileReader, and in its onload event, read the image selected by the user into the Image object.

2) In the onload event of the image object, change the size of the Image to the canvas through the drawImage method of the ('2d') canvas.

3) Through the ("image/jpeg", 0.1); method, turn the image into a base64 string and pass it to the server.

var vueImg = new Vue({
  el: "#divCarImages",
  data: { model: { carId: '@carId', imageTitle:'',img64:'' }, images: [] },
  methods: {
   imageHandle: function () {
    var fup = $("#fileImg")[0];

    var img = [0];

    var image = new Image();
    var canvas = $("#canvas")[0];//("canvas");
    var ctx = ('2d');

     = function () {
     var w = ,
      h = ;

     var toSize = 400;
      = toSize;
      = toSize;

     var w2 = toSize, h2 = toSize;
     if (w > h) {
      h2 = h / w * toSize;
     } else {
      w2 = w / h * toSize;
     }

     (image, 0, 0, w, h, 0, 0, w2, h2);
      
    }

    // Determine whether it is a picture    if (!img) {
     return;
    }

    //Judge image format    if (!(('image') == 0 &&  && /\.(?:jpg|png|gif)$/.test())) {
     alert('The picture can only be jpg,gif,png');
     return;
    }

    var reader = new FileReader();

     = function (e) { // reader onload start
     var url = ;
      = url;

    } // reader onload end

    (img);
   }

  }
 });
function uploadImg() {
  var canvas = $("#canvas")[0];
  .img64 = ("image/jpeg", 0.1);
  //$("#testMsg").html();
      
  // ajax upload image  $.post("@("~/AliOss/SaveCarImage")",  , function (ret) {

   parseAjaxData(data, function (model) {
    ();
    alert();
    $('#showimg').html('<img src="' +  + '">');
   })  
  }, 'json');
 }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.