User:Andrew Nikitin/pnm

From J Wiki
Jump to navigation Jump to search

Netpbm

PBM is for bitmaps (black and white, no grays) PGM is for grayscale PPM is for "pixmaps" which represent full RGB color

header

P1 Portable bitmap ASCII

P1
# This is an example bitmap of the letter "J"
6 10
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
1 0 0 0 1 0
0 1 1 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0

P2 Portable graymap ASCII

P2
# Shows the word "FEEP" (example from Netpbm main page on PGM)
24 7
15
0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
0  3  3  3  3  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15 15 15 15  0
0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0 15  0
0  3  3  3  0  0  0  7  7  7  0  0  0 11 11 11  0  0  0 15 15 15 15  0
0  3  0  0  0  0  0  7  0  0  0  0  0 11  0  0  0  0  0 15  0  0  0  0
0  3  0  0  0  0  0  7  7  7  7  0  0 11 11 11 11  0  0 15  0  0  0  0
0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0

P3 Portable pixmap ASCII

P3
# The P3 means colors are in ASCII, then 3 columns and 2 rows,
# then 255 for max color, then RGB triplets
3 2
255
255   0   0     0 255   0     0   0 255
255 255   0   255 255 255     0   0   0

P4 Portable bitmap Binary P5 Portable graymap Binary P6 Portable pixmap Binary [{{#file: "pnm.ijs"}} Download script: pnm.ijs ]

readpnm=:3 : 0
  d=.1!:1 boxopen y
  skip=.0

  type=.'' NB. pnm subtype
  s=.i.0 NB. size
  max=.0 NB. max component
  while. 1 do.
    l=.LF i.~ skip }. (skip+256){. d
    txt=.skip}.(skip+l){.d
    skip=.skip+1+#txt
    if. (-.'#'={.txt) *. -. ''-:txt do.
      if. ''-:type do.
        type=.txt
      elseif. 0=#s do.
        s=.|. _". txt
        assert. 2=#s
        assert. _>>./s
        if. ('P1'-:type) +. ('P4'-:type) do. break. end.
      elseif. 0=max do.
        max=._ ". txt
        assert. max>0 NB. positive
        assert. max<_ NB. valid
        assert. 0=#$max NB. scalar
        break.
      elseif. 1 do.
        'impossible' assert. 0
      end.
    end.
  end.
  d=.skip}.d
  if. type-:'P4' do.
    'hei wid'=.s
    wid{."1 (hei,(+8|-)wid)$,(8#2)&#: a. i. d
  elseif. type-:'P5' do.

    if. 255-:max do.
      s$ a.i.d
    else.
      s$ <.@*&(255%max)) a.i.d
    end.
    NB. multiply by 16b010101 to get rgb
  elseif. type-:'P6' do.
    if. 255-:max do.
      s$_3 (256&#.)\,a.i.d
    else.
      s$_3 (256 #. <.@*&(255%max))\,a.i.d
    end.
  elseif. type-:'P1' do.
    s$(+. # [)/ '10' =/ d
  elseif. 1 do.
    'Unsupported pnm subformat' assert. 0
  end.
)

writepbm=:writepbm4

writepbm4=:4 : 0
  y=.boxopen y
  y 1!:2~ 'P4',LF,(":|.$x),LF, _8 (a.{~#.)\ , ({.~ (] + 0 >. 0 8| -)@$) x
)

writepbm1=:4 : 0
  y=.boxopen y
  y 1!:2~ 'P1',LF,(":|.$x),LF
  _70 ([: (1!:3&y) ,&LF)\ ,x{'01'
)

writeppm6=:4 : 0
  y=.boxopen y
  y 1!:2~ 'P6',LF,(":|.$x),LF,'255',LF
  y 1!:3~ a.{~,256 256 256 #: x
)