Friday, January 22, 2010

A simple Java class for running scripts against an image

I like to do a bit of 2D and 3D graphics programming in my spare time. The trouble is, Java gets a bit heavy at times, and I look for ways to test new ideas quickly. Testing ideas quickly means scripting. But how do you get at pixel values with JavaScript?

The answer is, you write a super-simple Java class that can load an image and hand off pixels to the JavaScript context. The following is such a class.
/*
ImageMunger
Kas Thomas
http://asserttrue.blogspot.com/

Public domain code.

All it does is open an image, display it in a window,
and run a script file. Usage:

ImageMunger myimage.jpg myscript.js

The JavaScript file will (at runtime) have two global variables,
Panel and Image, in scope. They correspond to the
ImagePanel inner class instance and the BufferedImage
that's displaying in the panel. That way, your script
can easily manipulate the image and/or the panel.

*/

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class ImageMunger {

// This inner class is our canvas. We draw the image on it.
class ImagePanel extends JComponent {

BufferedImage theImage = null;

ImagePanel( BufferedImage image ) {
super();
theImage = image;
}

public BufferedImage getImage( ) {
return theImage;
}

public void setImage( BufferedImage image) {
theImage = image;
this.updatePanel();
}

public void updatePanel() {

invalidate();
getParent().doLayout();
repaint();
}

public void paintComponent( Graphics g ) {

int w = theImage.getWidth( );
int h = theImage.getHeight( );
g.drawImage( theImage, 0,0, w,h, this );
}
} // end ImagePanel inner class

// We need to keep a reference to the ImagePanel:
public ImagePanel theImagePanel = null;

// Constructor
public ImageMunger( String [] args ) {

parseArgs( args );

// open image
BufferedImage image = openImageFile( args[0] );

// create window
theImagePanel = new ImagePanel( image );
JFrame gMainFrame = new JFrame();
gMainFrame.setTitle( args[0] );
gMainFrame.setBounds(50,80,
image.getWidth( )+10, image.getHeight( )+10);
gMainFrame.setDefaultCloseOperation(3); // dispose
gMainFrame.getContentPane().add( theImagePanel );
gMainFrame.setVisible(true);

}

ImagePanel getImagePanel( ) {

return theImagePanel;
}

BufferedImage openImageFile( String fname ) {

BufferedImage img = null;

try {
File f = new File( fname );
img = ImageIO.read(f);
}
catch (Exception e) {
showMessage("Trouble reading file.");
e.printStackTrace();
}

return img;
}

public static void runScriptFromFile( String fileName,
ScriptEngine engine ) {

try {
engine.eval(new java.io.FileReader( fileName ));
}
catch( Exception exception ) {
exception.printStackTrace();
showMessage( exception.getMessage() );
}
}


public static void showMessage(String s) {
javax.swing.JOptionPane.showMessageDialog(null, s);
}

void parseArgs( String[] args ) {

if ( args.length < 2 )
tellUserHowToUseThisApp( );
}

void tellUserHowToUseThisApp( ) {
showMessage( "Supply an image file name and a script file name." );
}

// main()
public static void main( String[] args ) {

ImageMunger munger = new ImageMunger( args );

// create a script engine manager & engine
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");

engine.put( "Image", munger.getImagePanel( ).getImage( ) );
engine.put( "Panel", munger.getImagePanel( ) );
engine.put( "args" , args );

// evaluate JavaScript code from file
runScriptFromFile( args[1], engine );
}
}

This Java app does two things, based on arguments provided on the command line. First, it opens an image of your choice (you supply the file path as the first command-line arg) in a JFrame. Secondly, it opens and executes the JavaScript file whose path you supply as the second command-line argument.

Before executing the script, the Java app puts two variables, Image and Panel, into the JavaScript runtime scope. (These are references to the BufferedImage object, and the JComponent that renders it, respectively.) That way, it's easy to manipulate the image and/or its JComponent at runtime, using script.

Here's an example. Suppose you want to convert a color JPEG into a grayscale (black and white) image. You would write a script like the following and put it in a .js file on disk. Then run the ImageMunger app and have it execute the script.


// desaturate.js
// Converts RGB image to grayscale
.

