Để chuyển ảnh thành Blob, ta dùng fetch() tải ảnh rồi gọi response.blob(). Kỹ thuật này hữu ích khi cần xử lý ảnh phía client (resize, filter, upload...).
Ví dụ
Tải ảnh từ URL và chuyển thành Blob:
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ảnh sang Blob</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 18px; font-weight: 500; color: rebeccapurple; }
.sample img { max-width: 300px; }
</style>
</head>
<body>
<h1>Chuyển đổi hình ảnh thành Blob</h1>
<div class="sample">
<img src="https://picsum.photos/id/222/300/300.jpg" alt="Ảnh mẫu" />
</div>
<button class="Btn">CHUYỂN ĐỔI</button>
<div class="result"></div>
<h3>Nhấn nút để chuyển ảnh trên thành Blob</h3>
<script>
const btn = document.querySelector(".Btn");
const resEle = document.querySelector(".result");
btn.addEventListener("click", () => {
fetch("https://i.picsum.photos/id/222/300/300.jpg")
.then(res => res.blob())
.then(blob => {
resEle.innerHTML = `blob.size = ${blob.size} bytes<br>`;
resEle.innerHTML += `blob.type = ${blob.type}<br>`;
})
.catch(err => resEle.innerHTML = `Lỗi: ${err}`);
});
</script>
</body>
</html>
Kết quả
Ban đầu hiển thị ảnh. Sau khi nhấn CHUYỂN ĐỔI, thông tin size và type của Blob được in ra.
Lưu ý: Do chính sách CORS, một số ảnh từ domain khác có thể không fetch được. Cần server cho phép Access-Control-Allow-Origin.