1 of 29

Ch 09 – Files

Supanit Angsirikul

2 of 29

Text File

  • createWriter(file_name) //ใช้สร้างไฟล์ใน sketch folder ต้องใช้ PrintWriter เพื่อเขียนข้อมูลลงไฟล์
  • createReader(file_name) //ใช้อ่านข้อมูลในไฟล์ทีละบรรทัดโดยจะต้องใส่ลงใน BefferedReader

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

3 of 29

createWriter( )

PrintWriter pw = createWriter("test.txt"); // PrintWriter ใช้สำหรับพิมพ์ข้อความลงใน text-output stream ที่สร้างขึ้น คือ pw

for (int i = 0; i < 10; i++) // createWriter ใช้สร้างไฟล์ใน sketch folder และใช้ Object จาก PrinterWriter คือ pw เขียนข้อมูลลงไฟล์

pw.println(i + ""); // println() ของ PrintWriter ใช้เขียนข้อมูลลงใน Stream และขึ้นบรรทัดใหม่

pw.close(); // Finishes the file

BufferedReader br = null; // BufferedReader ใช้สร้าง Object สำหรับอ่านข้อมูลทีละบรรทัด

try {

br = createReader("test.txt"); // createReader ใช้ สร้าง BufferedReader Object สำหรับอ่านข้อมูลทีละบรรทัด

String s = null;

while ( (s = br.readLine ()) != null) // readLine() ของ BufferedReader ใช้สำหรับอ่านข้อมูลจากไฟล์

print(s + " " );

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

br.close();

} catch(IOException ex) {

ex.printStackTrace();

}

}

สร้างไฟล์ ชื่อ 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"); //สร้างไฟล์เก็บข้อมูลชื่อ test.data โดยใช้ OutputStream เป็นทางไหลออกของช้อมูล

DataOutputStream dos = new DataOutputStream(os); // สร้างช่องทางเชื่อมต่อการส่งข้อมูล คือ dos เพื่อส่งข้อมูลเข้าไปใน 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"); //สร้าง InputStream เป็นข่องทางให้ข้อมูลจากไฟล์ test.data ไหลเข้ามา

DataInputStream dis = new DataInputStream(is); //สร้าง DataInputStream เพื่ออ่านข้อมูลใน 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));

ดูไฟล์ได้ที่ เมนู 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); // เขียนค่าลงใน PrintWriter

pw.close();

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

printArray(lines); //print ค่าในอาร์เรย์ 1 มิติ ออกที่ 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 โหลดที่ https://sites.google.com/a/rsu.ac.th/supanit23/csc451

โหลดรูปใส่ไว้ที่ 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 #

  • กำหนดให้หน้าจอ sketch มีขนาด กว้าง x สูง : 1200 x 400 ให้นักศึกษาเขียนโปรแกรมโหลดรูปภาพของนักศึกษา 3 ภาพ ที่ต่างกัน แล้วทำการ resize ภาพ ให้มีขนาดความกว้างเท่ากับ 400 (1 ใน 3 ของความกว้างหน้าจอ) แล้วให้นำภาพที่ถูก resize ทั้ง 3 ภาพมาแสดงเรียงต่อกัน จนเต็มหน้าจอ sketch เมื่อทำการกดปุ่ม ‘s’ ให้ทำการบันทึกภาพโดยกำหนดชื่อไฟล์เป็น ‘รหัสนักศึกษา.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