在JavaScript中获取手机内图片的尺寸,可以通过以下步骤实现:
<input type="file">
)和图像对象(Image
)。以下是一个简单的示例,展示如何使用JavaScript获取手机内图片的尺寸:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Image Dimensions</title>
<script>
function getImageDimensions(file) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve({ width: img.width, height: img.height });
img.onerror = reject;
img.src = URL.createObjectURL(file);
});
}
document.getElementById('fileInput').addEventListener('change', async (event) => {
const file = event.target.files[0];
if (file) {
try {
const dimensions = await getImageDimensions(file);
console.log('Image dimensions:', dimensions);
alert(`Width: ${dimensions.width}, Height: ${dimensions.height}`);
} catch (error) {
console.error('Error loading image:', error);
alert('Failed to load image.');
}
}
});
</script>
</head>
<body>
<input type="file" id="fileInput" accept="image/*">
</body>
</html>
对于内存限制问题,可以在加载图片前检查其大小并进行压缩:
function compressImage(file, maxWidth, maxHeight, quality) {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = URL.createObjectURL(file);
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
resolve(new File([blob], file.name, { type: file.type }));
}, file.type, quality);
};
img.onerror = reject;
});
}
通过这种方式,可以在保证用户体验的同时,有效管理资源使用。
领取专属 10元无门槛券
手把手带您无忧上云