Wednesday, October 17, 2012

xPage: Optimize Uploaded Image

I had a task to upload images in xPage. The next one is to optimize image lossless. User upload the image in to the Domino media library and the image optimizing on the fly.

Unfortunately there is no good Java solution for lossless optimization of images. There are set of solution to use third party command line programs and run it from java. The problem is that you need to install this program on the server, many of them supports only one OS, so if you have Domino server on the windows and then would move to the Linux (or vice verse) you got a problem.

I decide to use online optimizer. It looks like there is no good paid online services with a good API. So I start from the free one. It is well known Yahoo! Smush.it.

Smush.it has no API, but there is a guy who create stand alone java API for Smush.it service. He did it in the way of command line tool, but it could be used as API in your application.

I like it! The only one problem is that program out process information (log) directly in to the System.out. I need some information to be printed in to my log.nsf and some information to be returned to the user. So I add ability to put StringBuilder object in to the Smush.it API.  

Code example:

//log and statistic contains information 
//about process and compression result 
// 
//file - file to optimize, 
//generally opt rewrite file, but not in all cases. 
//Look "Important" section 
// 
//opt - optimized file

StringBuilder log = new StringBuilder();
StringBuilder statistic = new StringBuilder();

SmushIt smushIt = new SmushIt();
smushIt.setVerbose(log);
smushIt.setVerboseStatistic(statistic);     
smushIt.addFile(file.getCanonicalPath());
List<smushitresultvo> smushItResultVos = smushIt.smush();

ImageDownloader imageDownloader = 
 new ImageDownloader(file.getParent());
imageDownloader.setVerbose(log);

File opt = imageDownloader.download(smushItResultVos.get(0));      

StringBuilder log variable after running code:

Smushing files:

C:\Windows\Temp\notesE3A053\xspupload\0001.jpg

Adding file:C:\Windows\Temp\notesE3A053\xspupload\0001.jpg
{"src":"0b2c68eb%2F0001.jpg","src_size":40895,
"dest":"http:\/\/ysmushit.zenfs.com\
/results\/0b2c68eb%2Fsmush%2F0001.jpg",
"dest_size":38749,
"percent":"5.25","id":""}

Downloaded smushed image - 
http://ysmushit.zenfs.com/results/0b2c68eb%2Fsmush%2F0001.jpg
Saved image - C:\Windows\TEMP\notesE3A053\xspupload\0001.jpg

StringBuilder statistic variable after running code:

Source Image:0001.jpg
Source image size:40895
Smushed image size:38749
Percentage saving:5.25

Projects on github:
https://github.com/andriykuba/smushit
https://github.com/abhirama/smushit

No comments: