Exporting from Processing

by Jan Vantomme | September 2012 | Cookbooks Open Source

If you want to show your art to the world, you may need to export your work in an appropriate format. Processing can be used to create images, movies, or interactive applications. In this article, we'll explore the different ways you can export your work for print, web, or projection.

In this article by Jan Vantomme, author of Processing 2: Creative Programming Cookbook, we will cover:

  • Saving images
  • Exporting applications
  • Saving PDF files
  • Calculating PDF sizes
  • Saving text files
  • Exporting 3D files
  • Saving binary files

 

(For more resources on this topic, see here.)

Saving images

The easiest way to share your work on the web is to upload images to Flickr or Facebook. You could take screenshots of your sketches and use those, but there are better ways to do this. Using the saveFrame( ) function, you can save the contents of your Processing sketch to your hard drive.

We'll use a basic sketch to show how saving images works. The following code will generate 1000 transparent white circles on a black background.

void setup()
{
size( 640, 480 );
smooth();
}
void draw()
{
background( 0 );
for ( int i = 0; i < 1000; i++ ) {
fill( random( 255 ), 64 );
stroke( 255, 128 );
ellipse( random( width ), random( height ), 40, 40 );
}
if ( keyPressed ) {
saveFrame("images/artwork-####.png");
}
}

The saved image will look somewhat like the following image:

Within the draw( ) function, we'll use the keyPressed system variable. The value of this variable is true if a key is pressed and false if no keys are pressed. The saveFrame( ) function is used to save the contents of the sketch window to the hard drive. The parameter for this function is a String containing the file name for the image you'll save. I've used images/ at the beginning of this String to tell Processing to save the image in the images directory. You'll find this folder in your sketch folder, after you've run the sketch and saved an image. #### is used to add the current frame number to the image. If you don't use this, existing files will be overwritten. Choosing a file type is very easy. If you use .png at the end of the String, Processing will save a PNG file. If you use .jpg, a JPEG file will be saved. The extensions you can use are .jpg, .png, .tif, and .tga. If you want to see the images you've saved, you need to check your sketch folder. Go to Sketch | Show Sketch Folder to open the images.

Exporting applications

If you need to show one of your interactive sketches in an exhibition, you'll most likely show it on a screen or project it on a wall. But you can't expect the people at the museum to run your sketch from Processing every day before the exhibition opens. A great thing about Processing, is that you can use it to create native fullscreen applications that run on Mac OS X, Windows, or Linux. In the following example, you'll learn how to do this.

You can start by creating a simple animated sketch The size of the sketch will be set dynamically, depending on the screen resolution of the computer you'll run it on. You can do this by using the displayWidth and displayHeight system variables as parameters for the size( ) function.

float x;
float y;
int b;
void setup()
{
size( displayWidth, displayHeight );
smooth();
x = 0;
y = 0;
background( 0 );
noFill();
}
void draw()
{
b++;
if ( b > 255 ) {
b = 0;
}
x += random( 2, 6 );
if ( x > width ) {
x = 0;
y += random( 20, 40 );
if ( y > height ) {
y = 0;
}
void setup()
{
size( 595, 842 );
}
}
stroke( 0, random( 255 ), b, 64 );
float r = random( 6, 60 );
ellipse( x, y, r, r );
}

Once you've finished coding, you can export the application. Go to the File | Export Application menu or use the Cmd + E shortcut on the Mac, or Ctrl + E on Windows or Linux. On the Export Options panel, you can choose any of the three platforms and whether you want the application to run fullscreen or not. If you click on the Export button, your sketch folder will open and the applications for each of the chosen platforms will be there.

Processing will take the code from your sketch and will wrap it in a Java file. You'll find this Java file in the source directory next to the application. The file will be compiled by Processing, using a Java compiler in a native application. This process is done in the background so you don't have to worry about anything.

Saving PDF files

If you want to print your artwork and you save your sketch as an image, the size of your print will be based on the resolution of your image. If you want to print your images really big, you might want to save your sketch as a PDF file. Every shape you draw in Processing is vector-based and can thus be printed at any size. Note that if you work with pixels in Processing, you won't be able to save your work as PDF.

The first thing you need to do is to import the PDF library into your sketch. Go to Sketch | Import Library | pdf to do this. You also need to declare a boolean variable named savePDF.

import processing.pdf.*;
boolean savePDF = false;
void setup()
{
size( 640, 480 );
smooth();
rectMode( CENTER );
stroke(0);
}

