file.previewPath就是图片路径
this.getImageSizeFromBlobUrl(file.previewPath) .then(size => { console.log('原图大小:', size.width, 'x', size.height); const screenWidth = window.innerWidth - 80; const screenHeight = window.innerHeight - 80; // const { width, height } = this.originalSize = this.calculateFitSize(size.width, size.height, screenWidth, screenHeight); console.log('换算大小:', this.originalSize); this.cropperModel = true; }) .catch(error => { console.error('获取原图大小失败:', error); });
// 获取原图大小
getImageSizeFromBlobUrl(blobUrl) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = function() {
// 在图像加载完成后获取其自然宽度和高度
const { naturalWidth } = this;
const { naturalHeight } = this;
resolve({ width: naturalWidth, height: naturalHeight });
};
img.onerror = function() {
reject(new Error('Failed to load image'));
};
// 设置 Image 对象的 src 属性为 Blob URL
img.src = blobUrl;
});
},
// 自适应显示图片高度和宽度 calculateFitSize(imageWidth, imageHeight, containerWidth, containerHeight) { const imageAspectRatio = imageWidth / imageHeight; const containerAspectRatio = containerWidth / containerHeight; let fitWidth, fitHeight; if (imageAspectRatio > containerAspectRatio) { // 图片的宽高比例大于容器的宽高比例,按照容器的宽度进行缩放 fitWidth = containerWidth; fitHeight = containerWidth / imageAspectRatio; } else { // 图片的宽高比例小于等于容器的宽高比例,按照容器的高度进行缩放 fitHeight = containerHeight; fitWidth = containerHeight * imageAspectRatio; } return { width: Math.round(fitWidth), height: Math.round(fitHeight) }; }
右侧赞助一下 代码改变世界一块二块也是爱