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

问题描述 投票:0回答:1

我想在将Pica上传到服务器之前使用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"
      }
    }
  }
};

如何使Pica工作?

javascript image vue.js image-resizing
1个回答
0
投票

好吧,我误解了Pica的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>
© www.soinside.com 2019 - 2024. All rights reserved.