Skip to content

Instantly share code, notes, and snippets.

@maitrungduc1410
Created October 31, 2018 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maitrungduc1410/f156be0abeb9090a0395142765d238ce to your computer and use it in GitHub Desktop.
Save maitrungduc1410/f156be0abeb9090a0395142765d238ce to your computer and use it in GitHub Desktop.
Resize image to squared image from input file before send server
var tmppath = URL.createObjectURL(file) // create temporary path of file
var img = new Image()
var offset = 0
let self = this
img.onload = function() {
if(this.width < this.height) {
offset = this.width
}
else {
offset = this.height
}
var mainCanvas = document.getElementById('canvas_image')
mainCanvas.width = offset
mainCanvas.height = offset
var ctx = mainCanvas.getContext("2d")
ctx.drawImage(img, 0, 0, mainCanvas.width, mainCanvas.height)
mainCanvas.toBlob(blob => { // convert data from canvas to blob
let imageData = new FormData
imageData.append('file', blob)
// send form data to server (using axios or anything)
// end send to server
}, 'image/jpeg', 1) // 1 ~ 100% is quality of image
}
img.src = tmppath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment