图片相关
a标签导出图片
js
// 如果你想在点击按钮后进行下载,可以创建一个a元素并模拟点击
let a = document.createElement('a');
a.href = imgSrc;
a.download = 'image.jpg'; // 设置下载文件名
document.body.appendChild(a);
a.click();
document.body.removeChild(a); // 清理不再需要的a元素
图片占位服务API
格式:http://via.placeholder.com/宽x高/背景色/字的颜色?text=占位文字
html
<img src="http://via.placeholder.com/200x300/f60/fff?text=HI" alt="">
第二种
html
<img src="https://picsum.photos/200/200" alt="">
第三种
格式:https://dummyimage.com/宽x高/背景色/文字颜色.png&text=显示的文字
html
<img src="https://dummyimage.com/200x100" alt="">
<img src="https://dummyimage.com/200x100/894FC4/FFF.png" alt="">
<img src="https://dummyimage.com/200x100/894FC4/" alt="">
<img src="https://dummyimage.com/200x100/894FC4/FFF.png&text=123" alt="">
如何判断图片全部加载完成
用Promise.all实现
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<script>
function loadImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = src;
img.onload = () => {
resolve(img);
};
img.onerror = () => {
reject(new Error(`Failed to load image at ${src}`));
};
});
}
function loadImages(imageSources) {
const promises = imageSources.map(src => loadImage(src));
return Promise.all(promises);
}
let num = (min,max) => {
return Math.floor(Math.random() * max) + min
}
// 示例使用
const imageUrls = [
`https://picsum.photos/200/${num(100, 300)}?v=` + Math.random(),
`https://picsum.photos/200/${num(100, 300)}?v=` + Math.random()
];
loadImages(imageUrls)
.then(images => {
console.log('所有图片已加载完成', images);
// 这里可以执行后续操作
})
.catch(error => {
console.error('加载图片时发生错误:', error);
});
</script>
</body>
</html>
多个图片打包成zip
shell
npm install jszip
import JSZip from 'jszip';
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ZIP Download Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
</head>
<body>
<button id="download">下载 ZIP 文件</button>
<script>
document.getElementById('download').addEventListener('click', function() {
// 创建一个 JSZip 实例
const zip = new JSZip();
// 假设你有多个图片的 URL
const imageUrls = [
'https://example.com/image1.jpg',
'https://example.com/image2.png',
'https://example.com/image3.gif'
];
const promises = imageUrls.map(url => {
return fetch(url)
.then(response => response.blob())
.then(blob => {
const filename = url.substring(url.lastIndexOf('/') + 1);
zip.file(filename, blob);
});
});
// 等待所有的图片都加载完成
Promise.all(promises).then(() => {
// 生成 ZIP 文件
zip.generateAsync({ type: 'blob' })
.then(content => {
// 创建下载链接
const link = document.createElement('a');
link.href = URL.createObjectURL(content);
link.download = 'images.zip';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
});
});
</script>
</body>
</html>
通过canvas实现图片压缩
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Compression</title>
</head>
<body>
<input type="file" id="upload" />
原始图片:
< img id="old" alt="Compressed Image" />
压缩之后的图片:
< img id="result" alt="Compressed Image" />
<script>
document.getElementById('upload').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
const img = new Image();
img.src = e.target.result;
document.getElementById('old').src = e.target.result;
img.onload = function() {
// 创建一个 canvas 元素并设置宽高
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const MAX_WIDTH = 800; // 最大宽度
const MAX_HEIGHT = 800; // 最大高度
let width = img.width;
let height = img.height;
// 计算压缩比例
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
// 设置 canvas 尺寸
canvas.width = width;
canvas.height = height;
// 绘制图片
ctx.drawImage(img, 0, 0, width, height);
// 导出为压缩后的图片
const dataURL = canvas.toDataURL('image/jpeg', 0.3); // 压缩质量设置为 0.7
document.getElementById('result').src = dataURL;
};
};
}
});
function base64ToFile(base64String, fileName) {
// 将 Base64 字符串分为两部分,分别是 MIME 类型和数据部分
const arr = base64String.split(',');
const mimeType = arr[0].match(/:(.*?);/)[1]; // 提取 MIME 类型
const base64Data = arr[1]; // 提取 Base64 数据
// 解码 Base64 字符串
const byteString = atob(base64Data); // 将 Base64 数据解码为字节字符串
const ab = new ArrayBuffer(byteString.length); // 创建一个 ArrayBuffer
const ia = new Uint8Array(ab); // 将 ArrayBuffer 转换为 Uint8Array
// 将字节字符串中的数据填充到 Uint8Array
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// 创建 Blob 对象
const blob = new Blob([ab], { type: mimeType });
// 创建 File 对象并返回
return new File([blob], fileName, { type: mimeType });
}
// 使用示例
const base64Image = 'data:image/png;base64,iVBORw0K...'; // 替换为你的 Base64 字符串
const fileName = 'image.png'; // 文件名
const file = base64ToFile(base64Image, fileName);
console.log(file);
</script>
</body>
</html>