Jump to content

Bitmap/Read a PPM file: Difference between revisions

→‎{{header|D}}: add reading
(Added Haskell.)
(→‎{{header|D}}: add reading)
Line 157:
return 0;
}</lang>
 
=={{header|D}}==
 
This example uses storage defined on [[Basic bitmap storage]] problem page.
 
This is wrap-around defined storage, P6 binary mode.
 
{{Works with|tango}}
 
<lang D>
import tango.core.Exception;
import tango.io.FileConduit;
import tango.io.MappedBuffer;
import tango.io.stream.LineStream;
import tango.io.stream.DataStream;
import tango.io.protocol.Reader;
import tango.text.convert.Integer;
 
class P6Image {
class BadInputException : Exception { this() { super("Bad file format"); } }
class NoImageException : Exception { this() { super("No image data"); } }
static const char[] type = "P6";
MappedBuffer fileBuf;
ubyte _maxVal, gotImg;
 
public:
RgbBitmap bitmap;
 
this (FileConduit input) {
fileBuf = new MappedBuffer(input);
if (processHeader(new LineInput(fileBuf)))
throw new BadInputException;
 
if (processData(new DataInput(fileBuf)))
throw new BadInputException;
}
 
ubyte maxVal() { return _maxVal; }
 
int processHeader(LineInput li) {
char[] line;
uint eaten;
 
li.readln(line);
if (line != type) return 1;
 
li.readln(line);
// skip comment lines
while (line.length && line[0] == '#') li.readln(line);
auto width = parse(line, 0, &eaten);
auto height = parse(line[eaten..$], 0, &eaten);
if (!eaten || width > 0xffff_ffff || height > 0xffff_ffff) return 1;
 
li.readln(line);
auto temp = parse(line, 0, &eaten);
if (!eaten || temp > 255) return 1;
_maxVal = temp;
 
bitmap = RgbBitmap(width, height);
 
gotImg = 1;
return 0;
}
 
int processData(DataInput di) {
if (! gotImg) throw new NoImageException;
foreach (ref cell; bitmap) {
cell(di.getByte, di.getByte, di.getByte);
}
return 0;
}
}
</lang>
 
Reading from file:
<lang>
auto p6 = new P6Image(new FileConduit("image.ppm"));
</lang>
 
=={{header|Forth}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.