Can you resize images in vuejs using vanilla js? I've managed to upload an image and send it to my s3 bucket using vue, but I'm struggling to figure out how to transform an image within vuejs and display it. Document.querySelector doesn't seem to work for me. I've been attempting this for days without success. Any assistance would be highly appreciated!
HTML CODE
<div id="imageAPP">
<div v-if="!image">
<h2>Select an image</h2>
<input type="file" id="upload" @change="imageFileChange">
</div>
<div v-else>
<br>
<br>
{{fileName}}
<br>
<br>
<img :src="image" ref="output"/>
<button v-if="!uploadIMAGE" @click="removeImage">Remove image</button>
<button v-if="!uploadIMAGE" @click="uploadImage">Upload image</button>
</div>
<br>
<br>
<h2 v-if="uploadIMAGE">Success! Image uploaded to bucket.</h2
Vue Code
new Vue({
el: "#imageAPP",
data: {
image: '',
uploadIMAGE: ''
},
methods: {
imageFileChange (e) {
let files = e.target.files || e.dataTransfer.files
if (!files.length) return
this.fileName = files[0].name;
this.createImage(files[0])
},
createImage (file) {
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = (e) => {
this.image = e.target.result;
}
},
reader.onload = function(event){
this.image = event.target.result;
const imgElement = document.createElement("img");
imgElement.src = this.image;
document.querySelector("#input").src = event.target.result;
imgElement.onload = function(e){
const canvas = document.createElement("canvas");
const MAX_WIDTH = 260;
const MAX_HEIGHT = 194;
canvas.width = MAX_WIDTH;
canvas.height = MAX_HEIGHT;
const ctx = canvas.getContext("2d");
ctx.drawImage(e.target, 0, 0, canvas.width, canvas.height);
const srcEndcoded = ctx.canvas.toDataURL(e.target, "image/jpeg");}
console.log(e.target);
document.querySelector("#output2").src = srcEndcoded2;
},
removeImage: function (e) {
console.log('Remove clicked')
this.image = ''
},
uploadImage: async function (e) {
console.log('Upload clicked')
const response = await axios({
method: 'GET',
url: API_ENDPOINT_IMAGE
})
console.log('Response: ', response.data)
console.log('Uploading: ', this.image)
let binary = atob(this.image.split(',')[1])
let array = []
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i))
}
let blobData = new Blob([new Uint8Array(array)], {type: 'image/jpeg'})
console.log('Uploading to: ', response.data.uploadIMAGE)
const result = await fetch(response.data.uploadIMAGE, {
method: 'PUT',
body: blobData
})
console.log('Result: ', result);
this.uploadIMAGE = response.data.uploadIMAGE.split('?')[0];
}
}
})