web-dev-qa-db-ja.com

2つのBufferedImagesを1つの画像に並べてコピーします

2つの画像があり、これら2つの画像を新しい画像にコピーして、2番目の画像が最初の画像の上ではなく横にあるようにします。

BufferedImage imgb1 = img1;
BufferedImage imgb2 = img2;
BufferedImage imgResult = new BufferedImage(...);

ここで、imgResultには、1番目と2番目の画像が隣り合って含まれています。

12
oooss

私はあなたのためにデモとユニットテストを作成しました、それがうまくいくことを願っています!

コード:

import Java.awt.Color;
import Java.awt.Graphics2D;
import Java.awt.image.BufferedImage;
import Java.io.File;
import Java.io.IOException;
import javax.imageio.ImageIO;
/**
 * This code try to join two BufferedImage
 * @author wangdq
 * 2013-12-29
 */
public class JoinImage {
    public static void main(String args[])
    {   
        String filename = System.getProperty("user.home")+File.separator;
        try {
            BufferedImage img1 = ImageIO.read(new File(filename+"1.png"));
            BufferedImage img2=ImageIO.read(new File(filename+"2.png"));
            BufferedImage joinedImg = joinBufferedImage(img1,img2);
            boolean success = ImageIO.write(joinedImg, "png", new File(filename+"joined.png"));
            System.out.println("saved success? "+success);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * join two BufferedImage
     * you can add a orientation parameter to control direction
     * you can use a array to join more BufferedImage
     */

    public static BufferedImage joinBufferedImage(BufferedImage img1,BufferedImage img2) {

        //do some calculate first
        int offset  = 5;
        int wid = img1.getWidth()+img2.getWidth()+offset;
        int height = Math.max(img1.getHeight(),img2.getHeight())+offset;
        //create a new buffer and draw two image into the new image
        BufferedImage newImage = new BufferedImage(wid,height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = newImage.createGraphics();
        Color oldColor = g2.getColor();
        //fill background
        g2.setPaint(Color.WHITE);
        g2.fillRect(0, 0, wid, height);
        //draw image
        g2.setColor(oldColor);
        g2.drawImage(img1, null, 0, 0);
        g2.drawImage(img2, null, img1.getWidth()+offset, 0);
        g2.dispose();
        return newImage;
    }
}
23
wangdq
public static BufferedImage joinBufferedImage(BufferedImage img1,
      BufferedImage img2) {
    //int offset = 2;
    int width = img1.getWidth();
    int height = img1.getHeight() + img2.getHeight();
    BufferedImage newImage = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = newImage.createGraphics();
    Color oldColor = g2.getColor();
    g2.setPaint(Color.WHITE);
    g2.fillRect(0, 0, width, height);
    g2.setColor(oldColor);
    g2.drawImage(img1, null, 0, 0);
    g2.drawImage(img2, null, 0, img1.getHeight());
    g2.dispose();
    return newImage;
  }

1つの画像を互いに重ねて印刷するようにコードを変更しました(次々に)

0
topcat3