Inside the draw( ) function, we'll use the savePDF variable to tell Processing when it needs to start recording the PDF file. Everything you draw between the beginRecord( ) and endRecord( ) functions will be included in the PDF file. The keyPressed( ) function is used to change the value of the savePDF variable.

void draw()
{
if ( savePDF ) {
beginRecord( PDF, "pdf/myartwork-####.pdf" );
}
background( 0 );
for ( int i = 0; i < 1000; i++ ) {
fill( 0, random( 255 ), random( 255 ), 64 );
pushMatrix();
translate( random( width ), random( height ) );
rotate( radians( random( 360 ) ) );
rect( 0, 0, 50, 50 );
popMatrix();
}
if ( savePDF ) {
endRecord();
savePDF = false;
}
}
void keyPressed()
{
if ( key == 's' ) {
savePDF = true;
}
}

If you run the sketch, you can save your work by pressing the S key. You will find the PDF files in the pdf folder inside your sketch folder.

The beginRecord( ) function is used to tell Processing that it needs to start recording the data that is drawn to the screen. The first parameter for this function is the renderer; in our case this will be PDF. The second parameter is a String with the name of the file you want to save. I've used pdf/myartwork-####.pdf in the example. The files will be saved in the pdf folder; the #### characters will be replaced with the current frame number. When you are finished drawing, you need to call the endRecord( ) function, so that Processing can save the file to the hard drive.

There are different ways to save PDF files from Processing. You can, for instance, save PDF files with multiple pages or flatten your 3D artwork and save it in a PDF file. You should take a look at the Processing reference to find out how the other techniques work. You can find it at http://processing.org/reference/libraries/pdf/index.html.

Calculating PDF sizes

Imagine that you need to generate a few thousand vector images to print postcards. To streamline your process, you probably want to generate PDF files with the exact dimensions, so that you don't have to crop them manually.

Imagine that you need to generate a few thousand vector images to print postcards. To streamline your process, you probably want to generate PDF files with the exact dimensions, so that you don't have to crop them manually.

void setup()
{
size( 595, 842 );
}

The only thing you need to know is that Processing displays everything on the screen with a resolution of 72 dots per inch (DPI). If you use the metric system, you'll need to convert the size of your final output from millimeters to inches first. One inch is 25.4 millimeters. If you use the imperial system, you won't need to convert anything. The next thing you need to do is to convert from inches to pixels. To do this, you need to multiply the number of inches by 72 and round it to the nearest integer value. A standard letter size page is 8.5 x 11 inches. The calculation to convert these dimensions to pixels is as follows:
8.5 x 72 = 612 pixels
11 x 72 = 792 pixels

Saving text files

In the previous chapter, you learned about opening text files. We'll take a look at how you can save them.

The first thing you'll need to do is declare an object of the PrintWriter type and initialize it with the createWriter( ) function.

PrintWriter textFile;
void setup()
{
textFile = createWriter("files/randomnumbers.txt");
}

In each cycle of the draw( ) function, we'll write a random number to the file. When the frameCount variable reaches 1000, we'll save the file and quit the application.

void draw()
{
textFile.println( random( 200 ) );
if ( frameCount >= 1000 ) {
textFile.flush();
textFile.close();
exit();
}
}

The createWriter( ) function is used to create a text file. The parameter for this file is a String containing the file name. Just like in the example on saving images, I've added a file directory to the String.

Inside the draw( ) function, you'll use the textFile.println( ) method. This method works just like the println( ) function but writes the line of text to the file instead of the console.

Saving the file is done with the flush( ) method, followed by the close( ) method. You have to use both of these methods to ensure that the file is made correctly.

Exporting 3D files

You've already learned that you can save your work as an image or a PDF file. If you want to generate 3D objects in Processing, and render them in a 3D application such as Cinema 4D or in a CAD program, you'll need to save that 3D data. We'll take a look at how you can use the DXF library that comes with Processing to save your generated 3D models.

We'll need to import the DXF and OpenGL libraries first. Go to the Sketch | Import Librarymenu, and choose these libraries from there. You'll also need to declare a boolean variable named saveDXF. We'll use this variable in the same way as we used the savePDF variable in the recipe on saving PDF files.

import processing.opengl.*;
import processing.dxf.*;
boolean saveDXF = false;
void setup()
{
size( 640, 480, OPENGL );
smooth();
}

In the draw( ) function, we'll use the beginRaw( ) and endRaw( ) functions to record the 3D data we need to save. You need to draw all 3D objects between these functions.

