We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
Posting to web > code (Read 2097 times)
Posting to web > code
May 27th, 2005, 1:41pm
 
I made a script that converts screen to jpg, then to base64, then posts it to a php-file, which converts it back to jpg, and saves on server.
Remember to set folder with php-file in to writable (chmod 777)

Code:

usage:
Post p;

void setup()
{
size(200,200);
p = new Post();
}

void draw()
{
rect(20,20,40,50);
if(mousePressed) p.postIt();
}

// ----------- POST CLASS ----------- //
class Post {
/* Name of file to be sent. */
String[] parameter = { "img", };
String[] value = { "", };
String urlMail = ">INSERT URL TO PHP-FILE<";

void postIt() {
encode(bufferImage());
postNewItem(parameter,value,urlMail);
}

boolean postNewItem (String[] Par, String[] Val, String strURL) {
boolean ret = false;

try {
URL url;
URLConnection urlConn;
DataOutputStream dos;
DataInputStream dis;
String s = "";
String S = "";

url = new URL(strURL);
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");

dos = new DataOutputStream (urlConn.getOutputStream());

// generate the post-string
for (int i=0; i<Par.length; i++)
{
if (S.length() > 0) S += "&";
S += Par[i] + "=" + Val[i];
}

// SEND
String message=S;
dos.writeBytes(message);
dos.flush();
dos.close();

// RECIEVE
dis = new DataInputStream(urlConn.getInputStream());
s = dis.readLine();
println(dis.readLine());
println(dis.readLine());
println(dis.readLine());
println(dis.readLine());
println(dis.readLine());
dis.close();

println(s); // if it outputs success, and nothing happens check this out..
if (s != "") { // Got Some reply
ret = true;
}
else {
ret = false;
}

} // end of "try"

catch (MalformedURLException mue) {
;
}
catch (IOException ioe) {
;
}
return ret;
} // end of postNewItem() method


String BaseTable[] = {
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
"Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f",
"g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v",
"w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"
};

void encode(ByteArrayOutputStream bout) {
// read file into bytes
byte bytes[] = bout.toByteArray();
int n = bytes.length;

if (n < 1) return; // no bytes to encode!?!

byte buf[] = new byte[4]; // array of base64 characters

int n3byt = n / 3; // how 3 bytes groups?
int nrest = n % 3; // the remaining bytes from the grouping
int k = n3byt * 3; // we are doing 3 bytes at a time
int linelength = 0; // current linelength
int i = 0; // index

// do the 3-bytes groups ...
while ( i < k ) {
buf[0] = (byte)(( bytes[i] & 0xFC) >> 2);
buf[1] = (byte)(((bytes[i] & 0x03) << 4) |
((bytes[i+1] & 0xF0) >> 4));
buf[2] = (byte)(((bytes[i+1] & 0x0F) << 2) |
((bytes[i+2] & 0xC0) >> 6));
buf[3] = (byte)( bytes[i+2] & 0x3F);
value[0] = value[0]+BaseTable[buf[0]];
value[0] = value[0]+BaseTable[buf[1]];
value[0] = value[0]+BaseTable[buf[2]];
value[0] = value[0]+BaseTable[buf[3]];


if ((linelength += 4) >= 76) {
//value[0] = value[0]+"\n";
linelength = 0;
}

i += 3;
}

// deals with with the padding ...
if (nrest==2) {
// 2 bytes left
buf[0] = (byte)(( bytes[k] & 0xFC) >> 2);
buf[1] = (byte)(((bytes[k] & 0x03) << 4) |
((bytes[k+1] & 0xF0) >> 4));
buf[2] = (byte)(( bytes[k+1] & 0x0F) << 2);
}
else if (nrest==1) {
// 1 byte left
buf[0] = (byte)((bytes[k] & 0xFC) >> 2);
buf[1] = (byte)((bytes[k] & 0x03) << 4);
}
if (nrest > 0) {
// send the padding
//if ((linelength += 4) >= 76) value[0] = value[0]+"\n";
value[0] = value[0]+BaseTable[buf[0]];
value[0] = value[0]+BaseTable[buf[1]];
if (nrest==2) {
value[0] = value[0]+BaseTable[buf[2]];
}
else {
value[0] = value[0]+"=";
}
value[0] = value[0]+"=";
}
}
}
import com.sun.image.codec.jpeg.*;

ByteArrayOutputStream bufferImage(){
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage img = new BufferedImage(width, height, 2);
img = (BufferedImage)createImage(width, height);
loadPixels();
for(int i = 0; i < width; i++)
{
for(int j = 0; j < height; j++)
{
int id = j*width+i;
img.setRGB(i,j, pixels[id]);
}
}
try{
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(img);
}
catch(FileNotFoundException e){
System.out.println(e);
}
catch(IOException ioe){
System.out.println(ioe);
}
return out;
}


Re: Posting to web > code
Reply #1 - May 27th, 2005, 1:41pm
 
Code:

// ---- PHP FILE ---- //
<?
$filename = "wcam.jpg";

base64_to_jpeg($filename);

function base64_to_jpeg( $outputfile ) {
/* read data (binary) */
//$ifp = fopen( $inputfile, "rb" );
$imageData = $_POST['img'];//fread( $ifp, filesize( $inputfile ) );
//fclose( $ifp );
/* encode & write data (binary) */
$ifp = fopen( $outputfile, "wb" );
fwrite( $ifp, base64_decode( $imageData ) );
fclose( $ifp );
/* return output filename */
return( $outputfile );
}
?>



sincerly
seltar
Re: Posting to web > code
Reply #2 - May 30th, 2005, 1:56pm
 
