3

画像の透明度に問題があります。それは次のとおりです。

image1 があり、その上に image2 を重ねる必要があります。image2 は透明度のある png です。透かし付きの画像を作成したいのですが、画像1の上に透明な画像2があります。

透明な image2 を開き、それを JFrame に入れてプレビューすると、透明で開きます。しかし、BufferImage オブジェクトのメソッド getRGB を使用して image2 のピクセルを取得し、setRGB を使用してそれを image1 に重ねると、image2 は透明度を失い、白い背景になります。コードは次のとおりです。

public class Test {
    public static void main(String[] args) throws IOException {
        BufferedImage image = ImageIO.read(new File("c:/images.jpg"));
        BufferedImage image2 = ImageIO.read(new File("c:/images2.png"));
        int w = image2.getWidth();
        int h = image2.getHeight();
        int[] pixels = image2.getRGB(0, 0, w, h, null, 0, w);
        image2.setRGB(0, 0, w, h, pixels ,0 ,w);
        // here goes the code to show it on JFrame
    }
}

誰かが私が間違っていることを教えてもらえますか? このコードが image2 のアルファを失っていることに気付きました。アルファを失わないようにするにはどうすればよいですか?

4

1 に答える 1

3

問題は、setPixelが、元の画像のグラフィックコンテキストを解釈せずに、ピクセルを直接受け取る画像のエンコーディングを使用することです。グラフィックスオブジェクトを使用する場合、これは発生しません。

試す:

public static void main(String[] args) throws IOException {
    BufferedImage image = ImageIO.read(new File("c:/images.jpg"));
    BufferedImage image2 = ImageIO.read(new File("c:/images2.png"));

    int w = image2.getWidth();
    int h = image2.getHeight();

    Graphics2D graphics = image.createGraphics();
    graphics.drawImage(image2, 0, 0, w, h, null);
    graphics.dispose();
    // here goes the code to show it on JFrame
}
于 2012-12-02T16:21:13.640 に答える