PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 6, 2022

[FIXED] How to place two images in one canvas through java (not jframe)

 May 06, 2022     image, java     No comments   

Issue

I just want to place two different images on one canvas and make it a .jpg file in Java. I just want to make a resulting file, not a GUI.

![enter image description here](https://i.stack.imgur.com/3pd1G.jpg)

I want to make a result file like below with both images above:


Solution

You can use BufferedImage to combine the two images. The following code shows a simple implementation:

public static void combineImages(String imagePath1, String imagePath2, String outputPath) throws IOException {
    int intervalWidth = 20; // The interval between two images
    BufferedImage image1 = ImageIO.read(new File(imagePath1));
    BufferedImage image2 = ImageIO.read(new File(imagePath2));
    int combinedWidth = image1.getWidth() + image2.getWidth() + intervalWidth;
    int combinedHeight = Math.max(image1.getHeight(), image2.getHeight());
    BufferedImage combined = new BufferedImage(combinedWidth, combinedHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = combined.createGraphics();
    g.setColor(Color.WHITE);
    // Fill the background with white
    g.fillRect(0, 0, combinedWidth, combinedHeight);
    // Draw the two images on the combined image
    g.drawImage(image1, 0, 0, null);
    g.drawImage(image2, image1.getWidth() + intervalWidth, 0, null);
    ImageIO.write(combined, "jpg", new File(outputPath));
}


Answered By - ZRnQ
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing