trying to write function to load textures

Started by Scarecrow, November 25, 2009, 01:53:12

Previous topic - Next topic

Scarecrow

I wrote this following method to streamline texture loading, it worked with the first image I tried but not the second, which was basically the same format(.png) and image but with no alpha.  That makes sense since the method does expect a 4 component texture but so far I haven't been able to come up with a solution that loads images with and without alpha.

public static int loadTexture(String textureName) throws IOException{
        if (loadedTextures.containsKey(textureName)) {
            return loadedTextures.get(textureName);
        }

        BufferedImage image = ImageIO.read(new File(textureName));

        int width = image.getWidth();
        int height = image.getHeight();
        DataBufferByte rawData =  (DataBufferByte) image.getData().getDataBuffer();

        ByteBuffer data = BufferUtils.createByteBuffer(rawData.getSize());
        data.put(rawData.getData());
        data.rewind();
        IntBuffer scratch = BufferUtils.createIntBuffer(1);

        GL11.glGenTextures(scratch);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, scratch.get(0));
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
        GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, 4, width, height, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, data);

        loadedTextures.put(textureName, scratch.get(0));
        textureDims.put(scratch.get(0), new Vector2f(image.getWidth(), image.getHeight()));

        return scratch.get(0);
    }


Edit: the GL11.glTexImage2D call wasn't supposed to be wrapped in the an if statement.

Evil-Devil

AFAIK it is possible to determine the png bitdepth and use GL_RGB instead of GL_RGBA when there is no alpha channel. That should do most of the magic :)