/** * 計算縮放寬高 * @param imgWidth 圖片寬 * @param imgHeight 圖片高 * @param maxWidth 指望的最大寬 * @param maxHeight 指望的最大高 * @returns [number,number] 寬高 */
export const zoomImgSize = (imgWidth, imgHeight, maxWidth, maxHeight) => {
let newWidth = imgWidth,
newHeight = imgHeight;
if (imgWidth / imgHeight >= maxWidth / maxHeight) {
if (imgWidth > maxWidth) {
newWidth = maxWidth;
newHeight = (imgHeight * maxWidth) / imgWidth;
}
} else {
if (imgHeight > maxHeight) {
newHeight = maxHeight;
newWidth = (imgWidth * maxHeight) / imgHeight;
}
}
if (newWidth > maxWidth || newHeight > maxHeight) {
//不知足預期,遞歸再次計算
return zoomImgSize(newWidth, newHeight, maxWidth, maxHeight);
}
return [newWidth, newHeight];
};
/** * 壓縮圖片 * @param img img對象 * @param maxWidth 最大寬 * @param maxHeight 最大高 * @param quality 壓縮質量 * @returns {string|*} 返回base64 */
export const resizeImg = (img, maxWidth, maxHeight, quality = 1) => {
const imageData = img.src;
if (imageData.length < maxWidth * maxHeight) {
return imageData;
}
const imgWidth = img.width;
const imgHeight = img.height;
if (imgWidth <= 0 || imgHeight <= 0) {
return imageData;
}
const canvasSize = zoomImgSize(imgWidth, imgHeight, maxWidth, maxHeight);
const canvas = document.createElement('canvas');
canvas.width = canvasSize[0];
canvas.height = canvasSize[1];
canvas.getContext('2d')
.drawImage(img, 0, 0, canvas.width,
canvas.height);
return canvas.toDataURL('image/jpeg', quality);
};
複製代碼
一個計算縮放後的寬高.一個壓縮圖片.java
固然也能夠再優化擴展一下,好比壓縮後的圖片格式,img的判空等等.canvas