在 my codepen 中,我想使用pixelmatch在浏览器中显示两个图像的差异。该功能是这样使用的
// img1, img2 — ImageData.data of the images to compare
// output — ImageData to write the diff to, or null if don't need a diff image.
// width, height of the images - all 3 images need to have the same dimensions.
// calling pixelmatch looks like this
var numDiffPixels = pixelmatch(img1.data, img2.data
, imageDataOutput, wdth, hght, {threshold: 0.1});
<img>
标签创建ImageData对象,并从图像中以Uint8Array
的形式检索数据Uint8Array
将每个图像的imageData.data
传递给函数pixelmatch
imageDataOutput
并在numDiffixels
中获得许多不同的像素HTML
<p>
<img id="imgBefore" src="./img/T1_Before.jpg">
<img id="imgAfter" src="./img/T1_After.jpg" >
</p>
<p>
<button id="diff" class="js-compareImages">compare images</button>
<canvas id="cnvDiff"></canvas>
</p>
<p id="result"> </p>
帮助功能
首先是一个帮助函数,用于从图像中获取“画布”
// Converts image to canvas; returns new canvas element
function convertImageToCanvas(imageID) {
var image = document.getElementById(imageID);
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
// image.style = "width: 400px";
return canvas;
}
主要功能
比较图像的主要功能
function compareImages()
{
var cnvBefore = convertImageToCanvas("imgBefore");
var cnvAfter = convertImageToCanvas("imgAfter");
var ctxBefore = cnvBefore.getContext("2d");
var ctxAfter = cnvAfter.getContext("2d");
let imgDataBefore = ctxBefore.getImageData(0,0,cnvBefore.width, cnvBefore.height);
let imgDataAfter = ctxAfter.getImageData(0,0, cnvAfter.width, cnvAfter.height);
const hght = imgDataBefore.height;
const wdth = imgDataBefore.width;
var imgDataOutput = new ImageData(wdth, hght);
var numDiffPixels = pixelmatch(imgDataBefore.data, imgDataAfter.data,
imgDataOutput, wdth, hght, {threshold: 0.1});
// this line does not work
writeResultToPage(imgDataOutput)
}
imgDataOutput
中的值在第三张图像或画布上显示两个图像的差异这是无法产生预期结果的代码
function writeResultToPage(imgDataOutput)
{
var canvas = document.createElement("canvas"); // new HTMLCanvasElement();
var ctx = canvas.getContext("2d");
ctx.putImageData(imgDataOutput, 0, 0);
var result = document.getElementById("result");
result.appendChild(ctx.canvas);
}
问题
为什么writeResultToPage(imgDataOutput)
的输出画布为空?
我需要更改什么才能将imgDataOutput
或<img>
或<canvas>
放在页面上?
答案 0 :(得分:1)
问题是您需要在此处将“ .data”添加到imgDataOutput中:
runtime: php55
handlers:
- url: .*
script: cloud-test.php
beta_settings:
cloud_sql_instances: "cloudtest-2412**:southamerica-east1:store"
我还添加了:
var numDiffPixels = pixelmatch(imgDataBefore.data, imgDataAfter.data,
imgDataOutput.data, wdth, hght, {threshold: 0.1});
writeResultToPage,以便画布适合图像的大小。