Question as drawing with pixels on Processing

Hello

Now I am trying to draw picture based on the data got from the original picture. It went quite successful on p5.js but it somehow did not work well on Processing. Am I doing wrong? and What is the problem? Thank you for reading.

p5js code

var img;
var cl = [];
var tileWidth;
var tileHeight;

function preload() {
img = loadImage(‘pic2.jpg’);
}

function setup() {
createCanvas(303, 473);

for (var gridX = 0; gridX < img.width; gridX++) {
cl[gridX] = [];
for (var gridY = 0; gridY < img.height; gridY++) {

  tileWidth = width / img.width;
  tileHeight = height / img.height;

  img.loadPixels();
  var c = color(img.get(gridX, gridY));

  cl[gridX][gridY] = c;
}

}
}

function draw() {

for (i = 0; i < 50; i++) {
var posX = random(width);
var posY = random(height);

var gridx = int(posX / tileWidth);
var gridy = int(posY / tileHeight);

fill(cl[gridx][gridy]);
noStroke();

ellipse(posX, posY, 5, 5);

}
}

Processing code

PImage img;

int cols;
int rows;
color[][] myArray;

int tileWidth;
int tileHeight;

void setup() {
img = loadImage(“pic2.jpg”);

cols = img.width;
rows = img.height;
myArray = new color [cols][rows];

size(684, 776);
background(255);

for (int gridX = 0; gridX < img.width; gridX += 1) {
for (int gridY = 0; gridY < img.height; gridY += 1) {

  tileWidth = width / img.width;
  tileHeight = height / img.height;

  img.loadPixels();
  color c = color(img.get(gridX, gridY));

  myArray[gridX][gridY] = c;
}

}
}

void draw() {

for (int i = 0; i < 50; i++) {

float x = random(width);
float y = random(height);

int gridx = floor(x / tileWidth);
int gridy = floor(x / tileHeight);
if (gridx >= 67) gridx = 66;
noStroke();
fill(myArray[gridx][gridy]);
ellipse(x, y, 5, 5);

}
}

Hi,

Welcome to the community! :wink:

Please read the guidelines on how to format your code : https://discourse.processing.org/faq#format-your-code

First of all on your p5.js code, few points to consider :

  • Don’t compute tileWidth and tileHeight in the for loop because their values are the same every time.

  • This is also true for loadPixels();, you only need to load your image once but at the beginning of the setup() function.

  • Why do you use tileWidth and tileHeight? In your processing code, it force you to check if gridx is larger than the size of the array. Make the canvas width and height the same as your image might ease the process…

1 Like