S_a_k_Uの日記みたいなDB

~サクゥーと呼ばないで~

Shapeを画像イメージに変換する

Shapeを画像ファイルにしたいのです。

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

public class ShapeTest {

    public static void main(String[] args) {

        // Shapeを生成
        float x = 0.0f;
        float y = 0.0f;
        float w = 100.0f;
        float h = 100.0f;
        GeneralPath s = new GeneralPath();
        s.append(new Line2D.Float(x, y, x, y + h), true);
        s.append(new Line2D.Float(x, y + h, x + w, y + h), true);
        s.append(new Line2D.Float(x + w, y + h, x + w, y), true);
        s.append(new Line2D.Float(x + w, y, x, y), true);
        s.append(new Line2D.Float(x, y, x + w, y + h), true);
        s.moveTo(x + w, y);
        s.append(new Line2D.Float(x + w, y, x, y + h), true);

        // BufferedImageを生成
        int iw = (int) w + 1;
        int ih = (int) h + 1;
        BufferedImage im = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);

        // Graphics2Dに描画
        Graphics2D g2 = im.createGraphics();
        if ((x != 0) || (y != 0)) {
            // 座標がずれている場合は原点(0, 0)へ移動
            g2.setTransform(AffineTransform.getTranslateInstance(-x, -y));
        }
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, iw, ih);
        g2.setPaint(Color.RED);
        g2.draw(s);

        // ImageWriterを使ってOutputStreamに出力
        ImageWriter imgwriter = (ImageWriter) ImageIO.getImageWritersByFormatName("png").next();
        try {
        	OutputStream os = new BufferedOutputStream(new FileOutputStream("c:/temp/test.png"));
        	ImageOutputStream ios = ImageIO.createImageOutputStream(os);
        	imgwriter.setOutput(ios);
        	imgwriter.write(im);
        	ios.close();
        	os.flush();
        	os.close();
        } catch (Exception e) {
        	e.printStackTrace();
        }
        
    }
	
}

できあがった画像ファイルはこんなの。