Convert an Image to a Byte Array for Inclusion in Source Code

I think I saw someone post something similar before? Nevertheless, here we go again…

I am somewhat anal about storing icons (or small images) in source code rather than on the file system. It’s very easy to mess up image loading, so here is my code to store an image in a .java source file rather than on the file system, where it can easily get lost. Please note the image size roughly doubles, so the procedure isn’t feasible for larger images.

Also, obviously I am not doing this for every icon, but only for the ones that are very unlikely to change (e.g. play, stop, pause button icons etc.).

Example Conversion: Image:

/ Java Source Code: Byte Array
Resource/Download: ImageUtil.java

Convert a byte array to Java code:

    // Load image
    Image image = loadImage(...);
    
    // Convert the image to a byte array
    byte[] data = ImageUtil.imageToByteArray(image);
    
    // Output data
    FileOutputStream fos = new FileOutputStream(args[1], false);
    DataOutputStream dos = new DataOutputStream(fos);
    for (int i = 0; i < data.length; i++) {
      if ((i % 8) == 0) {
        dos.writeBytes("\n");
      }
      dos.writeBytes("(byte)0x");
      String hex = Integer.toHexString(data[i]);
      if (hex.length() == 1) {
        hex = "0" + hex;
      }
      else if (hex.length() > 2) {
        hex = hex.substring(hex.length() - 2);
      }
      dos.writeBytes(hex);
      dos.writeBytes(", ");
    }
    dos.flush();
    dos.close(); 
    fos.flush();
    fos.close();

Website: http://www.noblemaster.com/public/ (see section 3)

While I’m sure someone will appreciate the contributed code, I wouldn’t recommend such a practice.