Last active
July 12, 2019 17:19
-
-
Save ingeit/7974de41ce844442e4a8cb932f4894ab to your computer and use it in GitHub Desktop.
cropp croppper foto base64 auto resize
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// libreria para disminuir el tamaño y redimensrionar a un width, pero a un heigth automatico para que mantenga el aspect, lo cual no necesitamos, pero es lo que hay, entonces antes que eso, se la redminesiona realmente a WxH que queremos, pero con el metodo canvas, el tamaño se va al pingo. entonces recien ahi usamos la libreria esta para achicar los KB. | |
-- npm install --save image-resize | |
import ResizeImage from 'image-resize'; | |
croppFoto(foto) {// la foto tiene que ser base64: data:image/jpg;base64,.... si o si el data:image..... | |
const img = document.createElement('img'); | |
// When the event "onload" is triggered we can resize the image. | |
img.onload = () => { | |
// We create a canvas and get its context. | |
const canvas = document.createElement('canvas'); | |
const ctx = canvas.getContext('2d'); | |
// We set the dimensions at the wanted size. | |
canvas.width = 640; | |
canvas.height = 480; | |
// We resize the image with the canvas method drawImage(); | |
ctx.drawImage(img, 0, 0, 640, 480); | |
const dataURI = canvas.toDataURL(); | |
// hasta aqui, tenemos ya la redimension pero ahora la imagen pesa mucho... hay que bajar el tamaño con lo siguiente | |
var resizeImage = new ResizeImage({ | |
format: 'jpg', | |
height: 480, | |
width: 640 | |
}); | |
resizeImage.play(dataURI). | |
then(res => { | |
const base64 = res.replace(/^data:image\/[a-z]+;base64,/, ""); | |
this.tramite.fotoPerfil = base64; | |
}) | |
.catch(err => { | |
console.log('err: ', err); | |
}) | |
}; | |
// aqui se hace la asignacion principal para que esto funcione | |
img.src = foto; | |
} | |
// para ver despues el width y el height hay que hacer lo siguiente | |
comprobarTamanio(foto){ // esta foto tiene que empezar tambien con data:image/jpg;base64..... | |
const i = new Image(); | |
i.onload = () => { | |
console.log(i.width, i.height); | |
}; | |
i.src = foto; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment