简体   繁体   中英

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?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM