Domanda

I am setting alpha of rgb of buffredimage in java. This code changes alpha value but i can't retrieve the same value after saving the file. How to overcome this problem.

// ================ Code for setting alpha ===============
int alpha=140;
// alpha value to set in rgb

int b=alpha<<24;
b=b|0x00ffffff;

ialpha.setRGB(0, 0,ialpha.getRGB(0, 0)&b);
// ialpha is a bufferedimage of type TYPE_INT_ARGB

ImageIO.write(ialpha, "png", new File("C:/newimg.png"));
System.out.println("\nFile saved !");

// ================ Code for getting alpha ===============

int val=(ialpha.getRGB(0, 0)&0xff000000)>>24;
if(val<0)
val=256+val;
System.out.println("Returned alpha value:"+val);

This just returns 255 as alpha value. it does not return value i set i.e 140.

Please help me to retrieve alpha value i previously set.

È stato utile?

Soluzione

The problem is in the code for getting the alpha. In the second bit shift operation, you don't take the sign bit into consideration.

int val=(ialpha.getRGB(0, 0) & 0xff000000) >> 24;

This will give the value 0xffffff8c (given your initial alpha of 140 of 0x8c). See Bitwise and Bit Shift Operators for more detail. In particular:

The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.

You need to either do either:

int val = (ialpha.getRGB(0, 0) & 0xff000000) >>> 24; // shift zero into left

Or:

int val = ialpha.getRGB(0, 0) >> 24) & 0xff; // mask out the sign part

PS: I tend to prefer the latter, because most people (myself included) never remember what the >>> operator actually does.. ;-)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top