'How can we resize the image width of base64 when converting from image url?
I have a script with me to convert image url to base64. But i don't know how to resize the image width and that of height respecting the aspect ratio of the image before converting it to base64.
<script>
const getBase64FromUrl = async (url) => {
const data = await fetch(url);
const blob = await data.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = () => {
const base64data = reader.result;
resolve(base64data);
}
});
}
getBase64FromUrl('https://lh3.googleusercontent.com/i7cTyGnCwLIJhT1t2YpLW-zHt8ZKalgQiqfrYnZQl975-ygD_0mOXaYZMzekfKW_ydHRutDbNzeqpWoLkFR4Yx2Z2bgNj2XskKJrfw8').then(console.log)
</script>
I got this from https://stackoverflow.com/a/64929732/18642473
Solution 1:[1]
This is what i did to compress an image before upload it:
const img_convert = (img_data) => {
const imgArr = img_data
const reader = new FileReader()
reader.readAsDataURL(img_data)
reader.onload = (e) => {
const imgData = e.target.result
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
const newImg = document.createElement('img')
newImg.setAttribute('src', imgData)
newImg.onload = () => {
const imgSize = (imgArr.size / (1000 * 1024)).toFixed(1)
const actualWidth = newImg.width
const actualHeight = newImg.height
const imgWidth = Math.floor(
actualWidth / (imgSize < 1 ? 1 : imgSize > 5 ? 4 : imgSize)
)
const imgHeight = Math.floor(
actualHeight / (imgSize < 1 ? 1 : imgSize > 5 ? 4 : imgSize)
)
canvas.width = imgWidth
canvas.height = imgHeight
ctx.drawImage(newImg, 0, 0, imgWidth, imgHeight)
const imgUrl = canvas.toDataURL('image/webp')
setPost_img(imgUrl)
}
}
}
You can customize it as you wish
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | A.Anvarbekov |
