当时的需求是将OpenCV.js操作以后的Mat数据类型转换为base64,然后将结果放到<img>标签
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>toGray</title>
<!--两张图片格式为左浮动,处在一行-->
<style type="text/css">
.InputOutput {
float: left;
margin: 10px;
}
</style>
</head>
<body>
<!--若 opencv.js 文件加载成功,则会显示“opencv.js is ready.”-->
<p id="status">opencv.js is loading...</p>
<!--图片读入区域-->
<div class="InputOutput">
<div class="caption">srcImg
<input type="file" id="inputFile" name="file"/>
</div>
<img id="srcImg" alt="No Image"/>
</div>
<!--结果展示区域-->
<div class="InputOutput">
<div class="caption">dstImg</div>
<canvas id="dstImg"></canvas>
</div>
<!--读入图片,并在 canvas 中显示-->
<script type="text/javascript">
// <!--读入图片-->
let imgElement = document.getElementById("srcImg");
let fileElement = document.getElementById("inputFile");
fileElement.addEventListener("change",
(e) => {
imgElement.src = URL.createObjectURL(e.target.files[0]);
}, false);
<!-- 显示 -->
imgElement.onload = function () {
let src = cv.imread(imgElement);
let x = 20
let y = 20
let w = 40
let h = 40
let point1 = new cv.Point(x, y);
let point2 = new cv.Point(x + w, y + h);
cv.rectangle(src, point1, point2, [255, 0, 0, 255], 6);
cv.imshow('dstImg', src);
let outputCanvas = document.createElement("canvas");
cv.imshow(outputCanvas, src)
let b64image = outputCanvas.toDataURL()
console.log(b64image)
document.getElementById("srcImg").src = b64image
src.delete();
};
<!--成功加载 opencv.js 后,status 标签会显示“opencv.js is ready.”-->
function onOpenCvReady() {
document.getElementById("status").innerHTML = "opencv.js is ready.";
}
</script>
<script async src="https://cdn.bootcdn.net/ajax/libs/Base64/1.1.0/base64.js"></script>
<script async src="https://unpkg.com/opencv.js@1.2.1/opencv.js" onload="onOpenCvReady();"
type="text/javascript"></script>
</body>
</html>