我正在尝试编写一个程序来读取 pbm、pgm 或 ppm 文件,并使用image
运算符将图像渲染到 postscript 输出设备。只是测试P4
输入(二进制可移植(1 位)位图)路径,但我的输出很糟糕。
%!
% cf. http://en.wikipedia.org/wiki/Netpbm_format
% cf. http://en.wikipedia.org/wiki/Computer_Graphics (origin of image)
% $ wget http://upload.wikimedia.org/wikipedia/commons/thumb/2/23/Spacewar%21-PDP-1-20070512.jpg/320px-Spacewar%21-PDP-1-20070512.jpg
% $ convert 320px-Spacewar%21-PDP-1-20070512.jpg spacewar.pbm
% $ convert 320px-Spacewar%21-PDP-1-20070512.jpg spacewar.pgm
% $ convert 320px-Spacewar%21-PDP-1-20070512.jpg spacewar.ppm
/filename (spacewar.pbm) def
%/filename (spacewar.pgm) def
%/filename (spacewar.ppm) def
/infile filename (r) file def
/readscale false def
% Read magic number
infile token pop <<
/P1 { /depth 1 def
/readscale false def
/filetype /ascii def }
/P2 { /depth 8 def
/readscale true def
/filetype /ascii def }
/P3 { /depth 24 def
/readscale true def
/filetype /ascii def }
/P4 { /depth 1 def
/readscale false def
/filetype /binary def }
/P5 { /depth 8 def
/readscale true def
/filetype /binary def }
/P6 { /depth 24 def
/readscale true def
/filetype /binary def }
>> exch 2 copy known not{pop/default}if get exec
% Read header
/buf 256 string def
infile buf readline pop % line
(1:)print dup ==
(#) { % line (#)
(2a:)print 1 index =
search { % post (#) pre
pop pop pop %
infile buf readline pop % (#) next-line
(#) % next-line (#)
(2b pstack\n)print pstack()=
}{ % line
(2c:)print dup ==
exit
} ifelse
} loop % line
pstack()=
token pop /height exch def
token pop /width exch def
readscale {
token pop /scale exch def
}{
pop
}ifelse
/buf width
depth mul
8 div ceiling cvi
string def
(bufsize: )print buf length =
/pad
buf length 8 mul
width sub def
(pad: )print pad =
/readdata <<
/ascii { % file buf
0 1 width 1 sub { % file buf i
2 index token pop % file buf i
} for
}
/binary { % file buf
readstring pop
%dup length 0 ne { 0 1 index length pad sub getinterval } if
dup == flush
%(bin)= flush
}
>> filetype get def
%errordict/rangecheck{pstack dup length = quit}put
width
height
depth
[ 1 0 0 -1 0 height ]
{
infile buf readdata
} image
showpage
我很确定问题是我计算了一行的字节宽度和预期的填充:
/buf width
depth mul
8 div ceiling cvi
string def
(bufsize: )print buf length =
/pad
buf length 8 mul
width sub def
(pad: )print pad =
但这似乎是对的,当我走过它时。对于这个 215 位宽的位图,我得到每行 27 个字节。
编辑:删除“垫”印章有帮助。也许我需要添加额外的填充?
输出中演示了该问题:
这个答案末尾的类似但更简单的程序可以正常工作。