void draw()
{
if ( saveDXF == true ) {
beginRaw( DXF, "files/myCubes.dxf" );
}
lights();
background( 255 );
fill( 128 );
noStroke();
for ( int i = 0; i < 100; i++ ) {
pushMatrix();
translate(random(width), random(height), random(-1000, 0));
pushMatrix();
rotateX( radians( random( 360 ) ) );
rotateY( radians( random( 360 ) ) );
rotateZ( radians( random( 360 ) ) );
box( 50 );
popMatrix();
popMatrix();
}
if ( saveDXF == true ) {
endRaw();
saveDXF = false;
}
}
void keyPressed()
{
if ( key == 's' ) {
saveDXF = true;
}
}

The beginRaw( ) and endRaw( ) functions are used to capture 3D data and write it to a file. You can use them to write your 3D scene to a PDF file, where it will be flattened. If you want the actual 3D data, you need to save the data to a .dxf file. The first parameter of the beginRecord( ) function is either DXF or PDF, the second one is the name of the file you want to save.

If you want to see the contents of your DXF file, you can use the free eDrawings Viewer software, which is available for Windows and Mac OS X. You can download it at http://www.edrawingsviewer.com/. If you open the file in this application, it should look somewhat like the following screenshot:

You can use Hemesh or Toxiclibs to generate 3D geometry and save everything as STL files. This file format is much more usable for rapid prototyping.

Saving binary files

You've already learned that Processing can save data to a text file. In this recipe, we'll take a look at how you can write data to a binary file. This might be useful when you want to create your own proprietary file format.

You need to declare an integer array with a length of 1000 before the setup( ) function. When you run the sketch, this array will be filled with some random numbers representing uppercase and lowercase letters of the alphabet.

int[] numbers = new int[1000];
void setup()
{
for ( int i = 0; i < numbers.length; i++ ) {
if ( random( 100 ) < 50 ) {
// uppercase A - Z
numbers[i] = floor( random( 65, 91 ) );
}
else {
// lowercase a - z
numbers[i] = floor( random( 97, 123 ) );
}
}
}

Inside the draw( ) function, we'll convert the integer array into a byte array and use the saveBytes( ) method to save the data to the hard drive.

void draw()
{
if ( keyPressed ) {
byte[] bytes = byte( numbers );
saveBytes( "strangefile-"+frameCount+".zzz", bytes );
exit();
}
}

The saveBytes( )function is used to save an array of bytes to the hard drive. The first parameter is a String representing the name of the file you want to save, while the second parameter is the array of bytes.

If you open the saved file in a text editor, you'll see lots of strange characters. If you want to see the real data, you'll need to open it in a hex editor. I've used HexEdit on Mac OS X; similar applications are available for Windows or Linux. The following screenshot shows the contents of the file we've just saved. You'll see that the column on the right-hand side contains lowercase and uppercase characters.

If you want to open thefile you've just saved, you can use the loadBytes( ) function. The following piece of code will print all characters you see in the right-hand side column of the hex editor screenshot, to the console. That is, it will if you've used the same file as I did.

byte[] bytes = loadBytes("strangefile-56.zzz");
println( char( bytes ) );


Further resources on this subject:


About the Author :


Jan Vantomme

Jan Vantomme is a computational designer and artist based in Ghent, Belgium. He runs Cloudswimmers, a small studio with a focus on computational and interaction design. Jan has been using Processing since the early beta versions. He taught the subject at a university college both as faculty staff and as a guest professor. He wrote some Processing libraries to work with colors and shapes in an easy way. Jan also co-founded Processing Ghent, a community for creative coders in Belgium. They organize free lectures and workshops on Processing.

Books From Packt


OpenCV 2 Computer Vision Application Programming Cookbook
OpenCV 2 Computer Vision Application Programming Cookbook

OpenNebula 3 Cloud Computing
OpenNebula 3 Cloud Computing

OpenSceneGraph 3 Cookbook
OpenSceneGraph 3 Cookbook

OpenGL 4.0 Shading Language Cookbook
OpenGL 4.0 Shading Language Cookbook

Blender 3D Basics
Blender 3D Basics

Blender 2.5 Character Animation Cookbook
Blender 2.5 Character Animation Cookbook

 Away3D 3.6 Cookbook
Away3D 3.6 Cookbook

Mudbox 2013 Cookbook
Mudbox 2013 Cookbook


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software