So what would I have to modifiy to change the jpeg compression? I'm guessing it's in the encode bit, but I'm a little lost ...
Re: Posting to web > code
Reply #3 - May 30th, 2005, 6:41pm
 
something like this:
Code:

>After JPEGImageEncoder<
JPEGEncodeParam encpar = encoder.getDefaultJPEGEncodeParam(img);
encpar.setQuality(1,true); // 0.0-1.0, force baseline (?)
>Before encoder.encode(img)<


---EDIT---
AND change encoder.encode(img); to encoder.encode(img,encpar);
Re: Posting to web > code
Reply #4 - Jun 29th, 2005, 2:57pm
 
i can't make it work. i've uploaded a .zip file here if someone has a minute to check if i am doing something wrong:
www.beyondthree.com/_dev/save_jpeg2.zip

*

i've copy/pasted all the code from above and compiled it with processing 0091 on my Apple G4 laptop (running OSX 10.3.8).

once placed on the server, i chmod'ed the folder and all the files to 777.

when i run the applet nothing happens. i've tried both with a relative path to the .php file and a relative path.

if type the URL for the php file in my browser, it creates an empty .jpeg (0k) file on the server, so it seems like it's got all the permissions it needs... i'm guessing the information just doesn't gets send correctly from the applet.

*

any pointers / help is very much appriciated - this would be very usefull and cool to get working!

thanks for sharing.

thanks,
mikkel
Re: Posting to web > code
Reply #5 - Jun 29th, 2005, 3:55pm
 
mikkel, i'd recommend to always at least put a "e.printStackTrace()" into your "catch" clauses to see if an error actually occured. at the moment, ignorance is != bliss... Wink

having said and changed that, you can see that "savefile.php" is not a valid URL. you'll have to turn into an absolute one like http://www.beyondthree.com/_dev/savefile.php and it should work...
Re: Posting to web > code
Reply #6 - Jun 29th, 2005, 5:34pm
 
thanks toxi!
well, small steps in the right direction.

now the applet manages to create a 2k file on the server, but the file has errors, see it here:
http://www.beyondthree.com/_dev/save_jpeg2/saved-img.jpg

ok, it can't be seen in a browser window, but after opening it in photoshop this is what you see:
http://www.beyondthree.com/_dev/save_jpeg2/saved-img_psd.jpg

any ideas?... has anyone gotten this working?
can you zip the folder on your server and share it?

thanks,
+ mikkel
Re: Posting to web > code
Reply #7 - Jun 30th, 2005, 5:11pm
 
just had another look and made some more tiny changes. looks like it's fixed now...

...

i think there was something slightly wrong with the way the image data has been set in the encode() function. i replaced it with:

Code:
// [toxi20050630] fixed colour model setting and added JPEG quality
ByteArrayOutputStream bufferImage(){
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage img = new BufferedImage(
width,
height,
BufferedImage.TYPE_INT_RGB
);
loadPixels();
img.setRGB(0,0,width,height,pixels,0,width);
try{
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam p=encoder.getDefaultJPEGEncodeParam(img);
// set JPEG quality to 50% with baseline optimization
p.setQuality(0.5,true);
encoder.setJPEGEncodeParam(p);
encoder.encode(img);
}
catch(FileNotFoundException e){
System.out.println(e);
}
catch(IOException ioe){
System.out.println(ioe);
}
return out;
}


the entire sketchbook is zipped up here:
http://toxi.co.uk/p5/save_jpeg/save_jpeg2.zip
Re: Posting to web > code
Reply #8 - Jul 1st, 2005, 12:09am
 
Hey, I was playing around with the code getting it to work. I think its a really nice job you've done getting JPEG data out of processing onto a webserver. Pretty handy.

The code could do with being a bit more modulated, perhaps even built as a library? Instead of buffering and converting the image, why not make it more generic - say someone supplies any PImage object and the method sorts out the rest.

Anyhow, I made this little applet that lets you dynamically set the quality and save to my server. I modified some of the methods so that I could define a custom quality, and a custom file name, and custom web address.

http://mkv25.net/applets/webSaveJPG/
(Refresh the loaded image after you click if you don't see the latest one)

Oh, and also.. the security on the PHP script thingy kinda(sucks)... definitely need to improve upon that. I'll see if I can dig some better code. I wrote a PHP script called FIAF (http://mkv25.net/showcase/) that does a quite nice job at filtering dodgey file types and limiting against filesize, width/height (images) etc. on HTTP uploads. I should be able to port some of it over.
Re: Posting to web > code
Reply #9 - Jul 1st, 2005, 11:14am
 
Ohoy.. back in norway, and gotten my computer, so now i'm back in business..
Yeah, that code i posted is getting a bit outdated, i changed it to something more like toxis a while ago..

and yeah.. a library would be the best way to use this.. perhaps even with a phpfile which can write php-files to server, so that it's All done in the processing library.. but that was just of the top of my head, so i'll have to think about that for a while..

but, still.. i'm glad this is coming in handy Smiley
let me know if you work anything out, and i'll try to do it myself as well .. Smiley maybe even a write-file-to-server library, not just image-to-server..

-seltar

(good to be back)
Re: Posting to web > code
Reply #10 - Jul 1st, 2005, 11:32pm
 
just for the record, maybe 1% of this code was contributed by me. all i did was fixing the existing example posted above, nothing more. but of course a general "post form data" library would be handy for such things. re: data security - the least thing would be to embed some sort of CRC/hash (e.g. MD5/SHA1sum) in the base64 data stream...
Re: Posting to web > code
Reply #11 - Jul 4th, 2005, 11:32am
 
thanks guys - now i've got it working too! Smiley

+ m
Page Index Toggle Pages: 1