Search code examples
javagroovyimage-resizingimage-scaling

Resize Image to defined Dimension and paint unused area red?


The following all happens server side. I want to scale an image like the following.

enter image description here

The image should be scaled to fit in predefined dimension. The image should scale to fit in the bounding rectangle. I know how to scale the image with Java libs like imageScalr. After scaling the image should be painted in the target dimensions rect and the places where the image does not fill the target rect should be painted red like shown in the following image:

enter image description here

How can I paint a image into a target rectangle and fill the areas where no image is with red?


Solution

  • Create a BufferedImage which is the bounding of box of the desired area

    // 100x100 is the desired bounding box of the scaled area
    // Change this for the actual area you want to use
    BufferedImage scaledArea = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
    

    Using the BufferedImage's Graphics context, fill the image with the desired color

    Graphics2D g2d = scaledArea.createGraphics();
    g2d.setColor(Color.RED);
    g2d.fillRect(0, 0, 100, 100);
    

    Draw the scaled image into this image...

    // 100x100 is the desired bounding box of the scaled area
    // Change this for the actual area you want to use
    int x = (100 - scaled.getWidth()) / 2;
    int y = (100 - scaled.getHeight()) / 2;
    g2d.drawImage(scaled, x, y, null);
    g2d.dispose();
    

    Then you could use ImageIO.write to save the result

    enter image description here

    Have a look at 2D Graphics and Writing/Saving an Image for more details