当处理基于 Base64 编码的图像数据时,您可以使用以下代码来获取图像的宽度、高度以及 Uint8ClampedArray(表示图像像素数据):
一、基于typescript的实现
function base64DataURLToImageData(base64DataURL: string): Promise<ImageData> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
if (!context) {
reject(new Error("context is null"));
return;
}
context.drawImage(img, 0, 0);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
resolve(imageData);
};
img.onerror = (error) => {
reject(error);
};
img.src = base64DataURL;
});
}
使用示例
// 示例用法:
const base64DataURL = "data:image/png;base64,iVBORw..."; // 替换为您的Base64数据URL
base64DataURLToImageData(base64DataURL)
.then((imageData) => {
console.log("图像宽度:", imageData.width);
console.log("图像高度:", imageData.height);
console.log("Uint8ClampedArray:", imageData.data);
})
.catch((error) => {
console.error("处理图像时出错:", error);
});
// 提取 base64 图像数据部分
const imageData = await base64DataURLToImageData(base64DataURL);
二、基于javascript的实现
function base64DataURLToImageData(base64DataURL) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
if (!context) {
reject(new Error("context is null"));
return;
}
context.drawImage(img, 0, 0);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
resolve(imageData);
};
img.onerror = (error) => {
reject(error);
};
img.src = base64DataURL;
});
}
使用示例
// 用法示例:
const base64DataURL = "data:image/png;base64,iVBORw0KG..."; // 你的Base64数据URL
base64DataURLToImageData(base64DataURL)
.then((imageData) => {
console.log("ImageData:", imageData);
// 在这里可以使用ImageData进行进一步处理
})
.catch((error) => {
console.error("Error:", error);
});