在画布上绘制之前操作像素



我使用以下代码在画布上绘制 base64 图像。我从 PHP 中的查询中获取 base64 字符串。使用 globalAlpha,我可以将整个图像的 alpha 设置为 0。我需要用一个表格来操纵随机像素的 alpha。因此,当我使用表单提交 7 时,需要将 7 个随机像素从 alpha 0 设置为 255。

是否可以操纵此图像的 alpha 并随后将其绘制到画布上?保持原始图像的秘密非常重要。

var complex = "<?php echo str_replace("n", "", $DBimage); ?>";
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = "data:image/png;base64," + complex;
image.onload= function(){
ctx.drawImage(image, 0, 0);
} 
<canvas id="rectangle" width="300" height="300" style="border:solid black 1px; </canvas>
​

JavaScript

var canvas = document.getElementById('rectangle');
//replace this rectangle drawing by your image
if (canvas.getContext) {
var context = canvas.getContext('2d');
context.fillStyle = "rgb(150,29,28)";
context.fillRect(10, 10, 280, 280);
}
var imgd = context.getImageData(0, 0, canvas.width, canvas.height);
var numberOfAlphaPix = 10000; //this is the number of pixel for which you want to change the alpha channel, I let you do the job to retrieve this number as you wish
//fill an array with numbers that we'll pop to get unique random values
var rand = [];
// Loop over each pixel with step of 4 to store only alpha channel in array ( R=0 ,G=1 , B=2, A=3 )
for (var i = 3; i < imgd.data.length; i += 4) {
rand.push(i);
}
//shuffle the array
for (var i = rand.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = rand[i];
rand[i] = rand[j];
rand[j] = tmp;
}

for (var i = 0; i < numberOfAlphaPix; i++) {
imgd.data[rand.pop()] = 255; //set alpha channel to 255
}
// Draw the ImageData object at the given (x,y) coordinates.
context.putImageData(imgd, 0, 0);​

在这里试试 http://jsfiddle.net/LuEzG/5/

我不确定你的意思是"保密",但我想你的意思是:

  1. 一次仅显示几个像素
  2. 使人们无法查看源代码并发现图像(使用一些JavaScript)

如果这些是唯一的要求(如果它们是要求),那么您必须:

  1. 解码服务器上的图像
  2. 在服务器上选取几个随机像素,并将这些像素的数据(RGB 值)发送到客户端
  3. 使用画布显示收到的少数像素

这种方法的好处是你根本不需要使用ImageData。您可以只fillRect接收到的每个像素的 RGB 值fillStyle

这种方法不太好的地方在于,这意味着您必须在服务器上做更多的工作,但是如果您希望图像对客户端完全隐藏,这是唯一的方法。

最新更新