简体   繁体   中英

How do I stop java from setting my BufferedImage to fully transparent?

I am trying to create an image editor in java, but when I run the code, the output image is fully transparent.

Here is my code for Main.java:

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

import javax.imageio.ImageIO;

public class Main {

    public static void main(String[] args) {

        BufferedImage image = null;
        try {
            image = ImageIO.read(new File("strawberry.png"));
        } catch (IOException e) {
            System.out.println(e);
        }

        new Negative(image);

        File outputfile = new File("saved.png");

        try {
            ImageIO.write(image, "png", outputfile);
        } catch (IOException e) {
            System.out.println(e);
        }

    }

}

And here is my code for Negative.java:

import java.awt.image.BufferedImage;

public class Negative {

    public Negative(BufferedImage img) {

          for (int x = 0; x < img.getWidth(); ++x) {
                for (int y = 0; y < img.getHeight(); ++y) {

                    int rgb = img.getRGB(x, y);
                    int r = (rgb >> 16) & 0xFF;
                    int g = (rgb >> 8) & 0xFF;
                    int b = (rgb & 0xFF);

                    r = 255 - r;
                    g = 255 - g;
                    b = 255 - b;

                    int newColour = (r << 16) + (g << 8) + (b << 4); 
                    img.setRGB(x, y, newColour);

                }
          }

    }

}

If anyone could help I would be very grateful.

Problem

What they call RGB color is in fact ARGB, 8 bits for each. Alpha is given in the highest 8 bits, 0 for transparent to 255 for fully opaque.

This is what TYPE_INT_ARGB means in the javadoc for BufferedImage.setRGB() :

The pixel is assumed to be in the default RGB color model, TYPE_INT_ARGB, and default sRGB color space.

Solution

For a fully opaque image, add a 255 alpha value:

int newColour = (0xff << 24) + (r << 16) + (g << 8) + (b << 4); 

Alternatively, you can take the original alpha of your image if you extract it too:

int rgb = img.getRGB(x, y);
int alpha = (rgb >>> 24);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb & 0xFF);

int newColour = (alpha << 24) + (r << 16) + (g << 8) + (b << 4);

There is one more component of a color: alpha channel. It is stored in 24-31 bits of a number. If it is set to 0, the image is transparent. So you need to set 24-31 bits of newColor to 1 to make it opaque.

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