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.

70 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
  47. Keep sharing such a great article! Are you stuck with your assignment? GoAssignmentHelp is one of the best Nursing Assignment Help providers that provide best engineering assignment help to those students who face these issues and write Artificial Intelligence Assignment Help and score good grades. Visit - Assignment Australia

    ReplyDelete
  48. There are a number of websites that provide online assignment help for various subjects, but to choose the one that provides the best service is very difficult. GoAssignmentHelp is the right place to go who is searching for someone for their economics assignments. I would recommend them because I use their services many times for different subjects and I feel glad for finding this portal. They promise to deliver top-quality Online Assignment Australia and they really mean it. They have highly qualified and well-experienced assignment writers who provide high-quality research material at amazingly lower pricing packages. I was worried about my complex economics Assignment writing. Then I took help from GoAssignmentHelp. I would have never able to complete my assignment myself. Their experts did it exceptionally well in a short span of time. I scored good grades just because they're accounting assignment help. I am pleased I made the right decision.
    Property Law Assignment Help
    Services Marketing Assignment Help
    Zoology Assignment Help
    Quantitative Analysis Assignment Help
    Astronomy Assignment Help

    ReplyDelete
  49. Besides our vast loaded catalogs of gifts and presents, we also have fast and reliable delivery services to send Women’s Day gifts to Mumbai, Delhi, Pune, Bangalore, and PAN India. In India, customers can also get prominent womens day gift delivery services internationally as well covering countries and nations like the UAE, the USA, Canada, Singapore, and many more.

    Women's Day Gifts

    ReplyDelete
  50. If you are still looking for trustworthy Assignment Help your search ends here. The GreatAssignmentHelper.com has got the largest team of expert professional writers offering stranded understudies perfectly convenient and bespoke compositions worthy of outstanding grades through its Online Assignment Help desk. Besides, we provide the most affordable Assignment Help UAE.

    ReplyDelete
  51. Make sure the surface where you are placing the printer is clean and close to Pc or laptop.Check the shipped components with your inkjet printer
    http //ij.start.canon,
    https //ij.start.cannon

    ReplyDelete
  52. Canon IJ Network Tool will get you through the network settings uninterruptedly. It is essentially required when you are attempting to get your printer connected to a different network because a new network tends to reset the printer’s existing network settings.The Canon IJ Printer Utility can be used to keep a check on your printer’s ink levels and cartridges and clean the ink tanks and paper feed rollers. Also, you can make adjustments to your Canon printer’s power settings.

    ReplyDelete
  53. Youtube.com/activate
    YouTube is the go-to stage for the vast majority to watch recordings in the present age. Whether you need to watch instructive instructional exercises, or motion pictures, or even web series, YouTube has it, and thus, it is the most well known video distributing and web based webpage as of date. While you can watch YouTube on any cell phone as lengthy it has video support and a web association as well as on PCs that have an upheld program with a web association, watching YouTube on TV is an alternate extravagance. YouTube support on brilliant TVs is a gift for everybody.
    https://os4youtube.com/activate.html

    ReplyDelete
  54. The ij.start.cannon setup process for every Canon model is almost similar, however the download through https //ij.start.cannon and http //ij.start.cannon installation process may differ. you can also visit canonsetup-canon.com/ijsetup website for same. Https //ij.start.cannon.Depending on your requirement, it offers a type printer including PIXMA, SELPHY, MAXIFY, etc. canon.com/ijsetup

    ReplyDelete
  55. Once you are done with the driver setup via canon.com/ijsetup , you will have to insert a pile of pages into the printer tray for printing the documents..

    Visit ij.start.canon | ij.start canon and find out the best way to download Canon printer drivers.
    All-in-one Canon Inkjet printers are suitable for home, business, school, and others to improve productivity. You can easily set up your Canon printer through drivers from Canon.com/ijsetup , wireless connection, USB, and a few components.

    ReplyDelete
  56. Canon drivers fully support and assists for all compatible products for all Window versions. We offer the required data to configure, utilize and install your Canon products on your Windows PC.canon is completely safe and secure. ij.start.canon |
    ij.start.cannon | ij.start.canon

    ReplyDelete
  57. Thank you very much for this extraordinary information.
    ติดต่อสอบถาม igoal88

    ReplyDelete

  58. Curry Leaves, er en lille perle i Sønderborg, der har fantastisk dejlig og velsmagende mad, take away ballerup og en forrygende god service. Curry Leaves er blevet en af vores yndlings restauranter i Sønderborg, og de fortjener den største ros. De får de største anbefalinger fra os.

    ReplyDelete
  59. Fermenters or stirred-tank bioreactors are small, economical, and sterilized process vessels used for cultivating heterotrophic microalgae. They utilize sensors, probes, and controlled clean-in-place systems to monitor conditions and maintain optimal levels of microbial growth.Fermenters Market find extensive applications in the manufacturing of numerous products, such as cellulose, ethanol, vinegar, lipase, citric acid, amylase, streptomycin, lactic acid, etc. They are also widely used in biological wastewater treatment, pulp and paper production, industrial solvents, etc. As the novel coronavirus (COVID-19) crisis takes over the world, we are continuously tracking the changes in the markets, as well as the industry behaviours of the consumers globally and our estimates about the latest market trends and forecasts are being done after considering the impact of this pandemic.



    Check here for more reports like this : Asia Pacific Vaccine Market, Micro Inverter Market, Albumin Market, Middle East and Africa Cybersecurity Market,Fibreglass Pipes Market, Vegetable Concentrates Market, Learning Management System Market, States Flooring Market, Sports and Energy Drinks Market, Brazil Healthcare, Sterilisation Services Market, Media Monitoring Tools Market


    ReplyDelete
  60. Thank You! For sharing such a great blog, I like to read the information you have mentioned in this blog is helpful for me. Visit Website: Rcedutalent

    ReplyDelete
  61. Get Quicken professional to know about quicken login, quicken software, quicken download .Quicken apps support most computing platforms like Windows, Mac, IOS, and Android. The latest version was also introduced with web-based services as well, which allows users to access their data files online from any computer and modify them within minutes.
    Get Full Information: Quicken Professional | Quicken Help Guide

    ReplyDelete
  62. Youre so right. Im there with you. Your weblog is definitely worth a read if anyone comes throughout it. Im lucky I did because now Ive received a whole new view of this. 먹튀검증사이트^^

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

    ReplyDelete
  64. This is such a great resource that you are providing and you give it away for free. for more information about abcs,nbcs and weathergroups you can visit to my websites.
    abc.com/activate
    nbc.com/activate
    weathergroup.com/activate

    ReplyDelete
  65. There are few important changes you can make to encourage your PC to run faster. I have written a blog regarding this.. Check out how to speed up computer | Printer Printing blank pages

    ReplyDelete
  66. Hello Everyone! I'm Ronald Frankeliene, an Online Dissertation Help expert who has been offering online Dissertation assistance for a long time duration. Many students have problems with their dissertations and are seeking help. If you're one of those who are facing the same issues, get in touch with us immediately. We have a team of experts to assist you in resolving your issue.

    ReplyDelete

Add a comment. Registration required because trolls.