Loading a random image from an array

Hi, Sorry for the basic question but I'm new in Processing. I've found this piece of code on the internet that converts images and sends them to a receipt printer through a FTDI serial connector. The thing is I wanted to adapt it a bit in order to load a random image from an array. I've looked it up and found some related answers but still no luck... :( Thank you

this is the code:

import processing.serial.*;

Serial myPort;
String portName = "";
PImage img;

int one_byte = 0;
int[] eight_pixels = new int[8];

void setup() 
{
  size(200, 200);
  String[] ports = Serial.list();
  for(int i = 0; i < ports.length; i++){
    if(ports[i].indexOf("usbserial")!=-1){
      portName = Serial.list()[i];
    }
  }
  if(portName!=""){
    myPort = new Serial(this, portName, 19200);
    myPort.bufferUntil(10);
    println(portName);
  }else{
    println("plug in the USB cable");
  }

  myPort.write(27);
  myPort.write(55);
  myPort.write(7); // 8*(x+1)
  myPort.write(160); // x*10 us
  myPort.write(2); // x*10 us

  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);

  img = loadImage("source_image4.jpg");

  img.resize(384, 0);
  img.loadPixels();

  for (int y = 0; y < img.height; y++) {
    myPort.write(18);
    myPort.write(42);
    myPort.write(1);
    myPort.write(48);
     for (int x = 0; x < 384; x++) {
         int loc = x + y*384;

         float r = red(img.pixels[loc]);
         float g = green(img.pixels[loc]);
         float b = blue(img.pixels[loc]);

         int rgb = int(r+g+b);

         if(rgb > 382){
            eight_pixels[7-(x%8)] = 0;
         }else{
            eight_pixels[7-(x%8)] = 1;
         }
         if((x+1)%8==0){
           one_byte = eight_pixels[0] | (eight_pixels[1] << 1) | (eight_pixels[2] << 2) | (eight_pixels[3] << 3) | (eight_pixels[4] << 4) | (eight_pixels[5] << 5) | (eight_pixels[6] << 6) | (eight_pixels[7] << 7);
           myPort.write((byte)one_byte);
           delay(1);
         }
     }
     delay(10);
  }

  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
  myPort.write(" \n");
  delay(500);
}

void draw() {

}
Tagged:

Answers

  • Please format your code

  • Please ask a question

  • sorry, updated it now

  • I wanted to adapt it a bit in order to load a random image from an array.

    Currently your line:

    img = loadImage("source_image4.jpg");
    

    supposing you had an array list of filename strings.

    String filenames[] = split("source_image1.jpg source_image2.jpg source_image3.jpg source_image4.jpg", ' ');
    

    Then you would choose a random string from that list, and load it.

    String filename = filenames[(int)random(filenames.length)];
    println(filename);
    img = loadImage(filename);
    
  • It worked perfectly, thanks a lot :)

Sign In or Register to comment.