Search code examples
javatransparencybufferedimageimage-resizing

How to remove black background after resizing BufferedImages java


I wrote a method to resize BufferedImages for me but after doing so .png images end up losing their transparency and instead they get a black background.

public BufferedImage getSizedImg(BufferedImage otherImage,int width,int height){
    BufferedImage outputImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    Graphics g = outputImg.createGraphics();
    g.drawImage(otherImage, 0, 0, width, height, null);
    g.dispose();
    return outputImg;
}

How can I fix the method so that the images keep their transparency?


Solution

  • Simple. When you create your new re-sized BufferedImage here:

    BufferedImage outputImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    

    don't use BufferedImage.TYPE_INT_RGB but rather BufferedImage.TYPE_INT_ARGB. The "A" stands for "alpha" and this gives you the transparency. For more on this, please see the BufferedImage API.