JS經過指定大小來壓縮圖片

安裝:
  npm i image-conversion --save

引入:
  <script src="https://cdn.jsdelivr.net/gh/WangYuLue/image-conversion/build/conversion.js"></script>
  or
  const imageConversion = require("image-conversion")

用例:
  <input id="demo" type="file" onchange="view()">

  1、將圖像壓縮到200kbhtml

  function view(){
    const file = document.getElementById('demo').files[0];
    console.log(file);
    imageConversion.compressAccurately(file,200).then(res=>{
      //The res in the promise is a compressed Blob type (which can be treated as a File type) file;
      console.log(res);
    })
  }

  // or use an async function
  async function view() {
    const file = document.getElementById('demo').files[0];
    console.log(file);
    const res = await imageConversion.compressAccurately(file,200)
    console.log(res);
  }

  2、圖像精度0.9git

  function view(){
    const file = document.getElementById('demo').files[0];
    console.log(file);
    imageConversion.compress(file,0.9).then(res=>{
      console.log(res);
    })
  }

 

imageConversion的一些方法:

  ①imagetoCanvas()----縮放和旋轉圖片github

    例子:npm

    imageConversion.imagetoCanvas(image);

    //or

    imageConversion.imagetoCanvas(image,{
      width: 300,   //result image's width
      height: 200,  //result image's height
      orientation:2,//image rotation direction
      scale: 0.5,   //the zoom ratio relative to the original image, range 0-10;
                    //Setting config.scale will override the settings of
                    //config.width and config.height;
    })

      

 

  ②dataURLtoFile()----肯定轉換後的圖像類型:「Image/png」、「Image/jpeg」、「Image/gif」promise

 

  ③compress()----若是傳入的是數字,表示圖片質量;若是傳入的是對象,表示將參數傳遞給imagetoCanvasdataURLtoFile方法async

    例子:ide

    // number
    imageConversion.compress(file,0.8)

    //or

    // object
    imageConversion.compress(file,{
      quality: 0.8,
      type: "image/jpeg",//若是壓縮PNG透明圖像,請選擇「Image/png」類型
      width: 300,
      height: 200,
      orientation:2,
      scale: 0.5,
    })

 

   ④compressAccurately()----若是是傳入的是數字,表示指定壓縮後圖像的大小(KB);若是傳入的是對象,表示將參數傳遞給imagetoCanvasdataURLtoFile方法工具

    例子:ui

      // number
    imageConversion.compressAccurately(file,100); //The compressed image size is 100kb
    // object
    imageConversion.compressAccurately(file,{
      size: 100,    //The compressed image size is 100kb
      accuracy: 0.9,//the accuracy of image compression size,range 0.8-0.99,default 0.95;
                    //this means if the picture size is set to 1000Kb and the
                    //accuracy is 0.9, the image with the compression result
                    //of 900Kb-1100Kb is considered acceptable;
      type: "image/jpeg",
      width: 300,
      height: 200,
      orientation:2,
      scale: 0.5,
    })    

 

 

 

 

參考:GitHubthis

圖片轉換工具:http://www.wangyulue.com/assets/image-comversion/example/index.html

相關文章
相關標籤/搜索