1 of 29

Ch 09 – Files

Supanit Angsirikul

2 of 29

Text File

  • createWriter(file_name) //To create a file in the sketch folder, use PrintWriter to write data to the file.
  • createReader(file_name) //Used to read data from a file line by line by placing it into a BufferedReader.

  • The file is created in the sketch folder.
  • Sketch -> Show Sketch Folder

3 of 29

createWriter( )

PrintWriter pw = createWriter("test.txt"); // PrintWriter is used for writing text to a text-output stream, and the created instance is named pw.

for (int i = 0; i < 10; i++) // createWriter is used to create a file in the sketch folder, and an object from PrintWriter named pw is used to write data to the file.

pw.println(i + ""); // println() of PrintWriter is used to write data to the stream and move to a new line.

pw.close(); // Finishes the file

BufferedReader br = null; // BufferedReader is used to create an object for reading data line by line.

try {

br = createReader("test.txt"); // createReader is used to create a BufferedReader object for reading data line by line.

String s = null;

while ( (s = br.readLine ()) != null) // readLine() of BufferedReader is used to read data from a file.

print(s + " " );

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

br.close();

} catch(IOException ex) {

ex.printStackTrace();

}

}

Create a file : text.txt

4 of 29

Java 7, Autoclosable Object and Resource Block�but not available in Processing yet.

try (BufferedReader br = createReader("test.txt"); ) {

String s = null;

while ( (s = br.readLine ()) != null)

print(s + " " );

} catch (IOException e) {

e.printStackTrace();

}

5 of 29

Data (Raw) File

  • createOutput(file_name)
  • createInput(file_name)

import java.io.*;

OutputStream os = createOutput("test.data"); //Create a data file named test.data using an OutputStream as the output stream for the data.

DataOutputStream dos = new DataOutputStream(os); // Create a data transmission channel named dos to send data into os.

try {

for (int i = 0; i < 10; i++)

dos.writeInt(i);

} catch(IOException e) {

e.printStackTrace();

} finally {

try {

dos.close();

}

catch(Exception ex) {

ex.printStackTrace();

}

}

6 of 29

Data (Raw) File

InputStream is = createInput("test.data"); //Create an InputStream as a channel for data to flow in from the file test.data.

DataInputStream dis = new DataInputStream(is); //Create a DataInputStream to read data from the InputStream.

try {

int x;

while (true) {

x = dis.readInt();

print(x + " " );

}

} catch(EOFException e) {

try {

dis.close();

}

catch(Exception ex) {

ex.printStackTrace();

}

} catch(IOException e) {

e.printStackTrace();

}

7 of 29

Binary File

  • saveBytes(file_name, byte_array)
  • loadBytes(file_name)

int max = 10;

byte b[] = new byte[max*4];

int k = 0;

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

b[k++] = (byte) ((i >> 24) & 0xFF); //>>shift bit to the right

b[k++] = (byte) ((i >> 16) & 0xFF);

b[k++] = (byte) ((i >> 8) & 0xFF);

b[k++] = (byte) (i & 0xFF);

}

saveBytes( "test.bin", b);

b = loadBytes("test.bin");

k = 0;

int a[] = new int[max];

for (int i = 0; i < max; i++)

a[i] = b[k++] << 24 | b[k++] << 16 | b[k++] << 8 | b[k++];

printArray(a);

// println(java.util.Arrays.toString(a));

Exlore file at Sketch -> show sketch folder

8 of 29

loadStrings(file_name) - Read from a file into an array of strings.

String sa[] = { "John", "Jack", "Joe", "Jim", "Jame" };

PrintWriter pw = createWriter("test.str");

for (String n : sa)

pw.println("Hello! " + n); // write the data into PrintWriter

pw.close();

String lines[] = loadStrings("test.str");

printArray(lines); //print data in lines array to Console

9 of 29

loadXML(file_name)

PrintWriter pw = createWriter("students.xml");

pw.println("<?xml version='1.0'?>");

pw.println("<students>");

pw.println("<student id='1' name='John Rambo' gpa='3.5'/>");

pw.println("<student id='2' name='Jack Ripper' gpa='4.0'/>");

pw.println("<student id='3' name='Joe Green' gpa='1.1'/>");

pw.println("</students>");

pw.close();

XML xml = loadXML("students.xml");

XML xa[] = xml.getChildren("student");

printArray(xa);

// for (XML x : xa)

// println(x.getInt("id") + "," + x.getString("name") + "," + x.getFloat("gpa"));

