-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (62 loc) · 2.16 KB
/
index.js
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
'use strict';
function stringToBits(string) {
return string.split('')
.map(char => char.charCodeAt(0))
.map(int => (int).toString(2).padStart(8, '0').split(''))
.flat()
.map(n => +n);
}
function bitsToString(bits) {
bits = [...bits.map(n => getBit(n, 0))];
return String.fromCharCode(...Array(Math.ceil(bits.length / 8))
.fill()
.map(() => bits.splice(0, 8))
.map(arr => parseInt(arr.join(''), 2)));
}
function setBit(number, bitPosition, sign) {
if (sign) return number | (1 << bitPosition);
const mask = ~(1 << bitPosition);
return number & mask;
}
function getBit(number, bitPosition) {
return (number & (1 << bitPosition)) === 0 ? 0 : 1;
}
function createWatermark(imageAsBase64, text) {
return new Promise(resolve => {
const image = new Image();
image.src = imageAsBase64;
image.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const bits = stringToBits(text);
for (let i = 0; i < text.length * 8; i += 4) {
imageData.data[i] = setBit(imageData.data[i], 0, bits[i]);
imageData.data[i + 1] = setBit(imageData.data[i + 1], 0, bits[i + 1]);
imageData.data[i + 2] = setBit(imageData.data[i + 2], 0, bits[i + 2]);
imageData.data[i + 3] = setBit(imageData.data[i + 3], 0, bits[i + 3]);
}
context.putImageData(imageData, 0, 0);
resolve(canvas.toDataURL());
}
});
}
function readWatermark(base64, textLength) {
return new Promise(resolve => {
const image = new Image();
image.src = base64;
image.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
const bits = imageData.data.slice(0, textLength * 8);
resolve(bitsToString(bits));
}
});
}