We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Finally decided to join this forum since I rely so much on other's people's questions/answers.
My question today is how to randomly place a pixel after loading it. I'm not interested in manipulating it's colors just the pixels. Here is my function:
void glitch () {
if (!glitchComplete) {
// load the image's pixels into .pixel array
img.loadPixels();
//iterate through each pixel row and column and apply the desired changes
for (int x = 0; x < img.width; x++) {
for (int y = 0; y < img.height; y++) {
color pixelColor = img.pixels[y + x * img.height];
//the formula I learned from the processing docs
int loc = y + x * img.height;
int randomOffset = int(random(5,20));
//slight shift in their original location
loc = loc + randomOffset;
img.pixels[loc] = pixelColor;
}
}//end of double loop
img.updatePixels();
glitchComplete = true;
// load updated image onto surface
image(img, 0, 0, img.width, img.height);
}
For anyone new to processing, just a heads up: " loc = loc + randomOffset;" will NOT work because this position technically doesnt exist in the pixel array. If you want to place a pixel in a random location, it must be a random location within the bounds of the pixel array (hope im using the right terminology here) .
My thinking here was I wanted to redraw the pixel at it's original location & color and simply shift it over a few pixels to produce something close to a glitch effect(instead of re-colouring the image). So can anyone suggest another method that can achieve the same results.
Your time and input is very much appreciated.
Answers
Just limit that new location so it's sure to have a destination pixel, and it works fine:
Press space for the glitching. Are you asking for more ways of doing glitch effects?
Same code as @TfGuy44.
Kf
See also:
Thank you @TfGuy44 and @kfrajer for your fast responses! I did end up using @kfrajer answer simply because it was minimal effort to add and I didn't need to modify my existing code.
So I see the magic line that I was missing is
pixels[constrain(i+randomOffset,0,n-1)] = pixelColor;
Do you mind explaining why you wrote that? I dont know what the constrain function does or why your code doesn't throw an out of bounds error.https://processing.org/reference/constrain_.html
Oh okay, then in that case I see how the constrain function is extremely useful in this case.