10 of 29

JSON

  • saveJSONObject(jsonObject, file_name);
  • loadJSONObject(file_name)

JSONObject jo = new JSONObject();

jo.setInt("id", 1);

jo.setString("name", "John Rambo");

jo.setFloat("gpa", 3.5);

saveJSONObject(jo, "students.json");

println(jo.toString());

JSONObject jx = loadJSONObject("students.json");

print(jx.getInt("id") + "," + jx.getString("name") + "," + jx.getFloat("gpa"));

11 of 29

JSONArray

  • saveJSONArray(jsonArray, file_name);
  • loadJSONArray(file_name)

JSONObject john = new JSONObject();

john.setInt("id", 1);

john.setString("name", "John Rambo");

john.setFloat("gpa", 3.5);

JSONObject jack = new JSONObject();

jack.setInt("id", 2);

jack.setString("name", "Jack Ripper");

jack.setFloat("gpa", 4.0);

JSONArray ja = new JSONArray();

ja.setJSONObject(0, john);

ja.setJSONObject(1, jack);

saveJSONArray(ja, "students.json");

println(ja.toString());

JSONArray jx = loadJSONArray("students.json");

println(jx);

for (int i = 0; i < jx.size(); i++) {

JSONObject s = jx.getJSONObject(i);

println(s.getInt("id") + "," + s.getString("name") + "," + s.getFloat("gpa"));

}

12 of 29

loadXML(file_name)

PrintWriter pw = createWriter("students.xml");

pw.println("<?xml version='1.0'?>");

pw.println("<students>");

pw.println("<student id='1' name='John Rambo' gpa='3.5'/>");

pw.println("<student id='2' name='Jack Ripper' gpa='4.0'/>");

pw.println("<student id='3' name='Joe Green' gpa='1.1'/>");

pw.println("</students>");

pw.close();

XML xml = loadXML("students.xml");

XML xa[] = xml.getChildren("student");

printArray(xa);

// for (XML x : xa)

// println(x.getInt("id") + "," + x.getString("name") + "," + x.getFloat("gpa"));

13 of 29

PDF File

  • Processing draws in vector-based so that the output can be printed at any size. PDF can present vector-based pictures and uses less memory to store big images.

  • Everything you draw between the beginRecord() and endRecord() will be saved in the PDF file.

14 of 29

import processing.pdf.*;

boolean savePDF = false;

void setup() {

beginRecord(PDF, "test.pdf" );

size(640, 480);

background(255);

smooth();

rectMode(CENTER);

noStroke();

}

void draw() {

fill(random(255), random(255), random(255), random(255));

pushMatrix();

translate( random( width ), random( height ) );

rotate(radians(random(360)));

rect(0, 0, random(60), random(60));

popMatrix();

}

void keyPressed() {

if (key == 's') {

endRecord();

noLoop();

print("Save.");

}

}

15 of 29

