Dynamic compass using OpenGL
arcgissamples\display\ImageTexturizer.java
/* Copyright 2010 ESRI
* 
* All rights reserved under the copyright laws of the United States
* and applicable international laws, treaties, and conventions.
* 
* You may freely redistribute and use this sample code, with or
* without modification, provided you include the original copyright
* notice and use restrictions.
* 
* See the use restrictions.
* 
*/
package arcgissamples.display;

import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

import javax.imageio.ImageIO;

import com.sun.opengl.util.BufferUtil;

public class ImageTexturizer {
    public static Texture readTexture(String filename, boolean storeAlphaChannel) throws IOException {
      BufferedImage img = ImageIO.read(new File(filename));
        int[] packedPixels = new int[img.getWidth() * img.getHeight()];

        PixelGrabber pixelgrabber = new PixelGrabber(img, 0, 0, img.getWidth(), img.getHeight(), packedPixels, 0, img.getWidth());
        try {
            pixelgrabber.grabPixels();
        } catch (InterruptedException e) {
            throw new RuntimeException();
        }

        int bytesPerPixel = storeAlphaChannel ? 4 : 3;
        ByteBuffer unpackedPixels = BufferUtil.newByteBuffer(packedPixels.length * bytesPerPixel);
        for (int row = img.getHeight() - 1; row >= 0; row--) {
            for (int col = 0; col < img.getWidth(); col++) {
                int packedPixel = packedPixels[row * img.getWidth() + col];
                int red = (packedPixel >> 16) & 0xFF;
                int blue = (packedPixel >> 8) & 0xFF;
                int green = (packedPixel >> 0) & 0xFF;
                unpackedPixels.put((byte) (red));
                unpackedPixels.put((byte) (blue));
                unpackedPixels.put((byte) (green));
                if (storeAlphaChannel) {
                  int alpha = (red==255&&blue==255&&green==255)?(0):(255);
                    unpackedPixels.put((byte) (alpha));
                }
            }
        }
        unpackedPixels.flip();


        return new Texture(unpackedPixels, img.getWidth(), img.getHeight());
    }

    public static class Texture {
        private ByteBuffer pixels;
        private int width;
        private int height;

        public Texture(ByteBuffer pixels, int width, int height) {
            this.height = height;
            this.pixels = pixels;
            this.width = width;
        }

        public int getHeight() {
            return height;
        }

        public ByteBuffer getPixels() {
            return pixels;
        }

        public int getWidth() {
            return width;
        }
    }
}