Bitmap/Read a PPM file: Difference between revisions

Replaced "File" by "Stream" which allows to use "readPPM" with a pipe.
m (Fixed typo.)
(Replaced "File" by "Stream" which allows to use "readPPM" with a pipe.)
Line 1,356:
<lang nim>import strutils
import bitmap
import streams
 
type FormatError = object of CatchableError
Line 1,364 ⟶ 1,365:
#---------------------------------------------------------------------------------------------------
 
iterator tokens(f: FileStream): tuple[value: string, lastInLine: bool] =
## Yield the tokens in the header.
for line in f.lines:
Line 1,383 ⟶ 1,384:
#---------------------------------------------------------------------------------------------------
 
proc header(f: FileStream): tuple[width, height: Index] =
## Read the header and returnretrun the image width and height.
var state = waitingMagic
for (token, lastInLine) in f.tokens:
Line 1,405 ⟶ 1,406:
#---------------------------------------------------------------------------------------------------
 
proc readPPM*(f: FileStream): Image =
## Read a PPM file from a stream into an image.
 
let header = f.header()
Line 1,413 ⟶ 1,414:
var
arr: array[256, int8]
read = f.readBytesreadData(addr(arr, 0), 256)
pos = 0
 
Line 1,425 ⟶ 1,426:
inc pos
 
read = f.readBytesreadData(addr(arr, 0), 256)
 
if pos != 3 * result.w * result.h:
Line 1,435 ⟶ 1,436:
## Load a PPM file into an image.
 
var file = openopenFileStream(filename, fmRead)
result = file.readPPM()
file.close()</lang>
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
when isMainModule:
let image = readPPM("output.ppm")
echo image.h, " ", image.w</lang>
 
=={{header|OCaml}}==
Anonymous user