投稿テストも兼ねて。
宗教上の理由でPGraphics.saveを使えない方におすすめ。
bmp.pde
import java.io.*;
void bmpSave(PGraphics g,String fileName){
g.updatePixels();
int bw = g.width * 3 + g.width % 4;
//== ceil(g.width*3/4)*4
int fileSize = 54 + bw * g.height;
try {
OutputStream os = new FileOutputStream(fileName);
os.write(new byte[]{'B', 'M'}); //ファイルタイプ
os.write(intToBytes(fileSize,4)); //ファイルサイズ
os.write(new byte[]{
0, 0, //予約領域1
0, 0, //予約領域2
54, 0, 0, 0, //画像データまでのオフセット
40, 0, 0, 0}); //情報ヘッダのサイズ
os.write(intToBytes(g.width,4)); //幅
os.write(intToBytes(g.height,4)); //高さ
os.write(new byte[]{
1, 0, //プレーン数
24, 0, //色のビット数
0, 0, 0, 0}); //圧縮形式
os.write(intToBytes(g.height*g.width*3,4)); //画像データのサイズ
os.write(new byte[]{
0, 0, 0, 0, //水平解像度
0, 0, 0, 0, //垂直解像度
0, 0, 0, 0, //パレットの色数
0, 0, 0, 0}); //重要なパレットのインデックス
for (int y = g.height - 1; y >= 0; y--) { //画像データの左下から読む
for (int x = 0; x < g.width; x++) {
os.write(intToBytes(g.pixels[x+y*g.width],3));
}
for (int x = 0; x < g.width % 4;x++){ //0埋め
os.write(0);
}
}
os.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
byte[] intToBytes(int number,int h) {
byte[] returnByte = new byte[h];
for(int i = 0; i < h; i++){
returnByte[i] = byte(number >> (i*8)); //リトルエンディアン
}
return returnByte;
}
void setup() {
size(299, 299);
PGraphics pg = createGraphics(width, height);
pg.beginDraw();
pg.background(255);
int count = 0;
for(int r = 0 ; r < 256; r+=127)
for(int g = 0 ; g < 256; g+=127)
for(int b = 0 ; b < 256; b+=127){
pg.fill(r,g,b);
pg.rect(count/6*50,count%6*50,50,50);
count++;
}
pg.endDraw();
image(pg, 0, 0);
bmpSave(pg,savePath("output.bmp"));
}