1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
|
const DefaultConfig = { width: 800, height: 600, quality: 0.92, fileType: 'jpg' }
export const converrVase64UrlToBlob = (base64, mimeType) => { const bytes = window.atob(base64.split(',')[1]) const ab = new ArrayBuffer(bytes.length)
const ia = new Uint8Array(ab) for (let i = 0; i < bytes.length; i++) { ia[i] = bytes.charCodeAt(i) } return new Blob([ia], { type: mimeType }) }
export const canvasCompress = async (file, config = {}) => { if (!file) return '' const { width, height, quality, fileType } = { ...DefaultConfig, ...config } let maxWidth = width let maxHeight = height return new Promise((resolve, reject) => { const reader = new FileReader() reader.readAsDataURL(file) reader.onload = function () { const img = new Image() const canvas = document.createElement('canvas') const ctx = canvas.getContext('2d') img.src = this.result as any img.onload = async function () { if (maxWidth === 0 || maxHeight === 0 || img.width < maxWidth || img.height < maxHeight) { maxWidth = img.width maxHeight = img.height } else if (maxWidth / maxHeight > img.width / img.height) { maxHeight = (img.height / img.width) * maxWidth } else { maxWidth = (img.width / img.height) * maxHeight } canvas.width = maxWidth canvas.height = maxHeight ctx?.drawImage(img, 0, 0, canvas.width, canvas.height) const imgResult = canvas.toDataURL(fileType, quality) const blobImg = converrVase64UrlToBlob(imgResult, fileType) resolve(blobImg) } img.onerror = function (e) { reject(e) } } }) }
|