0

I have in the past downloaded a tool that will take an image file as input and output a source file extending the Image class that can be used for graphics. I now have a practical application for this tool, but I no longer have a copy. I have searched many times in hope of finding it again without luck.

I would like to know how to hard code an image inside a class (no external image loading). I would actually use a char[] to store all the bytes, but arrays have have a length size limit that images often exceed.

Thanks in advance.

nimsson
  • 930
  • 1
  • 14
  • 27
  • Are you sure you really need to store the image inside a class? Loading the image from a resource stored in a JAR file seems the most natural method to me. It doesn't store the image in the class but if you build your app to a JAR or WAR file, no external files are needed. The upside is that the image can be stored as-is in your sources dir, so you can e.g. edit it with a regular image editor, which you can't if it's encoded inside a class. – Michał Kosmulski Jul 21 '14 at 18:15

2 Answers2

0

You could base64 encode the data.

Apache commons codec provides a base64 encoder and decoder. Then you could use an online tool to encode your image into base64. Just write a literal string in your java file that contains the text output by the encoder.

To access the image, first decode the Base64 string into a byte array.

Then you can create your image: ImageIO.read(new ByteArrayInputStream(base64bytes))

Your length size limit is also essentially irrelevant because the size limit of a java array is the integer type, which goes up above 2 billion, or 2 gigabytes.

Strikeskids
  • 3,932
  • 13
  • 27
0

A possible way would be just storing the image bytes as a String inside a class. This way is used, for example, by LWJGL in LWJGLUtil class. They convert the string to a ByteBuffer using the following function:

private static ByteBuffer loadIcon(String data) {
    int len = data.length();
    ByteBuffer bb = BufferUtils.createByteBuffer(len);
    for(int i=0 ; i<len ; i++) {
        bb.put(i, (byte)data.charAt(i));
    }
    return bb.asReadOnlyBuffer();
}

Where BufferUtils.createByteBuffer is declared as

public static ByteBuffer createByteBuffer(int size) {
    return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());
}
izstas
  • 5,004
  • 3
  • 42
  • 56