A screenshot of the ImageToClass GUI

ImageToClass Tool

Convert image files to native Java code to avoid the tedium of importing them!

If you like this, check out SoundToClass.


This project was born as I was working on a Java program which needed to launch three different ways: from the main class, from an executable JAR file, and as an Applet. To do this, it had to import images three different ways depending on the context. If you've ever dealt with a similar problem, you know how much of a hassle it can be to import images into Java.

This tool solves that problem. It converts files from an image format, like .JPG, into a Java code file, with a .JAVA extension, which is a subclass of javax.swing.ImageIcon. To do this, it simply reads in the image data as an array of bytes and hard-codes those bytes into the generated Java file, which then uses them in its constructor.

In other words, this image gets converted into this code.


Download the tool here: ImageToClass

How to Use ImageToClass

This tool has a graphical interface which can be accessed by double-clicking ImageToClass.jar (an executable JAR file). It can also be used from the command line, with the following syntax:

	java -jar ImageToClass.jar source/path/and/name.ext [destination/path/and/name.java]

".ext" above must be the extension of a supported image format: GIF, JPG, JPEG, and PNG. If no destination file is provided, it defaults to the same path and name as the source file.

Source Code

The source is available, already zipped up as an Eclipse project file for your convenience: ImageToClass.zip

This software is freeware. Use it, abuse it, change it, whatever. I'd appreciate it if you kept my name somewhere on the GUI though.

In case you were wondering, yes, the image in the GUI was made using this very tool.

Consideration: Size Increase

The downside to this tool is that the .JAVA files it generates are significantly larger than the image files from which they came. The image I tested this tool with went from about 10k in .PNG format to about 37k in .JAVA format, and then to about 67k in .CLASS format. The reason for this unfortunate increase in size is that fact that a byte must be represented as an int in the code. When you throw in the comma between each element of the array and the negative sign for negative integers, a single byte in the image could translate into as many as 5 bytes of code. So weight the pro's and con's of using this tool in your application.


As always, they go to sgware@gmail.com.