Archive for the ‘Utility’ Category

Resize Image Utility

Friday, February 6th, 2009

Java has excellent capability for images, sound, multimedia, etc. I developed this utility to, yes you guessed it, save some cycles and pain and aggravation for yours truly. This utility takes an image and resizes it based on input parameters. It requires three parameters: 1) url to the image, 2) width you want the resized image, 3) height you want the resized image. Now, as everybody know, it is impossible to resize objects exactly as asked for and keep a decent aspect. If I try, for example to take a large photo and resize it to 100×100, well… it’s not going to look good. The utility resizes while keeping the image “viewable”, so if I ask to resize to 100×100, the utility will select the best ratio. It still may look nasty, but as least it is consistently nasty!

The utility works for all images, but it works best for jpg. URLs to images behind ssl will not work. I suppose I could set up ssl connection, but… nah. Why make this hard! If you are faced with this issue, I suggest copying ssl image to your hard drive and point the utility there.

If you are using a Mac, trying this out will be easy. All you have to do is copy the code (see below) to a file, save it, compile it and run it. That’s it sports fans. Have I mentioned that I love my iMac? All the jar files were already setup and I did not even have to include a class path! Insane. For those out there who have run java programs before, you know that finding the necessary jar files can be a PIA. Well, if you are not using a Mac, all bets are off. You are on your own, although I run this at work on Windows XP.

At work, I made a slight modification to the utility to accept - in addition to url - a directory. Being able to ingest everything in a folder and resize is sweet. All I do is copy all the images I want to a folder and point the utility to it. Double sweet.

Note to reader: Adobe Photoshop does a better job of resizing images.

Run from my Mac:
javac ResizeImage
java ResizeImage http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/800/orca-killer-whale.jpg 300 300

Image before: http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/800/orca-killer-whale.jpg

Image after: http://www.csatechconsulting.com/blog/wp-content/uploads/2009/02/staticfilesngssharedstaticfilesanimalsimages800orcakillerwhale.jpg

ResizeImage.java:

import java.io.*; import java.net.URL; import java.net.MalformedURLException; import com.sun.image.codec.jpeg.*; import java.awt.*; import java.awt.image.*; public class ResizeImage{ public static void createThumbnail(String url, String width, String height){ try{ // get url handle URL my_url = new URL(url); // get image object so we can get width, height of image Image image = Toolkit.getDefaultToolkit().getImage(my_url); // let's track the object MediaTracker mt = new MediaTracker(new Container()); mt.addImage(image, 0); // wait for image to load mt.waitForID(0); // convert input width/height to integers int thumbWidth = Integer.parseInt(width); int thumbHeight = Integer.parseInt(height); double thumbRatio = (double)thumbWidth / (double)thumbHeight; // get width/height of image int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double)imageWidth / (double)imageHeight; if (thumbRatio < imageRatio) thumbHeight = (int)(thumbWidth / imageRatio); else thumbWidth = (int)(thumbHeight * imageRatio); BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); // resize image Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); // extract the file name from the url and replace "evil" characters String fName = my_url.getFile().replaceAll("/","").replaceAll(":","").replaceAll("-",""); // create output file BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fName)); // write resized image to output file JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = Integer.parseInt("100"); // we want good quality quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float)quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); // close output file out.close(); } catch(MalformedURLException e){ e.printStackTrace(); } catch(Exception e){ e.printStackTrace(); } } public static void main(String[] args){ // must have 3 parameters: 1) url of image, 2) width you want the new image, 3) height you want the new image String url = args[0]; String w = args[1]; String h = args[2]; createThumbnail(url, w, h); } }

Printing CGI Environment Variables

Monday, February 2nd, 2009

A Web/Application server interacts with CGI (Common Gateway Interface) scripts via environment variables. These variables are set by the server running the script and may be accessed (read only) by the script.  As noted, they are set every time a script is run. I have used the QUERY_STRING variable in the past to get the string that was passed to the script. I think of these as session variables that you can not create and/or update that contain server information.

I also have used the HTTP_REFERER to refer back to who called the script.


Env.pl

#!/usr/bin/perl print "Content-type: text/html\n\n"; foreach $key (sort keys(%ENV)) { print "$key = $ENV{$key}<p>"; }

Click here to see my web server variables
CGI Info: http://www.cs.unc.edu/Courses/jbs/lessons/www/arch/cgi/

Utility that Finds and Replaces String In File

Sunday, January 25th, 2009

This is a handy utility that finds and replaces a text string in one or more files using Perl regular expression.

I frequently use this to globally change text when I have many files that I need to change. Not long ago, I had 38 xsl attachments that I had to change because the path to my css changed. All the reorganizations are insane! Next change is to store the css as an Oracle artifact. Anyway,  I have half of my object in a weblogic container, but I decided to change those manually. Since the attachments are stored in Oracle as Blobs, I used my Download java program to extract the attachments to disk. Then I used this utility to change the 38 files to the new css file path. Then I used my Upload java program to load them from disk back to the Oracle Blob. This literally took 20 minutes to do, and since I did not have to rely on manually (i.e. fat fingering) doing the changes, there were no runs, no drips, and more importantly no errors!

You may ask why I did not use this method for the files in the container. There are approximately 200 files in the container. In case the pooch was injured (i.e. I screwed up), I have backups, for sure, but said backups are not easily obtained. How difficult you ask. Jumping through fire hoops after skinny dipping in a gasoline bubble bath comes to mind. I would not go so far as to say that I was concerned about the possibility of doing extra work, although the thought did cross my mind, but I really dislike fire and I absolutely dislike the backup custodian, and did not want to take a chance dealing with either.

Example:

Windows: perl -pi.bak -e “s/old-css-path/new-css-path/g” 1.xsl 2.xsl 3.xsl

Mac: perl -pi.bak -e ’s/old-css-path/new-css-path/g’ *.xsl

The ‘g’ modifier (at the end of the expression) will replace all occurrences in the file. Omitting the ‘g’ will only change the first occurrence. Include the ‘i’ modifier will do case-insensitive matching (find).

The above example (windows version) changes three files; 1.xsl, 2.xsl, 3.xsl in the current directory,  make a backups copy (i.e. 1.xsl.bak) of each file, and changes the string ‘old-css-path’ to ‘new-css-path’ if applicable.

Note: I could not get the wildcard ‘*’ to work in the windows environment. It seems to me that ‘*.xsl’ should work, but no such luck. You can stack them up as shown. Oh well, Windows lovers; you’re out of luck. It worked as advertised on my iMac running OS X . Go figure. Also, note that I have to use double quotes around the expression in windows. I received errors otherwise.

switches:
‘p’ - loops over code segment

‘i’ - specifies edit in place, including extension will make backup of file before changing

‘e’ - used to enter one or more lines of script in command line