ComputationalCamerasWeek1
Search:
ClassWork / ComputationalCamerasWeek1

Capturing (Mobile Processing

  1. Install Mobile Processing. Check out Mobile Media Week 7 for tips for getting started with mobile processing.
  2. If you can't get a phone that runs java, your can do this on your laptop (check out simple tint example). The regular java is pretty much the same thing.
import processing.video.*;

import java.io.DataOutputStream;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;


public class CaptureIt1 extends PMIDlet {

  Capture myCam;
  PImage myImage = null;
  int xpos = 0;
  int ypos = 0;


  void setup(){
    myCam = new Capture(this);
    myCam.show(0,0);  //this takes over the screen showing camera preview
    noLoop();  //this disables the draw loop

  }

  void draw(){
    background(255);
    if (myImage != null){
      image(myImage,xpos,ypos);
    }
  }

  void keyPressed(){
    if (key == '5'){
      byte[] imageData = myCam.read("image/png",160,120); //read in the picture
      //  new PostFile(imageData, "test.jpg", "http://itp.nyu.edu/~dbo3/up.php");
      myCam.hide(); //tell Capture to stop previewing
      myImage = loadImage(imageData); //make an image from the array of bytes
      loop();  //this reenables the draw loop
    }
    else if (key == '4'){
      xpos = xpos -1;
    }
    else if (key == '6'){
      xpos = xpos + 1;
    } 
    else if (key == '9'){
      //resume preview
      myCam.show(0,0);  //this takes over the screen showing camera preview
      noLoop();  //this disables the draw loop
    }
  }

  void destroy() {
    //// close the camera object on sketch exit
    myCam.close();
  }

}

Sending (Processing or Mobile Processing)

  1. Add this line when you want to take a picture (say in the keyPressed function): new PostFile(imageData, "test.jpg", "http://itp.nyu.edu/~dbo3/up.php");
  2. Then paste the class and import statements below in your code (or alternatively add this library)
  3. You should see the pictures at http://itp.nyu.edu/~dbo3/up/ (if instead of "test.jpg" you put "http://itp.nyu.edu/~yourNetID/yourfolder" it should go there if the folder has permissions 777).

//add these at the very top
import java.io.DataOutputStream;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;


//add this just before the last curly bracket, that makes it an inner class.

  class PostFile extends Thread{

    int length;
    String filename;
    byte[] outputArray;
    String url;
    String fileType = "jpeg";

    PostFile( byte[] _outputArray, String _filename, String _url){
      url = _url;
      outputArray = _outputArray;
      filename = _filename;
      length = outputArray.length;
      this.start();
    }

    public void run(){
      InputStream is = null;
      String response = "Server Response:";
      System.out.println("filename "+ filename);
      try {
        HttpConnection  c = (HttpConnection) Connector.open(url);
        c.setRequestMethod(HttpConnection.POST);
        c.setRequestProperty("Content-Type", "multipart/form-data, boundary=AaB03x");
        //	c.setRequestProperty("content-length", "" + (boundaryMessageBytes.length + outputArray.length + endBoundary.length())); 
        DataOutputStream dataOut = new DataOutputStream(c.openOutputStream());
        dataOut.write("--AaB03x\r\n".getBytes());
        dataOut.write(("Content-Disposition: form-data; name=\"data_file\"; filename=\"" + filename + "\"\r\n").getBytes());
        dataOut.write(("Content-Type: " + fileType + " \r\n").getBytes());
        dataOut.write("\r\n".getBytes());
        dataOut.write(outputArray,0,length);
        dataOut.write("\r\n--AaB03x--\r\n".getBytes());
        dataOut.flush();
        dataOut.close();
        System.out.println("waiting for server");
        //receive response and display in a text box.
        is = c.openDataInputStream();
        int ch;
        while ((ch = is.read()) != -1) {
          response = response + (char) ch;
        }
        is.close();
      } 
      catch (Exception e) {
        System.out.println("Problem with post " + e);
      }
      System.out.println( " size:" + outputArray.length + " "+ response);
    }
  }

Recieving (PHP)

  1. If you put this script in your folder on the server make sure there is a folder in the same directory named "up" with permissions for everyone to write (777)
<?
//print_r($_POST);
//print_r($_FILES); 
//This is a function used later on for testing extenstions
//skip it for now
function endsWith( $str, $sub ) {
   return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
}
//get ready
unset($filename);

//get the files in from the post
if(!isset($_FILES) && isset($HTTP_POST_FILES))
$_FILES = $HTTP_POST_FILES;
//if no file was sent
if(!isset($_FILES['data_file']))
$error["data_file"] = "File named data_file was not found.";

$filename = urldecode($_FILES['data_file']['name'] );
//this will contain the extra information that you sent over
//if they don't have a path name use the default of an "up"
//folder in the current directory.  This requires you to have a 
//world writable "up" directory in the same directory as up.php
$pos = strpos($filename,"/home/");
if ($pos === false) {
			$filename = "./up/" . $filename;
}
//if they did not send over any filename
if(empty($filename))
$error["filename"] = "The name of the file was not found.";

//if there were no previous problems
if(empty($error))
{
	//security measure, only good file extensions get in
	if (endsWith($filename, ".png") || endsWith($filename,".jpg") || endsWith($filename,".log")){
		//this is it, move and name the file within the server
		$result = @move_uploaded_file($_FILES['data_file']['tmp_name'], $filename );
		if(empty($result))
			$error["result"] = "There was an error moving the uploaded file.";
	}else{
		$error["extension"] = "Bad File Extension.";
	}

}


if(is_array($error))
{
	//send back the litany of errors
	while(list($key, $val) = each($error))
		{
		echo $val;
		echo "<br>\n";
		}
}else{
	//send back a sunny message
	$size = filesize($tmp );
	echo "OK: $size bytes FILENAME: $filename  ";  
}

?>

Viewing (Processing)


import javax.imageio.ImageIO;

public class  DisplayImage extends PApplet {

  ArrayList pictures = new ArrayList();

  void setup(){
    size(800,600);
    pictures = getPicturesInWebDirectory("http://itp.nyu.edu/~dbo3/up/");
    for (int i = 0; i < pictures.size(); i++){
        BufferedImage thisPicture = (BufferedImage) pictures.get(i);
        image(new PImage(thisPicture), 0,i*100);
    }
  }

  void draw(){


  }

  public ArrayList getPicturesInWebDirectory(String _dir) {
    // for this to work you have to make you directory listing visible to
    // the web
    // by adding a file called ".htacces" with one line "DirectoryIndex
    // showit" in it.
    ArrayList pics = new ArrayList();
    try {
      URL myURL = new URL(_dir);
      BufferedReader dis = new BufferedReader(new InputStreamReader(myURL.openStream()));
      // InputStreamReader isr = new InputStreamReader(myURL.openStream())
      String line = dis.readLine();
      while (line != null) {
        if (line.indexOf("img src=\"/icons/image2.gif") != -1) {
          String frontMark = "<a href=\"";
          int beg = line.indexOf(frontMark) + frontMark.length();
          int end = line.indexOf("\"", beg);
          String filename = line.substring(beg, end);
          System.out.println("----" + filename);
          BufferedImage bi = ImageIO.read(new URL(_dir + filename));
          pics.add(bi);
        }
        line = dis.readLine();
      }
    } 
    catch (IOException e) {
      System.out.println("BAD URL");
    }
    return pics;
  }

  /**
   * 	 * Get a list of pictures from a file directory
   * 	 * 
   	 */
  public ArrayList getPicturesInFileDirectory(String _dir, boolean _deeper) {
    ArrayList pictures = new ArrayList();
    setCursor(new Cursor(Cursor.WAIT_CURSOR));
    // System.out.println("file" + thisFile);
    File firstDirectory = new File(_dir);
    File[] sourceDirFilesArray = firstDirectory.listFiles();
    for (int f = 0; f < sourceDirFilesArray.length; f++) {
      File daFile = sourceDirFilesArray[f];
      System.out.println("File: " + daFile.getName());
      if (daFile.isDirectory()) {
        if (_deeper) {
          getPicturesInFileDirectory(daFile.getName(), _deeper); // recursive
        }
      } 
      else {
        String namer = daFile.getName().toLowerCase();
        if (namer.endsWith(".jpg") || namer.endsWith(".gif") || namer.endsWith(".png")) {
          BufferedImage bi = null;
          try {
            bi = ImageIO.read(daFile);
          } 
          catch (IOException e) {
            e.printStackTrace();
          }
          pictures.add(bi);
        }
      }
    }
    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    return pictures;

  }

}
Search
  Page last modified on February 02, 2009, at 12:48 PM