S_a_k_Uの日記みたいなDB

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

透過したShapeを画像イメージに変換する

「Shapeを透過した画像イメージに変換する」の方が正しいのか???
Shapeを画像イメージに変換するを改造してみた。
気の向くままに・・・: 透過PNG - 8bitPNGでを参考にして、下記のようなコードとしてみた。

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import java.awt.image.IndexColorModel;
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);

        // 透過するBufferedImageを生成
        byte a[] = { (byte)0 , (byte)255, (byte)255, (byte)255 , (byte)255, (byte)255 };
        byte r[] = { (byte)0 , (byte)0, (byte)255, (byte)0 , (byte)0, (byte)255 };
        byte g[] = { (byte)0 , (byte)0, (byte)0 , (byte)255 , (byte)0, (byte)255 };
        byte b[] = { (byte)0 , (byte)0, (byte)0 , (byte)0 , (byte)255, (byte)255 };
        IndexColorModel icm = new IndexColorModel(8 , a.length , r , g , b , a);
        BufferedImage im = new BufferedImage(iw, ih, BufferedImage.TYPE_BYTE_INDEXED, icm);
        
        // 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();
        }
        
    }
	
}