changePixcelColor.html
2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<head>
<p>Original Image</p>
<img id="image0" width=200 height=200/>
<br />
<p>Red recolored Green Image</p>
<img id="image1" width=200 height=200/>
</head>
</head>
<body>
<script type="text/javascript">
// this just makes an image we can test with
// it's just an image of a red rectangle
var temp = document.createElement("canvas");
var tempctx = temp.getContext("2d");
tempctx.fillStyle = "red";
tempctx.strokeStyle = "blue";
tempctx.lineWidth = 5;
tempctx.rect(20, 20, 75, 50);
tempctx.fill();
tempctx.stroke();
var image0 = document.getElementById("image0");
image0.src = temp.toDataURL();
var image = new Image();
image.onload = function () {
// replace red with green
recolorImage(image, 255, 0, 0, 0, 255, 0);
}
image.src = image0.src;
function recolorImage(img, oldRed, oldGreen, oldBlue, newRed, newGreen, newBlue) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var w = img.width;
var h = img.height;
c.width = w;
c.height = h;
// draw the image on the temporary canvas
ctx.drawImage(img, 0, 0, w, h);
// pull the entire image into an array of pixel data
var imageData = ctx.getImageData(0, 0, w, h);
// examine every pixel,
// change any old rgb to the new-rgb
for (var i = 0; i < imageData.data.length; i += 4) {
// is this pixel the old rgb?
if (imageData.data[i] == oldRed && imageData.data[i + 1] == oldGreen && imageData.data[i + 2] == oldBlue) {
// change to your new rgb
imageData.data[i] = newRed;
imageData.data[i + 1] = newGreen;
imageData.data[i + 2] = newBlue;
}
}
// put the altered data back on the canvas
ctx.putImageData(imageData, 0, 0);
// put the re-colored image back on the image
var img1 = document.getElementById("image1");
img1.src = c.toDataURL('image/png');
}
</script>
</body>
</html>