PShape

  • Processing has the PShape class for representing vector based image.
  • loadShape("file_name") loads image from a svg file into a PShape.
  • shape(PShape, x, y) show the PShape at location x, y.

  • SVG files are xml for representing a vector based image.
  • We can draw objects using a vector editing program(try: http://inkscape.org), and export it as an SVG file to use in Processing programs.

16 of 29

PShape ps;

void setup() {

// copy /data to /mysketch

ps = loadShape("data/tiger.svg");

// size(300, 200);

size(640, 480);

// size(800, 600);

shape(ps, 0, 0);

}

void draw() { }

void keyPressed() {

if (key == 'm') {

stroke(0);

strokeWeight(5);

noFill();

arc(350, 380, 100, 50, 0, PI);

}

else if (key == 's') {

save("tiger.png");

}

}

tiger.svg download at https://sites.google.com/a/rsu.ac.th/supanit23/csc451

save picture at processing-4.1.1-widows-x64/processing-4.1.1/data

17 of 29

save(file_name)

  • Save the current screen to the sketch directory.
  • The image files may have extension .jpg, .png, .tif, and .tga.
  • The size of the picture will be based on the size() of the image.

18 of 29

float a = 0, s = 12, cx, cy, d = 200;

void setup() {

size(600, 400);

background(255);

noFill();

smooth();

cx = width/2; cy = height/2;

}

void draw() {

pushMatrix();

translate(cx, cy);

rotate(a);

ellipse(0, 0, 2*d, d);

popMatrix();

a += PI/s;

d -= 10;

if (d < 3) {

stroke(random(255), random(255), random(255), random(255));

cx = random(width); cy = random(height);

d = random(90);

s = random(12);

}

}

void keyPressed() {

if (key == 'n') {

noLoop();

}

else if (key == 'p') {

save("test.png");

}

else if (key == 'j') {

save("test.jpg");

}

else if (key == 'i') {

save("test.tif");

}

else if (key == 'a') {

save("test.tga");

}

}

save(file_name)

19 of 29

saveFrame("name-####.png")

  • Save the screen at the end of draw() or mouse and key events.
  • It saves a numbered sequence of image files.

20 of 29

void setup() {

size(640, 480);

background(255);

smooth();

noStroke();

}

void draw() {

fill(random(255), random(255), random(255), random(255));

ellipse( random(width), random(height), random(5, 50), random(5, 50));

}

void keyPressed() {

if (key == 's')

saveFrame("test-####.png");

else

noLoop();

}

21 of 29

PImage

  • Processing has the PImage class for representing raster based image.
  • loadImage(image-file) - load an image from a file into a PImage.
  • Currently loadImage() works with .gif, .tif, .jpg, .tga and .png, but not svg.

  • PImage has 'width' and 'height' properties of the image.

  • background(im) - display the image as the background of the frame.

22 of 29

PImage

  • The image and the frame must have the same size.
  • resize(width, height)
  • resize its image to the width and height.

  • save(filename)
  • saves the image into a file.
  • If no file extension the file will saved as .tif.

23 of 29

PImage

size(200, 200);

PImage im = loadImage(“data/android2.jpg");

im.resize(width, height);

// resize the image to the frame size

background(im);

save("android-Saved.png");

24 of 29

Show Image

  • A PImage can be showed by using:

image(image, x, y) display image at x, y (upper left corner).

image(image, x, y, w, h)

or

background(image)

  • In Active Mode, images should not be loaded outside setup()
  • unless they're inside a function called from setup().
  • Loading images in draw() will reduce the program speed.

25 of 29

void setup() {

size( 250, 250 );

strokeWeight(4);

// point(20, 20);

}

void draw() { }

void keyPressed() {

if (key == '1') {

PImage im = loadImage("data/android1.png");

image(im, 20, 20);

}

else if (key == '2') {

PImage im = loadImage("data/android1.png");

image(im, 20, 20, width/2, height/2);

}

else if (key == '3') {

PImage im = loadImage("data/android2.jpg");

image(im, 20, 20);

}

else if (key == '4') {

PImage im = loadImage("data/bird3.png");

background(255);

image(im, 20, 20);

}

else if (key == '5') {

PImage im = loadImage("data/bird1.png");

im.resize(width, height);

background(im);

}

}

26 of 29

imageMode(mode)

  • For image(pimage, x, y, w, h)
  • CORNER (x, y) is upper-left corner, (w, h) is width and height. // default
  • CORNERS (x, y) is upper-left corner, (w, h) is lower-right corner.
  • CENTER (x, y) is center, (w, h) is width and height.

27 of 29

PImage im;

void setup() {

size(200, 200);

im = loadImage(“data/bird3.png");

}

void draw() { }

void keyPressed() {

if (key == '1') {

imageMode(CORNER);

background(255);

image(im, width/2, height/2, 100, 100);

}

else if (key == '2') {

imageMode(CORNERS);

background(255);

image(im, 20, 20, 120, 120);

}

else if (key == '3') {

imageMode(CENTER);

background(255);

image(im, width/2, height/2, 100, 100);

}

}

28 of 29

Assignment # ch9

  • Set the sketch window size to 1200 x 400 pixels. Students are required to write a program that loads 3 different images (you can use any image from internet), resizes each image to a width of 400 pixels (one-third of the screen width), and then displays the three resized images side by side to completely fill the sketch window. When the ‘s’ key is pressed, the program should save the displayed image with the filename named as the student ID (e.g., 66xxxxx.jpg).

29 of 29

read more

  • http://www.yourhtmlsource.com/images/fileformats.html
  • https://www.labnol.org/software/tutorials/jpeg-vs-png-image-quality-or-bandwidth/5385/
  • http://www.digitalfamily.com/tutorials/whats-the-best-image-format-for-the-web/

  • raw files:
  • http://www.cambridgeincolour.com/tutorials/imagetypes.htm
  • http://www.cambridgeincolour.com/tutorials/RAW-file-format.htm