Skip to content

Instantly share code, notes, and snippets.

@rikschennink
Created October 11, 2021 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rikschennink/7269c6044500a83deb0ec3e4c1d400a5 to your computer and use it in GitHub Desktop.
Save rikschennink/7269c6044500a83deb0ec3e4c1d400a5 to your computer and use it in GitHub Desktop.
Scramble filter for use in worker
export default (
options: { imageData: ImageData; amount: number },
done: (err: string, imageData: ImageData) => void
): void => {
const { imageData, amount = 1 } = options;
const intensity = Math.round(Math.max(1, amount) * 2);
const range = Math.round(intensity * 0.5);
const inputWidth = imageData.width;
const inputHeight = imageData.height;
const outputData = new Uint8ClampedArray(inputWidth * inputHeight * 4);
const inputData = imageData.data;
let randomData;
let i = 0,
x,
y,
r;
let xoffset = 0;
let yoffset = 0;
let index;
const l = inputWidth * inputHeight * 4 - 4;
for (y = 0; y < inputHeight; y++) {
randomData = crypto.getRandomValues(new Uint8ClampedArray(inputHeight));
for (x = 0; x < inputWidth; x++) {
r = randomData[y] / 255;
xoffset = 0;
yoffset = 0;
if (r < 0.5) {
xoffset = (-range + Math.round(Math.random() * intensity)) * 4;
}
if (r > 0.5) {
yoffset = (-range + Math.round(Math.random() * intensity)) * (inputWidth * 4);
}
// limit to image data
index = Math.min(Math.max(0, i + xoffset + yoffset), l);
outputData[i] = inputData[index];
outputData[i + 1] = inputData[index + 1];
outputData[i + 2] = inputData[index + 2];
outputData[i + 3] = inputData[index + 3];
i += 4;
}
}
done(null, {
data: outputData,
width: imageData.width,
height: imageData.height,
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment