我想用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正常工作?
答案 0 :(得分: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>