Created
January 11, 2022 17:12
-
-
Save CezaryDanielNowak/ea3448172d30c19d657b59fc898006fa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Extra filters for https://github.com/kig/canvasfilters.git | |
Filters.scaleUp = function (imageData, scale = 2) { | |
const sourceWidth = imageData.width; | |
const sourceHeight = imageData.height; | |
const targetWidth = parseInt(sourceWidth * scale, 10); | |
const targetHeight = parseInt(sourceHeight * scale, 10); | |
const targetImageData = new ImageData(targetWidth, targetHeight); | |
for (let row = 0; row < sourceHeight; row++) { | |
for (let col = 0; col < sourceWidth; col++) { | |
const sourcePixel = [ | |
imageData.data[(row * sourceWidth + col) * 4 + 0], | |
imageData.data[(row * sourceWidth + col) * 4 + 1], | |
imageData.data[(row * sourceWidth + col) * 4 + 2], | |
imageData.data[(row * sourceWidth + col) * 4 + 3] | |
]; | |
for (let y = 0; y < scale; y++) { | |
const destRow = row * scale + y; | |
for (let x = 0; x < scale; x++) { | |
const destCol = col * scale + x; | |
for (let i = 0; i < 4; i++) { | |
targetImageData.data[(destRow * targetImageData.width + destCol) * 4 + i] | |
= sourcePixel[i]; | |
} | |
} | |
} | |
} | |
} | |
return targetImageData; | |
}; | |
Filters.sharpen = function(imageData, sharpenLevel) { | |
// inspired by https://gist.github.com/mikecao/65d9fc92dc7197cb8a7c | |
var mix = sharpenLevel || 0.3; // sharpen level. 0 - 1 | |
var w = imageData.width; | |
var h = imageData.height; | |
var x, sx, sy, r, g, b, a, dstOff, srcOff, wt, cx, cy, scy, scx, | |
weights = [0, -1, 0, -1, 5, -1, 0, -1, 0], | |
katet = Math.round(Math.sqrt(weights.length)), | |
half = (katet * 0.5) | 0, | |
dstData = new ImageData(w, h), | |
dstBuff = dstData.data, | |
srcBuff = imageData.data, | |
y = h; | |
while (y--) { | |
x = w; | |
while (x--) { | |
sy = y; | |
sx = x; | |
dstOff = (y * w + x) * 4; | |
r = 0; | |
g = 0; | |
b = 0; | |
a = 0; | |
for (cy = 0; cy < katet; cy++) { | |
for (cx = 0; cx < katet; cx++) { | |
scy = sy + cy - half; | |
scx = sx + cx - half; | |
if (scy >= 0 && scy < h && scx >= 0 && scx < w) { | |
srcOff = (scy * w + scx) * 4; | |
wt = weights[cy * katet + cx]; | |
r += srcBuff[srcOff] * wt; | |
g += srcBuff[srcOff + 1] * wt; | |
b += srcBuff[srcOff + 2] * wt; | |
a += srcBuff[srcOff + 3] * wt; | |
} | |
} | |
} | |
dstBuff[dstOff] = r * mix + srcBuff[dstOff] * (1 - mix); | |
dstBuff[dstOff + 1] = g * mix + srcBuff[dstOff + 1] * (1 - mix); | |
dstBuff[dstOff + 2] = b * mix + srcBuff[dstOff + 2] * (1 - mix); | |
dstBuff[dstOff + 3] = srcBuff[dstOff + 3]; | |
} | |
} | |
return dstData; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment