Ken
Ken

Reputation: 550

Java - subtract a scalar from the RGB values of an image

Using Java EDIT: and a good Image Library BESIDES ImageMagick/JMagick:

I want to subtract a scalar (say 100) from the RGB values of ALL pixels, (bottoming out at zero). This is effectively darkening the image.

For example, for a given pixel with R: 20 G: 103 B: 200, after this subtraction that pixel should be R: 0 G: 3 B: 100 (again I want to quickly and efficiently perform this on ALL pixels, not just one)

I have already tried using ImageMagick and gotten imprecise results - it's vital that the subtraction is accurate and there are no rounding errors and the such. Any other libraries that would be good at this? Are there other options that don't deal with iterating over arrays of RGB values?

Upvotes: 0

Views: 1509

Answers (2)

Musfiqur rahman
Musfiqur rahman

Reputation: 739

Try this: If R or G or B is negative, then you can make it 0.

//At first get the RGB value
int RGB=getRGB(x,y);
int R=RGB>>>16-100; //shift by 16 bit to get the R value
if(R<0) R=0;
int G=(RGB<<<8)>>>16-100;//clear the preceding numbers than shift 16 bit
if(G<0) G=0;
int B=(RGB<<<16)>>>16-100;
if(B<0)B=0;
int newRGB=R<<<16+G<<<8+B;
setRGB(x,y,newRGB);

Upvotes: 2

Colin D
Colin D

Reputation: 5661

The BufferedImage class has both a getRGB() and setRGB() method that can act on individual pixels or arrays of pixels.

http://docs.oracle.com/javase/6/docs/api/java/awt/image/BufferedImage.html

Upvotes: 2

Related Questions