MCPcopy Create free account
hub / github.com/APIParkLab/APIPark / compressImage

Function compressImage

frontend/packages/common/src/utils/uploadPic.ts:10–54  ·  view source on GitHub ↗
(file: RcFile, maxSize: number)

Source from the content-addressed store, hash-verified

8}
9
10export const compressImage = (file: RcFile, maxSize: number): Promise<string> => {
11 const img = document.createElement('img')
12 const canvas = document.createElement('canvas')
13 const reader = new FileReader()
14
15 return new Promise((resolve, reject) => {
16 reader.onload = (e) => {
17 img.src = e.target?.result as string
18 img.onload = () => {
19 let quality = 0.9
20 let width = img.width
21 let height = img.height
22
23 const ctx = canvas.getContext('2d')
24
25 const compress = () => {
26 canvas.width = width
27 canvas.height = height
28 ctx?.clearRect(0, 0, width, height)
29 ctx?.drawImage(img, 0, 0, width, height)
30
31 const dataUrl = canvas.toDataURL(file.type, quality)
32 const base64 = dataUrl.split(',')[1]
33 return { base64, size: base64.length * 0.75 }
34 }
35
36 let { base64, size } = compress()
37
38 while (size > maxSize && quality > 0.1) {
39 quality -= 0.1
40 ;({ base64, size } = compress())
41 }
42
43 while (size > maxSize && (width > 50 || height > 50)) {
44 width *= 0.9
45 height *= 0.9
46 ;({ base64, size } = compress())
47 }
48 resolve(base64)
49 }
50 }
51 reader.onerror = (e) => reject(e)
52 reader.readAsDataURL(file)
53 })
54}

Callers

nothing calls this directly

Calls 2

compressFunction · 0.85
createElementMethod · 0.45

Tested by

no test coverage detected