明示的に設定して試してみる

これまでgnuplotの端末設定はpngのデフォルトのままにしていたが、
画像サイズや画素のビット深度などを変えてもこのやり方が通るかどうか確かめてみた。

import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;

public class GnuplotUser5 {
    private static final String GNUPLOT = "/usr/bin/gnuplot";

    public static void main(String[] args) throws IOException, InterruptedException {
        Process p = new ProcessBuilder(GNUPLOT, "-").start();
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(p.getOutputStream())));
        BufferedInputStream in = new BufferedInputStream(p.getInputStream());

        /*
          the 1st element of each String[]: optional parameters for "set terminal png"
        */
        String[][] cmds = {
            {"", "plot sin(x)"},
            {"", "plot sin(x+pi/10)"},
            {"size 321,247 truecolor", "plot cos(x+pi/5)"},
            {"size 1000,1000 notruecolor", "set xrange [1:5*pi]", "set yrange [1:5*pi]", "set logscale xy", "splot sin(x+y)"},
        };

        for (String[] cmd : cmds) {
            out.println("set terminal png " + cmd[0]);
            for (int i = 1; i < cmd.length; i++) out.println(cmd[i]);
            out.println("set output");
            out.flush();
            BufferedImage image = ImageIO.read(in);
            System.err.println(image);
            in.skip(16);
        }

        out.close();
        in.close();
        p.waitFor();
    }
}

実行すると、

BufferedImage@a6e0a9: type = 13 IndexColorModel: #pixelBits = 8 numComponents = 
3 color space = java.awt.color.ICC_ColorSpace@1e779a1 transparency = 1 transInde
x   = -1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 640
 height = 480 #numDataElements 1 dataOff[0] = 0
BufferedImage@187f9f1: type = 13 IndexColorModel: #pixelBits = 8 numComponents =
 3 color space = java.awt.color.ICC_ColorSpace@1e779a1 transparency = 1 transInd
ex   = -1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 64
0 height = 480 #numDataElements 1 dataOff[0] = 0
BufferedImage@bdb375: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 col
or space = java.awt.color.ICC_ColorSpace@1e779a1 transparency = 1 has alpha = fa
lse isAlphaPre = false ByteInterleavedRaster: width = 321 height = 247 #numDataE
lements 3 dataOff[0] = 2
BufferedImage@78529d: type = 13 IndexColorModel: #pixelBits = 8 numComponents = 
3 color space = java.awt.color.ICC_ColorSpace@1e779a1 transparency = 1 transInde
x   = -1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 100
0 height = 1000 #numDataElements 1 dataOff[0] = 0

widthやheight、#pixelBitsなどに注目すると設定通りに出力されているようである。
この環境ではストリームに残っている16バイト分をスキップするやり方が有効といえる。
しかしこの方法は環境依存性が強く、また、今うまくやれていても実装の変更で破綻する可能性がある。
それに、連続する画像データ間に境界がないため、根本的にトラブルからの回復がかなり困難である。