showing results for - "javascript resize image base64"
Giuseppe
08 Nov 2017
1function resizeImage(base64Str, maxWidth = 400, maxHeight = 350) {
2  return new Promise((resolve) => {
3    let img = new Image()
4    img.src = base64Str
5    img.onload = () => {
6      let canvas = document.createElement('canvas')
7      const MAX_WIDTH = maxWidth
8      const MAX_HEIGHT = maxHeight
9      let width = img.width
10      let height = img.height
11
12      if (width > height) {
13        if (width > MAX_WIDTH) {
14          height *= MAX_WIDTH / width
15          width = MAX_WIDTH
16        }
17      } else {
18        if (height > MAX_HEIGHT) {
19          width *= MAX_HEIGHT / height
20          height = MAX_HEIGHT
21        }
22      }
23      canvas.width = width
24      canvas.height = height
25      let ctx = canvas.getContext('2d')
26      ctx.drawImage(img, 0, 0, width, height)
27      resolve(canvas.toDataURL())
28    }
29  })
30}