在JavaScript中获取手机内的图片,通常会利用HTML5的<input type="file">
元素结合一些特定的属性来实现。以下是相关的基础概念、优势、类型、应用场景以及可能遇到的问题和解决方法:
<input type="file" accept="image/*">
。<input type="file" accept="image/*" multiple>
。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>获取手机内图片</title>
</head>
<body>
<input type="file" id="fileInput" accept="image/*" multiple>
<div id="preview"></div>
<script>
document.getElementById('fileInput').addEventListener('change', function(event) {
const files = event.target.files;
const preview = document.getElementById('preview');
preview.innerHTML = ''; // 清空预览区域
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement('img');
img.src = e.target.result;
img.style.width = '100px';
img.style.margin = '5px';
preview.appendChild(img);
};
reader.readAsDataURL(file);
}
}
});
</script>
</body>
</html>
function compressImage(file, maxWidth, maxHeight, quality) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = function(e) {
const img = new Image();
img.onload = function() {
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;
}
}
const canvas = document.createElement('canvas');
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.src = e.target.result;
};
reader.readAsDataURL(file);
});
}
通过以上方法,你可以在JavaScript中有效地获取并处理手机内的图片。
领取专属 10元无门槛券
手把手带您无忧上云