How can I overlay images over one another in Java?

Posted by Sam on Stack Overflow See other posts from Stack Overflow or by Sam
Published on 2009-03-13T22:59:41Z Indexed on 2010/04/12 0:03 UTC
Read the original article Hit count: 289

Filed under:
|
|
|

So I have been posting all over and have yet to get a solid answer:

I have created an image resizing class, with a crop method. The cropping works great. The issue that I am having is the background color that I specify in the drawImage function of Graphics is not working correctly. It defaults to black as the background regardless of what I supply (in this case Color.WHITE).

Also, the overlaying image or top most image (comes from a file) is being inverted (I think it is) or otherwise discolored. Just so you can conceptualize this a little bit better, I am taking a jpeg and overlaying it on top of a new BufferedImage, the new buffered image's background is not being set. Here is the code below that I am working with:

public void Crop(int Height, int Width, int SourceX, int SourceY) throws Exception {
    //output height and width
    int OutputWidth = this.OutputImage.getWidth();
    int OutputHeight = this.OutputImage.getHeight();

    //create output streams
    ByteArrayOutputStream MyByteArrayOutputStream = new ByteArrayOutputStream();
    MemoryCacheImageOutputStream MyMemoryCacheImageOutputStream = new MemoryCacheImageOutputStream(MyByteArrayOutputStream);

    //Create a new  BufferedImage
    BufferedImage NewImage = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_RGB);
    Graphics MyGraphics = NewImage.createGraphics();

    MyGraphics.drawImage(this.OutputImage, -SourceX, -SourceY, OutputWidth, OutputHeight, Color.WHITE, null);

    // Get Writer and set compression
    Iterator MyIterator = ImageIO.getImageWritersByFormatName("png");
    if (MyIterator.hasNext()) {
        //get image writer
        ImageWriter MyImageWriter = (ImageWriter)MyIterator.next();

        //get params
        ImageWriteParam MyImageWriteParam = MyImageWriter.getDefaultWriteParam();

        //set outputstream
        MyImageWriter.setOutput(MyMemoryCacheImageOutputStream);

        //create new ioimage
        IIOImage MyIIOImage = new IIOImage(NewImage, null, null);

        //write new image
        MyImageWriter.write(null, MyIIOImage, MyImageWriteParam);
    }

    //convert output stream back to inputstream
    ByteArrayInputStream MyByteArrayInputStream = new ByteArrayInputStream(MyByteArrayOutputStream.toByteArray());
    MemoryCacheImageInputStream MyMemoryCacheImageInputStream = new MemoryCacheImageInputStream(MyByteArrayInputStream);

    //resassign as a buffered image
    this.OutputImage = ImageIO.read(MyMemoryCacheImageInputStream);
}

© Stack Overflow or respective owner

Related posts about java

Related posts about awt