无法在 Vue CLI 应用程序中使用 Pica 调整图像大小

Can't resize image with Pica in Vue CLI application

我想在将图像上传到服务器之前使用 Pica 调整图像大小。我将 vue-upload-component 与此代码一起使用 https://github.com/lian-yue/vue-upload-component/blob/master/docs/views/examples/Avatar.vue,没有 Pica 一切正常。

我将 inputFilter() 方法重写为:

inputFilter(newFile, oldFile, prevent) {
  if (newFile && !oldFile) {
    if (!/\.(gif|jpg|jpeg|png|webp)$/i.test(newFile.name)) {
      this.alert("Your choice is not a picture");
      return prevent();
    }
  }

  if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
    newFile.url = "";
    let URL = window.URL || window.webkitURL;
    if (URL && URL.createObjectURL) {
      newFile.url = URL.createObjectURL(newFile.file);
    }
  }

  const pica = Pica();
  const resizedCanvas = document.createElement("canvas");
  resizedCanvas.height = 100;
  resizedCanvas.width = 100;

  console.log(resizedCanvas);
  console.log(newFile.file);

  pica
    .resize(newFile.file, resizedCanvas)
    .then(result => console.log("resize done!"))
    .catch(error => {
      console.log("got error..");
      console.log(error);
    });
}

我在控制台中看到了这个:

AvatarUpload.vue?df5a:178 <canvas height=​"100" width=​"100">​
AvatarUpload.vue?df5a:179 File {name: "img-913965899011452289.jpg", lastModified: 1473514866000, lastModifiedDate: Sat Sep 10 2016 15:41:06 GMT+0200 (czas środkowoeuropejski letni), webkitRelativePath: "", size: 179941, …}
AvatarUpload.vue?df5a:185 got error..
AvatarUpload.vue?df5a:186 TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
    at _iterableToArrayLimit (pica.js?824b:1636)
    at _slicedToArray (pica.js?824b:1632)
    at processStages (pica.js?824b:2126)
    at eval (pica.js?824b:2157)

我也将 vue.config.js 添加到我的项目中:

module.exports = {
  configureWebpack: {
    resolve: {
      alias: {
        pica: "pica/dist/pica.js"
      }
    }
  }
};

异食癖如何运作?

嗯,我误解了异食癖API。我应该使用 <img src="" /> 标记而不是 File 对象。

工作示例:

<template>
  <div>
    <img
      src="@/assets/logo.png"
      ref="imgSrc"
    />
    <img ref="imgResult" />
    <button @click="compress">Compress!</button>

  </div>
</template>

<script>
import Pica from "pica";
export default {
  methods: {
    compress() {
      const pica = Pica();

      const resizedCanvas = document.createElement("canvas");
      resizedCanvas.height = 100;
      resizedCanvas.width = 100;

      pica
        .resize(this.$refs.imgSrc, resizedCanvas)
        .then(result => {
          console.log("resize done!");
          this.$refs.imgResult.src = result.toDataURL();
        })
        .catch(error => {
          console.log("got error..");
          console.log(error);
        });
    }
  }
};
</script>