Search code examples
javaimagepngawtalpha-transparency

Convert alpha channel in white when saving to JPEG with ImageWriter


I'm converting a png image to jpeg with the following snippet of code:

ByteArrayOutputStream image1baos = new ByteArrayOutputStream();

image1 = resizeImage(cropImage(image1, rect1), 150);

ImageWriter writer = null;
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpg");
if (iter.hasNext()) {
  writer = (ImageWriter) iter.next();
}

ImageOutputStream ios = ImageIO.createImageOutputStream(image1baos);
writer.setOutput(ios);

// set the compression quality
ImageWriteParam iwparam = new MyImageWriteParam();
iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwparam.setCompressionQuality(0.2f);

// write image 1
writer.write(null, new IIOImage(image1, null, null), iwparam);

ios.flush();

// set image 1
c.getItem1().setImageData(image1baos.toByteArray());

I'd like to convert the alpha channel to white, not black as it does by default, but I couldn't find a way to do that. Will appreciate any help!


Solution

  • My solution is ugly and probably slow, but it's a solution :)

        BufferedImage img = <your image>
        for( int i = 0; i < img.getWidth( ); i++ )
            for( int j = 0; j < img.getHeight( ); j++ ) {
                // get argb from pixel
                int coli = img.getRGB( i, j );
                int a = coli >> 24 & 0xFF;
                int r = coli >> 16 & 0xFF;
                int g = coli >> 8 & 0xFF;
                int b = coli & 0xFF;
                coli &= ~0xFFFFFFFF;
                // do what you want with a, r, g and b, in your case :
                a = 0xFF;
                // save argb
                coli |= a << 24;
                coli |= r << 16;
                coli |= g << 8;
                coli |= b << 0;
                img.setRGB( i, j, coli );
            }
        }
    

    Of course, you can reduce the code by 60% if you just need to adjust the alpha channel. I kept all RGB stuff for further referece.