Search code examples
javaimagegraphicspnggraphics2d

How can I extend the width size in a PNG file?


I am currently working with PNG images and I'm little bit blocked because a task that not sure how to fix...

This is the scenario. I have a PNG file of 655x265 pixels with a barcode inside of it. What I need to do is 'extend' the width of the image just to include a blank zone on the left of the image, just like this:

Resize and extends canvas in png file Java

The problem is that nothing happens with the image dimensions when I execute my code:

public static void main(String[] args)
{
    try
    {
        String path = "C:\\Users\\xxx\\Desktop\\a.png";
        BufferedImage image = ImageIO.read(new File(path));
        resizeImage(path, image.getWidth() + 100, image.getHeight());
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.BLACK);
        graphics.setFont(new Font("Verdana", Font.PLAIN, 40));
        graphics.drawString("TTT", 5, 250);
        graphics.dispose();
        ImageIO.write(image, "png", new File(path));
        System.out.println("Image created");
    } catch (Exception e)
    {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
    System.out.println("Fin");
}

public static void resizeImage(String path, int newHeight, int newWidth) throws IOException
{
    File inputFile = new File(path);
    BufferedImage inputImage = ImageIO.read(inputFile);

    BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType());

    Graphics2D graphics = outputImage.createGraphics();
    graphics.drawImage(inputImage, 0, 0, newWidth, newHeight, null);
    graphics.dispose();

    ImageIO.write(outputImage, "png", new File(path));
    inputImage.flush();
    outputImage.flush();
}

Do you know what I am doing wrong? Is one of my first times working with image files and probably I misunderstood something important...

Edit: Solution provides in the comments. Link


Solution

  • What you could do is let the method take a BufferedImage, resize it and return it:

    public static BufferedImage resizeImage(BufferedImage inputImage, int newHeight, int newWidth){
        BufferedImage outputImage = new BufferedImage(newWidth, newHeight, inputImage.getType());
        Graphics2D graphics = outputImage.createGraphics();
        graphics.drawImage(inputImage, 0, 0, newWidth, newHeight, null);
        graphics.dispose(); 
        outputImage.flush();
        return outputImage;
    }
    

    Then continue working on the resized image in your surrounding method:

        String path = "C:\\Users\\xxx\\Desktop\\a.png";
        BufferedImage image = ImageIO.read(new File(path));
        image = resizeImage(image, image.getWidth() + 100, image.getHeight());  // here you replace the image with the new, resized image from your method
        Graphics graphics = image.getGraphics();
        graphics.setColor(Color.BLACK);
        ....