Hh3
Hh3

Reputation: 3

Processing(Java) to p5js - glitch effect

I'm new in p5js and i want to create a noise effect in an image with it. I create a functional sketch with Java in processing, but when i pass it to p5j something is wrong. The image is download in the html field hwne i put , but the pixels loc staff doesn't. Can anyone help me!! This is my sketch:


function  setup()
{
  createCanvas(400,300);
  img = loadImage("data/monja.jpg");
  //surface.setResizable(true);
  //surface.setSize(img.width, img.height);
  background(0);
}

function  draw()
{
  loadPixels();
  img.loadPixels();
  for (let x = 0; x < img.width; x++)
  {
    for (let y = 0; y < img.height; y++)
    {
      let loc = x+y*width;
      let c = brightness(img.pixels[loc]);
      let r = red(img.pixels[loc]);
      let g = green(img.pixels[loc]);
      let b = blue(img.pixels[loc]);
      if (c < 70){
          img.pixels[loc]= color(random(255));
      }
      else {
          img.pixels[loc] = color(r, g, b);
      }
    }
  }
  updatePixels();
  //image(img, 0, 0);
}```
   

Upvotes: 0

Views: 672

Answers (1)

Charlie Wallace
Charlie Wallace

Reputation: 1830

To modify the color of certain pixels in an image here are some things to keep in mind.

  • When we call loadPixels the pixels array is an array of numbers.
  • How many numbers each pixel gets is determined by the pixel density
  • If pixel density is 1 then each pixel will get 4 numbers in the array, each with a value from 0 to 255.
  • The first number determines the amount of red in the pixel, the second green, the third red and the fourth is the alpha value for transparency.

Here is an example that changes pixels with a high red value to a random gray scale to create a glitch effect.

var img;
var c;
function preload(){
  img = loadImage("https://i.imgur.com/rpQdRoY.jpeg");
}

function  setup()
{
  createCanvas(img.width, img.height);
  background(0);
  let d = pixelDensity();
  img.loadPixels();
  for (let i = 0; i < 4 * (img.width*d * img.height*d); i += 4) {
    if (img.pixels[i] > 150 && img.pixels[i+1] <100&&img.pixels[i+2] < 100){
    let rColor = random(255);
    img.pixels[i] = rColor;
    img.pixels[i + 1] = rColor;
    img.pixels[i + 2] = rColor;
    img.pixels[i + 3] = rColor;
    }
  }
  img.updatePixels(); 
}
function draw() {
  image(img,0,0);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>

Upvotes: 1

Related Questions