Binary files
Julia can handle binary files as easily as text files using read()
and write()
.
Earlier, we created a simple grayscale image for a Julia set. Here, we will read the file and invert the image:
julia>
cd(ENV["HOME"]*"/MJ2/DataSources/Files");julia>
img = open("juliaset.pgm");julia>
magic = chomp(readline(img))
We can open the file in the normal way. The first value is the “magic” number P5 (for a PGM file), terminated by \n
, so we can get that with readline()
.
We will be creating another PGM file so that can write the magic
number.
The next line comprises three integers – that is, the width and height of the image and the maximum pixel value (usually 255).
These are read and copied without change:
julia>
if magic == "P5"
out = open("jsetinvert.pgm", "w");
println(out, magic);
params = chomp(readline(img));
# Should be =>...