( function desaturate( ) {

if (Image == null) {
java.lang.System.out.println("Nothing to do; no source image." );
return;
}

var w = Image.getWidth();
var h = Image.getHeight();
var pixels = Image.getRGB( 0,0,w,h,null,0,w );
var tmp;

for ( var i = 0; i < pixels.length; i++ ) {

// get Green value
tmp = 255 & (pixels[ i ] >> 8);

// set Red, Green, and Blue channels the same
pixels[ i ] = (tmp << 16) | (tmp << 8) | tmp;
}

Image.setRGB( 0,0,w,h,pixels,0,w );
Panel.updatePanel( );
} ) ( );

No real magic here. The script just grabs pixels from the BufferedImage (via the Image global that we put into the JS scope), converts all pixels in the image to monochrome RGB values, stuffs the pixels back into the image, and requests a redraw of the ImagePanel (using the Panel global).

No rocket science. Just quick-and-dirty pixel banging. Perfect if you're into peeking and poking pixels late at night but like to avoid getting Java under your fingernails just before climbing into a clean bed.

48 comments:

  1. Anonymous5:04 AM

    Where is the demo link?

    ReplyDelete
  2. You can do this with Flash, too. Or just by using the canvas element.

    ReplyDelete
  3. Think you're missing the point TmDean. Sure you can do graphics in alternative languages/technologies but this demonstrates server side Java scripting.

    ReplyDelete
  4. I am trying to use this ImageMunger, but I have zero knowledge to where to put the code so I can run it using JAVA command?

    ReplyDelete
  5. Really loved reading your blog. keep blogging.
    Top Web Design Companies

    ReplyDelete
  6. Thanks for the information. It's very useful. If any business looking for best web design & digital marketing in Minneapolis, check our website now for the best Minneapolis web design.

    ReplyDelete
  7. My Assignment help is the best online assignment writing service provider that offers skillful assignments for the students. We have the best team of experts who can provide the best assignment help.

    ReplyDelete
  8. The blog written is extremely impressive, with a great topic. However, a bit more research could have strengthened it even further. You can explore the services as offered by livewebtutors.com, a premium academic writing services platform offering the best of Vancouver Referencing Generator teamed with knowledge and experience.

    ReplyDelete
  9. Congratulations on receiving a great response to your post! We at the Myassignmenthelpau platform understand how difficult it can be for the students to manage complicated assignments in high school, college, or university, therefore, we have introduced an
    exclusive Assignment Help facility that will cater to all your writing requi ements precisely.

    ReplyDelete
  10. I really enjoy reading your impressive post. Keep doing and update more information.
    For more information about web design go to https://www.login4ites.com/

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. This comment has been removed by the author.

    ReplyDelete
  13. Wonderful Article, Thanks for Putting This Together! This Is One Great Post. My assignment help Is Providing Online Assignment help New Zeeland from the Qualified Expert. I Have Written Many Contents on Case Study Help, Essay Writing Service, CDR Report Writing, Proofreading Services and More. You Can Email us at cs@myassignmenthelpau.com or Phone Number: +44-20-8144-9988

    ReplyDelete
  14. That was a great write-up. Keep up the good work. It is high time you beat academic stress with the supreme assignment help vancouver service by the livewebtutors platform. Receive flawless solutions that can easily woo your mentors and professors at extremely affordable
    rates

    ReplyDelete
  15. The details of the write-up were amazing! Keep up the good work. Talking about details, the diligent Essay help USA experts of the LiveWebTutors platform are highly qualified to handle the challenging academicwriting tasks efficiently. They are well known for delivering plagiarism-free content in every order.

    ReplyDelete
  16. Essay Help Zone offers you online essay editing services. Their professional essay writers are capable of making your essay 100% authentic and reliable. They check and fix the gaps in your essay writing. The entire team is professionally trained for writing academic essays. They follow the right procedures of writing that give them a result of plagiarism-free writing.

    ReplyDelete
  17. The American Psychological Association reference style is one of the Author-Date reference styles.We provide you best harvard apa referencing

    ReplyDelete
  18. When it comes to providing best assignment service online,
    Unique Submission makes sure to complete assignment antecedently to offer scholars enough time to proof read the given assignment
    before submitting it to their tutors/professors. We never compromise to timely delivery and deadlines given by our customers.

    Case Study Writing Help

    ReplyDelete

  19. The blog is quite resourceful, however a touch of the professionals can diversity it even further. Visit myassignmenthelpau.com and watch how the experts promise a fine quality Assignment Help Sheffield. The best experts in the business are here to take care of your academic needs.

    ReplyDelete
  20. If you are a student looking for Assignment Help Canberra then you should academic services from GreatAssignmentHelp.com. They provide some great academic services in Canberra, which is worth every penny you pay them.

    ReplyDelete
  21. We are providing CDR Writers Australia. If anybody requires to get CDR For Australia Immigration for successful visa migration approval in Australia, communicate with our experts and visit our website CDRAustralia.Org.
    Mail us at: Contact@CDRAustralia.Org.

    Our other Services:
    RPL Writing Services
    NER work experience statement
    Competency Based Assessment For Papua New Guinea
    RPEQ Australia

    ReplyDelete
  22. I look forward to fresh updates and will share this website with my Facebook group!
    Find your HP printer support
    Easy way for How to connect hp printer to wifi
    Why is my HP printer offline

    ReplyDelete
  23. It's really a nice and useful piece of info.
    Setup your ms office from office.com/setup |
    How to set up Data Loss prevention Microsoft Office 365 ?
    How to get microsoft Office 365 for free ?
    Do you know you can Install office without account .
    Differences between Microsoft Office vs Office 365 ?
    How to Create Windows 10 recovery USB

    ReplyDelete
  24. How McAfee Total Protection helps you to be secure on the internet?
    What is McAfee LiveSafe Security.
    How to Register McAfee on Lenovo ?
    How to Register McAfee on dell ?

    ReplyDelete
  25. I look forward to fresh updates and will share this website with my Facebook group!
    McAfee programming gives the digital security services to ensure your hardware information.Install mcafee from www.mcafee.com/activate |
    How to use McAfee Removal tool ?
    What is McAfee total protection Error while installing updates on Mac ?
    What is McAfee LiveSafe Connect VPN and its benefits?
    What are McAfee LiveSafe Installation and its features ?

    ReplyDelete
  26. Checking every unit in a rental business is vital to dealing with numerous properties. Quicken Rental Property Manager helps by putting away information on every rental company, regardless of whether it's an independent home or a unit in multifamily construction. The worth of the investment properties you own adds to your total assets similarly to other individual property, so Rental Property Manager offers the alternative to follow this part of your resources. Try not to stress on the off chance that you need to get the lease assortment fully operational rapidly. You can add esteem following some time in the not too distant future. To learn more, you can visit our Website or can contact us.

    ReplyDelete
  27. Do you need Nursing Assignment Help within a stipulated deadline? Get higher grades in nursing assignments with our online help. My Assignment Help has a team of subject knowledge experts who come from diverse academic backgrounds and have been associated with the field of a homework assignment and project writing as lecturers, professors and education industry practitioners. Order now to get the best Nursing Assignment Help from the experts.

    ReplyDelete
  28. IT assignment help is all about the multipurpose usage of software and hardware, also of different supporting systems for storing, presenting, exchanging, manipulating, and retrieving data. You may already know that that it is a broad concept and this is why it has been classified into some fragments. Each of them is a prolonged concept in itself and needs a detailed study. It is quite obvious that no student can master all of them. This is why our and make things bit easier for you. We are at assignment help. Assignment helps under our IT assignment help so that students can complete their assignment on time and score good marks.

    ReplyDelete
  29. I acknowledge you so much for giving this valuable information. I am applauding to discover your post. We are the Best provider of CDR Report Engineers Australia. Visit CDR Australia for detail information.
    Also visit :
    CEng Report For UK Council
    RPEng Australia
    Kindly mail us at Contact@CDRAustralia.Org

    ReplyDelete
  30. I highly appreciate the efforts of the author to share the vital subjective knowledge. I request him to carry on their sharing as much as they can. Making the mutual bonding of trade, it is convenient to stay on Assignment Help Online co-operation to make you academic journey convenient.

    ReplyDelete
  31. I have visited your site for the first time. It is a really good site. I liked it very much and I have also shared this site with my special friends. I have also created a few sites that everyone liked very much. hire assignment writer

    ReplyDelete
  32. Get the best expert advice for writing Do My Coursework online. Our work is plagiarism-free, reliable and mistake-proof. We ensure you quality Assignment Support Service.
    Visit our website: Do My Coursework

    ReplyDelete
  33. I have seen your post and I really found it very informative, we give online assignment help to students at genuine price.

    ReplyDelete
  34. Wow! Great quality content. Are you also looking for Finance assignment help Canada because you do not know how to make top-quality projects? Take the academic writing assistance from professional writers and get the top-class projects written in the least amount of time.

    ReplyDelete
  35. This is top quality content, Also know about AppSquadz, which is the best mobile app development company Gurgaon, their developers are highly experienced and they are giving full client satisfaction for more than 12 years.

    ReplyDelete
  36. We provide Global Assignment Help writing services in Australia, USA & UK for University Students. Exclusive offers get best assignment help 25% discount on each.

    For more info:- https://www.assignmenthelpexperts.com/global-assignment-help/

    Contact us at info@assignmenthelpexperts.com or call us at +61-3-9088-1335 for more information.

    ReplyDelete
  37. The Hbomax support on shiny TVs is a gift for everyone. As soon as you connect to the hbomax app on a smart TV or other device, your device displays an 8-digit code. This is the Hbomax activation code that is used to log into hbomax.
    hbomax.tvsignin

    ReplyDelete
  38. Great work. Do you want help with case study assignment help? sourceessay.com will be ideal place to explore numerous blog on different subjects. Essay typer New York

    ReplyDelete
  39. HBO Max constitutes a go-to platform for many people to entertain with streaming content in a flawless manner. Whether with movies, web series or even tutorials, HBO Max is the place to be. While you can go for HBO Max on your smartphone and computers with Internet connectivity as well as a supported browser, watching HBO Max on TV is a simple luxury. HBO Max smart TV support can easily be activated with the hbomax.com/tvsignin code link.
    Hbo max/tv signin

    ReplyDelete
  40. This is such a great resource that you are providing and you give it away for free.twitch.tv activate I love seeing blog that understand the value of providing a quality resource for free.
    twitch.tv/activate

    ReplyDelete
  41. Great work. Do you want help with case study assignment help? sourceessay.com will be ideal place to explore numerous blog on different subjects. Do my assignment Leeds

    ReplyDelete
  42. Great work. Do you want help with case study assignment help? sourceessay.com will be ideal place to explore numerous blog on different subjects. Research proposal Sydney

    ReplyDelete
  43. YouTube is a famous platform, which people use widely for streaming videos, movies, web series, tutorials, channels, educational content etc. You can play and watch YouTube videos on any device that shows an active internet connection and video support. But, there are situations when you do not want to connect to Wi-Fi, and still need access to YouTube on your television. In that case, you can connect to YouTube via code. You can follow this at tv.youtube.com/start enter code. It will serve your purpose. The explanation of the entire procedure to connect to the code is below.
    tv.youtube tv/start |
    venmo login |
    Coinbase pro login |
    ij.start.canon |
    youtube.com/activate |


    Outlook email - formerly called Hotmail and which also went by the name msn hotmail is one of the leading email services, second only to Gmail.

    ReplyDelete
  44. Garmin Express is an application that is utilized to oversee, set up, and register the Garmin devices. It is useful for clients in installing all the software and guide updates. At whatever point new updates are accessible, it gives you warnings simultaneously. Clients can save their ideal guides and areas with Garmin Express and can see the information on the navigation device. Thus, garmin.com/express guarantees fast and exact navigation.

    ReplyDelete
  45. Funding is a money management science. The focus is on numbers. Asset and liability dynamics are integrated into its overtime under a variety of risks and uncertainties. This topic is picked by the numbers and markets interested. The professionals can improve your academic characteristics and spare your time by obtaining assistance from management. In addition, financing for a myriad of factors has become a lucrative alternative. Most institutions worldwide provide a wide variety of management courses. Comprehensive management skills help students create a successful business career. Students getting assignments after enrolling in such classes is how their professors assess what their students are learning and how their foundation is built. Our management assignment help absolutely could be helpful for this kind of student.

    ReplyDelete
  46. This article is such a nice and interesting one, I'm very satisfied with the provided contents. I hope more excellent articles would be posted in your website. Thank you so much for this and keep sharing. Get best Dubai App Development service of app developer you visit here site for more info.

    ReplyDelete

Add a comment. Registration required because trolls.