Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting rid of the alpha channel on a buffered image

Tags:

java

I came across this code while watching a java game development series online.

Video Link

package gfx;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class SpriteSheet {

    public String path;
    public int width;
    public int height;
    public int[] pixels;

    public SpriteSheet(String path){
        BufferedImage image=null;

        try {
            image = ImageIO.read(SpriteSheet.class.getResourceAsStream(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(image==null){
            return;
        }
        this.path=path;
        this.width=image.getWidth();
        this.height=image.getHeight();

        pixels=image.getRGB(0, 0,width,height,null,0,width);

        for(int i=0;i<pixels.length;i++){
            pixels[i] = (pixels[i] & 0xff)/64;
        }
    }
}

I am still fairly new to java so please forgive me if it is obvious. It is explained in the video that

pixels[i] = (pixels[i] & 0xff) 

gets rid of the alpha channel in the 0xAARRGGBB notation of the pixel to make it 0xRRGGBB. From what I understand, what the & 0xff does is capture the last byte of information off of an integer. It is also explained that the number 64 in

pixels[i] = (pixels[i] & 0xff)/64;

is produced by dividing 255 by 4(I believe it was about limiting the amount of colors).

so essentially my question is: how does 0xff get rid of the alpha channel?

I am fairly certain that my confusion is my lack of experience with numbers in hexadecimal form.

like image 528
MineTurtle Avatar asked Nov 09 '22 07:11

MineTurtle


1 Answers

Your understanding is correct and the explanation in the video about removing the alpha channel is wrong.

This does not mean that everything is displayed as blue, because this image will not displayed as it is now, he only needs the numbers 0, 1, 2, 3 at the moment (I didn't watch the end of the video, so I don't know how he is going to make colors from 0, 1, 2, 3, but it must be a different step).

However, if these colors were displayed, they would be extremely dark blue colors, practically black. 0 is pure black and the others are colors indistinguishable from black.

For positive numbers (we know that (pixels[i] & 0xff) are positive) dividing by 64 is the same as shifting 6 bits to the right. See https://en.wikipedia.org/wiki/Arithmetic_shift

Anyway, the code would be much clearer if it used the shift operator:

pixels[i] = (pixels[i] & 0xff) >>> 6;
like image 84
lbalazscs Avatar answered Nov 29 '22 21:11

lbalazscs