Bitmap/Write a PPM file: Difference between revisions
Content deleted Content added
Added an example; modified the way to write into file. |
Alextretyak (talk | contribs) m →{{header|11l}}: BVec3 |
||
(37 intermediate revisions by 16 users not shown) | |||
Line 1:
[[Category:Input Output]]
{{task|Raster graphics operations}}
Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster images, write the image to a PPM file (binary P6 preferred).
(Read [[wp:Netpbm_format|the definition of PPM file]] on Wikipedia.)
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">T Colour = BVec3
V black = Colour(0, 0, 0)
V white = Colour(255, 255, 255)
T Bitmap
Int width, height
Colour background
[[Colour]] map
F (width = 40, height = 40, background = white)
assert(width > 0 & height > 0)
.width = width
.height = height
.background = background
.map = (0 .< height).map(h -> (0 .< @width).map(w -> @@background))
F fillrect(x, y, width, height, colour = black)
assert(x >= 0 & y >= 0 & width > 0 & height > 0)
L(h) 0 .< height
L(w) 0 .< width
.map[y + h][x + w] = colour
F set(x, y, colour = black)
.map[y][x] = colour
F get(x, y)
R .map[y][x]
F writeppmp3()
V magic = "P3\n"
V comment = "# generated from Bitmap.writeppmp3\n"
V s = magic‘’comment‘’("#. #.\n#.\n".format(.width, .height, 255))
L(h) (.height - 1 .< -1).step(-1)
L(w) 0 .< .width
V (r, g, b) = .get(w, h)
s ‘’= ‘ #3 #3 #3’.format(r, g, b)
s ‘’= "\n"
R s
F writeppmp6()
V magic = "P6\n"
V comment = "# generated from Bitmap.writeppmp6\n"
[Byte] b
b [+]= magic.encode()
b [+]= comment.encode()
b [+]= ("#. #.\n#.\n".format(.width, .height, 255)).encode()
L(h) (.height - 1 .< -1).step(-1)
L(w) 0 .< .width
V (r, g, bl) = .get(w, h)
b [+]= [r, g, bl]
R b
V bitmap = Bitmap(4, 4, black)
bitmap.fillrect(1, 0, 1, 2, white)
bitmap.set(3, 3, Colour(127, 0, 63))
print(bitmap.writeppmp3())
File(‘tmp.ppm’, WRITE).write_bytes(bitmap.writeppmp6())</syntaxhighlight>
{{out}}
<pre>
P3
# generated from Bitmap.writeppmp3
4 4
255
0 0 0 0 0 0 0 0 0 127 0 63
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0
</pre>
=={{header|Action!}}==
{{libheader|Action! Bitmap tools}}
<syntaxhighlight lang="action!">INCLUDE "H6:RGBIMAGE.ACT" ;from task Bitmap
PROC SaveHeader(RgbImage POINTER img
CHAR ARRAY format BYTE dev)
PrintDE(dev,format)
PrintBD(dev,img.w)
PutD(dev,32)
PrintBDE(dev,img.h)
PrintBDE(dev,255)
RETURN
PROC SavePPM3(RgbImage POINTER img CHAR ARRAY path)
BYTE dev=[1],x,y
RGB c
Close(dev)
Open(dev,path,8)
SaveHeader(img,"P3",dev)
FOR y=0 TO img.h-1
DO
FOR x=0 TO img.w-1
DO
GetRgbPixel(img,x,y,c)
PrintBD(dev,c.r) PutD(dev,32)
PrintBD(dev,c.g) PutD(dev,32)
PrintBD(dev,c.b)
IF x=img.w-1 THEN
PutDE(dev)
ELSE
PutD(dev,32)
FI
OD
OD
Close(dev)
RETURN
PROC SavePPM6(RgbImage POINTER img CHAR ARRAY path)
BYTE dev=[1],x,y
RGB c
Close(dev)
Open(dev,path,8)
SaveHeader(img,"P6",dev)
FOR y=0 TO img.h-1
DO
FOR x=0 TO img.w-1
DO
GetRgbPixel(img,x,y,c)
PutD(dev,c.r)
PutD(dev,c.g)
PutD(dev,c.b)
OD
OD
Close(dev)
RETURN
PROC Load(CHAR ARRAY path)
CHAR ARRAY line(255)
BYTE dev=[1]
Close(dev)
Open(dev,path,4)
WHILE Eof(dev)=0
DO
InputSD(dev,line)
PrintE(line)
OD
Close(dev)
RETURN
PROC Main()
BYTE ARRAY rgbdata=[
0 0 0 0 0 255 0 255 0
255 0 0 0 255 255 255 0 255
255 255 0 255 255 255 31 63 127
63 31 127 127 31 63 127 63 31]
BYTE width=[3],height=[4]
RgbImage img
CHAR ARRAY path3="D:PPM3.PPM"
CHAR ARRAY path6="D:PPM6.PPM"
Put(125) PutE() ;clear the screen
InitRgbImage(img,width,height,rgbdata)
PrintF("Saving %S...%E%E",path3)
SavePPM3(img,path3)
PrintF("Saving %S...%E%E",path6)
SavePPM6(img,path6)
PrintF("Loading %S...%E%E",path3)
Load(path3)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Write_a_PPM_file.png Screenshot from Atari 8-bit computer]
<pre>
Saving D:PPM3.PPM...
Saving D:PPM6.PPM...
Loading D:PPM3.PPM...
P3
3 4
255
0 0 0 0 0 255 0 255 0
255 0 0 0 255 255 255 0 255
255 255 0 255 255 255 31 63 127
63 31 127 127 31 63 127 63 31
</pre>
=={{header|Ada}}==
<
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
with Bitmap_Store; use Bitmap_Store;
-- This package is defined in the Bitmap task.
procedure Put_PPM (File : File_Type; Picture : Image) is
Line 31 ⟶ 221:
end loop;
Character'Write (Stream (File), LF);
end Put_PPM;</
The solution writes the image into an opened file. The file format might fail to work on certain [[OS]]es, because output might mangle control characters like LF, CR, FF, HT, VT etc. The OS might also limit the line length of a text file. In general it is a bad idea to mix binary and text output in one file. This solution uses ''stream I/O'', which should be as portable as possible.
=={{header|Aime}}==
<
file f;
Line 51 ⟶ 241:
16.times(f_bytes, f, drand(255), drand(255), drand(255));
} while ((i += 16) < w);
} while ((j += 1) < h);</
=={{header|Applesoft BASIC}}==
<syntaxhighlight lang="gwbasic"> 100 W = 8
110 H = 8
120 BA = 24576
130 HIMEM: 8192
140 D$ = CHR$ (4)
150 M$ = CHR$ (13)
160 P6$ = "P6" + M$ + STR$ (W) + " " + STR$ (H) + M$ + "255" + M$
170 FOR I = 1 TO LEN (P6$)
180 POKE BA + I - 1, ASC ( MID$ (P6$,I,1))
190 NEXT I
200 BB = BA + I - 1
210 BL = (BB + W * H * 3) - BA
220 C = 255 + 255 * 256 + 0 * 65536: GOSUB 600FILL
230 X = 4:Y = 5:C = 127 + 127 * 256 + 255 * 65536: GOSUB 500"SET PIXEL"
240 PRINT D$"BSAVE BITMAP.PPM,A"BA",L"BL
250 END
500 R = C - INT (C / 256) * 256:B = INT (C / 65536):G = INT (C / 256) - B * 256:A = BB + X * 3 + Y * W * 3: POKE A,R: POKE A + 1,G: POKE A + 2,B: RETURN
600 FOR Y = 0 TO H - 1: FOR X = 0 TO W - 1: GOSUB 500: NEXT X,Y: RETURN</syntaxhighlight>
=={{header|ATS}}==
For this code you will also need <code>bitmap_task.sats</code> and <code>bitmap_task.dats</code> from [[Bitmap#ATS]].
The static file provides templates for writing a PPM in either raw or plain format, regardless of what type you use to represent a pixel. The dynamic file, however, provides implementations ''only'' for the <code>rgb24</code> type defined in <code>bitmap_task.sats</code>.
===The ATS static file===
The following interface file should be named <code>bitmap_write_ppm_task.sats</code>.
<syntaxhighlight lang="ats">
#define ATS_PACKNAME "Rosetta_Code.bitmap_write_ppm_task"
staload "bitmap_task.sats"
(* Only pixmaps with positive width and height (pixmap1) are accepted
for writing a PPM. *)
fn {a : t@ype}
pixmap_write_ppm_raw_or_plain
(outf : FILEref,
pix : !pixmap1 a,
plain : bool)
: bool (* success *)
fn {a : t@ype}
pixmap_write_ppm_raw
(outf : FILEref,
pix : !pixmap1 a)
: bool (* success *)
overload pixmap_write_ppm with pixmap_write_ppm_raw_or_plain
overload pixmap_write_ppm with pixmap_write_ppm_raw
</syntaxhighlight>
===The ATS dynamic file===
The following file of implementations should be named <code>bitmap_write_ppm_task.dats</code>.
<syntaxhighlight lang="ats">
(*------------------------------------------------------------------*)
#define ATS_DYNLOADFLAG 0
#define ATS_PACKNAME "Rosetta_Code.bitmap_write_ppm_task"
#include "share/atspre_staload.hats"
staload "bitmap_task.sats"
(* You need to staload bitmap_task.dats, so the ATS compiler will have
access to its implementations of templates. But we staload it
anonymously, so the programmer will not have access. *)
staload _ = "bitmap_task.dats"
staload "bitmap_write_ppm_task.sats"
(*------------------------------------------------------------------*)
(* Realizing that MAXVAL, and how to represent depend on the
pixel type, we implement the template functions ONLY for pixels of
type rgb24. *)
(* We will implement raw PPM using "dump", and plain PPM using the
"get a pixel" square brackets. The latter method is simpler than
writing a different implementation of pixmap$pixels_dump<rgb24>,
and also helps us satisfy the stated requirements of the task.
("Dump" goes beyond what was asked for.) *)
implement
pixmap_write_ppm_raw_or_plain<rgb24> (outf, pix, plain) =
begin
fprintln! (outf, (if plain then "P3" else "P6") : string);
fprintln! (outf, width pix, " ", height pix);
fprintln! (outf, "255");
if ~plain then
dump<rgb24> (outf, pix)
else
let
val w = width pix and h = height pix
prval [w : int] EQINT () = eqint_make_guint w
prval [h : int] EQINT () = eqint_make_guint h
fun
loop {x, y : nat | x <= w; y <= h}
.<h - y, w - x>.
(pix : !pixmap (rgb24, w, h),
x : size_t x,
y : size_t y)
: void =
if y = h then
()
else if x = w then
loop (pix, i2sz 0, succ y)
else
let
val @(r, g, b) = rgb24_values pix[x, y]
in
fprintln! (outf, r, " ", g, " ", b);
loop (pix, succ x, y)
end
in
loop (pix, i2sz 0, i2sz 0);
true
end
end
implement
pixmap_write_ppm_raw<rgb24> (outf, pix) =
pixmap_write_ppm_raw_or_plain<rgb24> (outf, pix, false)
(*------------------------------------------------------------------*)
#ifdef BITMAP_WRITE_PPM_TASK_TEST #then
implement
main0 () =
let
val bgcolor = rgb24_make (217u, 217u, 214u)
and fgcolor1 = rgb24_make (210, 0, 0)
and fgcolor2 = rgb24_make (0, 150, 0)
and fgcolor3 = rgb24_make (0, 0, 220)
stadef w = 300
stadef h = 200
val w : size_t w = i2sz 300
and h : size_t h = i2sz 200
val @(pfgc | pix) = pixmap_make<rgb24> (w, h, bgcolor)
val () =
let
var x : Size_t
in
for* {x : nat | x <= w}
.<w - x>.
(x : size_t x) =>
(x := i2sz 0; x <> w; x := succ x)
begin
pix[x, i2sz 50] := fgcolor1;
pix[x, i2sz 100] := fgcolor2;
pix[x, i2sz 150] := fgcolor3
end
end
val outf_raw = fileref_open_exn ("image-raw.ppm", file_mode_w)
and outf_plain = fileref_open_exn ("image-plain.ppm", file_mode_w)
val success = pixmap_write_ppm<rgb24> (outf_raw, pix)
val () = assertloc success
val success = pixmap_write_ppm<rgb24> (outf_plain, pix, true)
val () = assertloc success
in
fileref_close outf_raw;
fileref_close outf_plain;
free (pfgc | pix)
end
#endif
(*------------------------------------------------------------------*)
</syntaxhighlight>
There is a test program that you can compile and run thus:
<pre>$ patscc -std=gnu2x -g -O2 -DATS_MEMALLOC_LIBC -DATS BITMAP_WRITE_PPM_TASK_TEST bitmap_{,write_ppm_}task.{s,d}ats
$ ./a.out
</pre>
If everything worked, you should end up with two image files, <code>image-raw.ppm</code> and <code>image-plain.ppm</code>. The former will have been made with the "dump" functionality that outputs the raw pixel data in one call to <code>fwrite(3)</code>. The latter will have been written more in the way the task assumes: reading pixels individually, left-to-right and top-to-bottom.
The images should appear thus:
[[File:Bitmap write ppm task ATS.png|alt=A gray background with red, green, and blue horizontal stripes, one pixel thick each, evenly placed, top to bottom.]]
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L|45}}
<syntaxhighlight lang="autohotkey">
cyan := color(0,255,255) ; r,g,b
cyanppm := Bitmap(10, 10, cyan) ; width, height, background-color
Line 87 ⟶ 461:
return 0
}
</syntaxhighlight>
=={{header|AWK}}==
<
BEGIN {
split("255,0,0,255,255,0",R,",");
Line 102 ⟶ 476:
}
close(outfile);
}</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
Height% = 200
Line 135 ⟶ 508:
col% = TINT(x%*2,y%*2)
SWAP ?^col%,?(^col%+2)
= col%</
=={{header|BQN}}==
<syntaxhighlight lang="bqn">header_ppm ← "P6
4 8
255
"
red ← 255‿0‿0 # a 3-element 1D list
grn ← 0‿255‿0
ble ← 0‿0‿255
blk ← 0‿0‿0
gry ← 128‿128‿128
wht ← 255‿255‿255
all ← ∾red‿grn‿ble‿blk‿gry‿wht # join "colors" to 1D list
image_ppm ← 8‿4‿3 ⥊ all # reshape "all" to 8 rows by 4 cols by 3, "all" gets reused as needed to fill
image_ppm ↩ @ + ⥊ image_ppm # deshape, convert to chars (uint8_t)
bytes_ppm ← header_ppm ∾ image_ppm
"small.ppm" •file.Bytes bytes_ppm</syntaxhighlight>
{{trans|C}}
<syntaxhighlight lang="bqn">header_ppm ← "P6
800 800
255
"
image_ppm ← @ + ⥊ > {256|𝕨‿𝕩‿(𝕨×𝕩)}⌜˜ ↕800
"first_bqn.ppm" •file.Bytes header_ppm ∾ image_ppm</syntaxhighlight>
=={{header|C}}==
This is one file program which writes one color in each step :
<
#include <stdio.h>
Line 162 ⟶ 557:
(void) fclose(fp);
return EXIT_SUCCESS;
}</
This program writes whole array in one step :
<
int main()
Line 202 ⟶ 597:
printf("OK - file %s saved\n", filename);
return 0;
}</
Line 211 ⟶ 606:
Interface:
<
Implementation:
<
void output_ppm(FILE *fd, image img)
Line 224 ⟶ 619:
(void) fwrite(img->buf, sizeof(pixel), n, fd);
(void) fflush(fd);
}</
=={{header|C sharp|C#}}==
This implementation uses a StreamWriter to write the header in text, then writes the pixel data in binary using a BinaryWriter.
<
using System.IO;
class PPMWriter
Line 252 ⟶ 646:
writerB.Close();
}
}</
=={{header|C++}}==
{{trans|C}}
<
int main() {
constexpr auto dimx = 800u, dimy = 800u;
std::ofstream ofs("first.ppm", ios_base::out | ios_base::binary);
ofs << "P6\n" << dimx << ' ' << dimy << "\n255\n";
for (auto j = 0u; j < dimy; ++j)
for (auto i = 0u; i < dimx; ++i)
ofs <<
<< static_cast<char>(j % 256)
<< static_cast<char>((i * j) % 256);
}</syntaxhighlight>
=={{header|Common Lisp}}==
<
(with-open-file (stream filename
:element-type '(unsigned-byte 8)
Line 304 ⟶ 693:
(write-byte green stream)
(write-byte blue stream)))))))
filename)</
=={{header|D}}==
The Image module contains a savePPM6 function to save binary PPM images.
=={{header|Delphi}}==
Helper class to enable bitmap export to ppm.
<syntaxhighlight lang="delphi">
program btm2ppm;
Line 363 ⟶ 750:
end;
end.
</syntaxhighlight>
=={{header|E}}==
The code for this task is incorporated into [[Basic bitmap storage#E]].
=={{header|Erlang}}==
Writes a bitmap to PPM file. Uses 24 bit color depth (color max value 255).
<
-module(ppm).
Line 418 ⟶ 803:
integer_to_list(Number).
</syntaxhighlight>
=={{header|Euphoria}}==
{{trans|C}}
<
constant fn = open("first.ppm","wb") -- b - binary mode
sequence color
Line 436 ⟶ 820:
end for
end for
close(fn)</
Procedure writing [[Bitmap#Euphoria|bitmap]] data storage:
<
integer fn,dimx,dimy
dimy = length(image[1])
Line 452 ⟶ 836:
end for
close(fn)
end procedure</
=={{header|FBSL}}==
This code converts a Windows BMP to a PPM. Uses FBSL volatiles for brevity.
Line 459 ⟶ 842:
'''24-bpp P.O.T.-size BMP solution:'''
[[File:FBSLWritePpm.PNG|right]]
<
DIM bmpin = ".\\LenaClr.bmp", ppmout = ".\\Lena.ppm", bmpblob = 54 ' Size of BMP file headers
Line 481 ⟶ 864:
WEND
FILEPUT(FILEOPEN(ppmout, BINARY_NEW), ppmdata): FILECLOSE(FILEOPEN)</
=={{header|Forth}}==
<
s" P6" fid write-line throw
bmp bdim swap
Line 497 ⟶ 879:
s" red.ppm" w/o create-file throw
test over write-ppm
close-file throw</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
It loads <code>rgbimage_m</code> module, which is defined [[Basic bitmap storage#Fortran|here]].
<
use rgbimage_m
Line 527 ⟶ 908:
call im%write('fig.ppm')
end program</
=={{header|GAP}}==
<
# Only P3 format, an image is a list of 3 matrices (r, g, b)
# Max color is always 255
Line 580 ⟶ 960:
PutPixel(g, 2, 2, [255, 255, 255]);
PutPixel(g, 2, 3, [0, 0, 0]);
WriteImage("example.ppm", g);</
=={{header|Go}}==
Code below writes 8-bit P6 format only. See Bitmap task for additional file needed to build working raster package.
<
import (
Line 637 ⟶ 1,016:
}
return f.Close()
}</
Demonstration program. Note that it imports package raster. To build package raster, put code above in one file, put code from Bitmap task in another, and compile and link them into a Go package.
<
// Files required to build supporting package raster are found in:
Line 657 ⟶ 1,036:
fmt.Println(err)
}
}</
=={{header|Haskell}}==
<
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where
Line 709 ⟶ 1,087:
stToIO (getPixels i) >>= hPutStr h . toNetpbm
where magicNumber = netpbmMagicNumber (nil :: c)
maxval = netpbmMaxval (nil :: c)</
=={{header|J}}==
'''Solution:'''
<
NB. ($x) is height, width, colors per pixel
Line 719 ⟶ 1,096:
header=. 'P6',LF,(":1 0{$x),LF,'255',LF
(header,,x{a.) fwrite y
)</
'''Example:'''
Using routines from [[Basic_bitmap_storage#J|Basic Bitmap Storage]]:
<
pixellist=: >,{;~i.10
myimg=: ((150 + pixellist) ; 255 0 255) setPixels 0 255 0 makeRGB 600 300
myimg writeppm jpath '~temp/myimg.ppm'
540015</
=={{header|Java}}==
See [[Basic_bitmap_storage#Java|Basic Bitmap Storage]] for the <tt>BasicBitmapStorage</tt> class.
<syntaxhighlight lang="java">import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class PPMWriter {
public void bitmapToPPM(File file, BasicBitmapStorage bitmap) throws IOException {
file.delete();
try (var os = new FileOutputStream(file, true);
var bw = new BufferedOutputStream(os)) {
var header = String.format("P6\n%d %d\n255\n",
bitmap.getWidth(), bitmap.getHeight());
bw.write(header.getBytes(StandardCharsets.US_ASCII));
for (var y = 0; y < bitmap.getHeight(); y++) {
for (var x = 0; x < bitmap.getWidth(); x++) {
var pixel = bitmap.getPixel(x, y);
bw.write(pixel.getRed());
bw.write(pixel.getGreen());
bw.write(pixel.getBlue());
}
}
}
}
}</syntaxhighlight>
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
h, w = 50, 70
Line 741 ⟶ 1,150:
save("data/bitmapWrite.ppm", img)
save("data/bitmapWrite.png", img)</
=={{header|Kotlin}}==
For convenience, we repeat the code for the class used in the [[Bitmap]] task here.
<
import java.awt.Color
Line 796 ⟶ 1,204:
}
}
}</
=={{header|LiveCode}}==
LiveCode has built in support for importing and exporting PBM, JPEG, GIF, BMP or PNG graphics formats
<syntaxhighlight lang="livecode">
export image "test" to file "~/Test.PPM" as paint -- paint format is one of PBM, PGM, or PPM
</syntaxhighlight>
=={{header|Lua}}==
===Original===
<
-- helper function, simulates PHP's array_fill function
Line 908 ⟶ 1,320:
example_colorful_stripes():writeP6('p6.ppm')
</syntaxhighlight>
===Alternate===
Uses the alternate Bitmap implementation [[Bitmap#Alternate|here]], extending it with..
<
local fp = io.open(filename, "wb")
if fp == nil then return false end
Line 923 ⟶ 1,335:
fp:close()
return true
end</
Example usage:
<
bitmap:clear({255,255,255})
for y = 1, 5 do
Line 934 ⟶ 1,346:
end
end
bitmap:savePPM("lua3x5.ppm")</
=={{header|M2000 Interpreter}}==
Added ToFile in group which return the function Bitmap. In this example we export using ToFile and get bytes (unsigned values) from buffer, and we export from outside, using getpixel and convert the RGB value to bytes (color returned as a negative number, so we have to invert before further process it)
===P3 type===
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Function Bitmap (x as long, y as long) {
Line 1,052 ⟶ 1,463:
Checkit
</syntaxhighlight>
{{out}}
Line 1,073 ⟶ 1,484:
===P6 type===
<syntaxhighlight lang="m2000 interpreter">
Module PPMbinaryP6 {
If Version<9.4 then 1000
Line 1,252 ⟶ 1,663:
PPMbinaryP6
</syntaxhighlight>
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
<
=={{header|MATLAB}} / {{header|Octave}}==
<
G=[0,255,0;255,255,0];
B=[0,0,255;0,0,0];
Line 1,269 ⟶ 1,678:
fprintf(fid,'P6\n%i %i\n255\n',size(R));
fwrite(fid,[r,g,b]','uint8');
fclose(fid);</
=={{header|Modula-3}}==
<code>Bitmap</code> is the module from [[Basic_bitmap_storage#Modula-3|Basic Bitmap Storage]].
<
IMPORT Bitmap, Pathname;
Line 1,279 ⟶ 1,687:
PROCEDURE Create(imgfile: Pathname.T; img: Bitmap.T);
END PPM.</
<
IMPORT Bitmap, Wr, FileWr, Pathname;
Line 1,309 ⟶ 1,717:
BEGIN
END PPM.</
==
<syntaxhighlight lang="nim">import bitmap
import
#---------------------------------------------------------------------------------------------------
proc writePPM*(img: Image, stream: Stream) =
## Write an image to a PPM stream.
stream.writeLine("P6 ", $img.w, " ", $img.h, " 255")
for x, y in img.indices:
#---------------------------------------------------------------------------------------------------
proc writePPM*(img: Image; filename: string) =
## Write an image in a PPM file.
var file =
img.writePPM(file)
file.close()
#———————————————————————————————————————————————————————————————————————————————————————————————————
when isMainModule:
var image =
image.fill(
for row in 10..20:
for col in 0..<image.w:
image[col, row] =
for row in 30..40:
for col in 0..<image.w:
image[col, row] =
image.writePPM("output.ppm")</syntaxhighlight>
==
<
let width = Bigarray.Array2.dim1 r_channel
and height = Bigarray.Array2.dim2 r_channel in
Line 1,361 ⟶ 1,772:
output_char oc '\n';
flush oc;
;;</
=={{header|Oz}}==
As a function in the module <code>BitmapIO.oz</code>:
<
import
Bitmap
Line 1,403 ⟶ 1,813:
end
end
end</
=={{header|Perl}}==
{{libheader|Imager}}
<
$image = Imager->new(xsize => 200, ysize => 200);
Line 1,414 ⟶ 1,823:
xmin => 50, ymin => 50,
xmax => 150, ymax => 150);
$image->write(file => 'bitmap.ppm') or die $image->errstr;</
=={{header|Phix}}==
Copy of [[Bitmap/Write_a_PPM_file#Euphoria|Euphoria]].
<syntaxhighlight lang="phix">-- demo\rosetta\Bitmap_write_ppm.exw
constant dimx = 512, dimy = 512
constant fn = open("first.ppm","wb") -- b - binary mode
sequence color
Line 1,430 ⟶ 1,839:
end for
end for
close(fn)</syntaxhighlight>
The following more general purpose routine is used in several other examples (via include ppm.e):
<syntaxhighlight lang="phix">global procedure write_ppm(string filename, sequence image)
integer fn = open(filename,"wb"),
dimx = length(image),
dimy = length(image[1])
printf(fn, "P6\n%d %d\n255\n", {dimx,dimy})
for y
for x
sequence r_g_b =
puts(fn,r_g_b)
end for
end for
close(fn)
end procedure</
=={{header|PHP}}==
Writes a P6 binary file
<
public $data;
public $w;
Line 1,503 ⟶ 1,909:
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');</
=={{header|PicoLisp}}==
<
(out File
(prinl "P6")
(prinl (length (car Ppm)) " " (length Ppm))
(prinl 255)
(for Y Ppm (for X Y (apply wr X))) ) )</
=={{header|PL/I}}==
<
test: procedure options (main);
declare image (0:19,0:19) bit (24);
Line 1,560 ⟶ 1,964:
write file (out) from (ch);
end put_integer;
end test;</
=={{header|Prolog}}==
This is an extremely straight forward way to write in Prolog, more complicated methods might use DCGs:
<
:- module(bitmapIO, [
write_ppm_p6/2]).
Line 1,581 ⟶ 1,984:
maplist(maplist(maplist(put_byte(Output))),Pixels),
close(Output).
</syntaxhighlight>
usage:
<
:- use_module(bitmap).
:- use_module(bitmapIO).
Line 1,594 ⟶ 1,997:
write_ppm_p6('AlmostAllBlack.ppm',AlmostAllBlack).
</syntaxhighlight>
=={{header|PureBasic}}==
<
; Author Roger Rösch (Nickname Macros)
IDFiIe = CreateFile(#PB_Any, file$)
Line 1,630 ⟶ 2,032:
CloseFile(IDFiIe)
EndIf
EndProcedure</
=={{header|Python}}==
{{works with|Python|3.1}}
Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
<
# String masquerading as ppm file (version P3)
import io
Line 1,699 ⟶ 2,100:
bitmap.writeppm(ppmfileout)
ppmfileout.close()
</syntaxhighlight>
=={{header|R}}==
{{libheader|pixmap}}
<syntaxhighlight lang="r">
# View the existing code in the library
library(pixmap)
Line 1,710 ⟶ 2,110:
#Usage
write.pnm(theimage, filename)
</syntaxhighlight>
=={{header|Racket}}==
<
;P3
(define (bitmap->ppm bitmap output-port)
Line 1,755 ⟶ 2,154:
;or any other output port
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2016-01}}
<syntaxhighlight lang="raku"
class Bitmap {
has UInt ($.width, $.height);
Line 1,790 ⟶ 2,188:
}
$*OUT.write: $b.P6;</
Converted to a png. (ppm files not locally supported)
[[File:Ppm-perl6.png]]
=={{header|REXX}}==
<
green = 00ff00 /*define a pixel with the color green. */
parse arg oFN width height color . /*obtain optional arguments from the CL*/
Line 1,816 ⟶ 2,213:
call charout oFID, _ /*write the image's raster to the file.*/
call charout oFID /*close the output file just to be safe*/
/*stick a fork in it, we're all done. */</
<br><br>
=={{header|Ruby}}==
Extending [[Basic_bitmap_storage#Ruby]]
<
def values
[@red, @green, @blue]
Line 1,840 ⟶ 2,236:
end
alias_method :write, :save
end</
=={{header|Rust}}==
<
use std::io::Write;
use std::fs::File;
Line 1,905 ⟶ 2,300:
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file =
let header = format!("P6 {} {} 255\n", self.width, self.height);
Ok(())
}
}</
=={{header|Scala}}==
Extends Pixmap class from task [[Read_ppm_file#Scala|Read PPM file]].
<
def save(bm:RgbBitmap, filename:String)={
val out=new DataOutputStream(new FileOutputStream(filename))
Line 1,927 ⟶ 2,321:
}
}
}</
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<
(define (write-image image)
(define (write-row row)
Line 1,952 ⟶ 2,345:
(display 255)
(newline)
(write-image image)))))</
Example using definitions in [[Basic bitmap storage#Scheme]]:
<
(image-fill! image *black*)
(image-set! image 400 300 *blue*)
(write-ppm image "out.ppm")</
=={{header|Seed7}}==
<
include "draw.s7i";
include "color.s7i";
Line 1,984 ⟶ 2,376:
close(ppmFile);
end if;
end func;</
=={{header|Sidef}}==
{{trans|Raku}}
<
subset UInt < Int {|n| n >= 0 }
subset UInt8 < Int {|n| n ~~ ^256 }
Line 2,030 ⟶ 2,421:
}
%f"palette.ppm".write(b.p6, :raw)</
=={{header|Stata}}==
P3 format only, with Mata.
<
void writeppm(name, r, g, b) {
n = rows(r)
Line 2,055 ⟶ 2,445:
b = J(6, 6, 255)
writeppm("image.ppm", r, g, b)
end</
=={{header|Tcl}}==
{{libheader|Tk}}
Referring to [[Basic bitmap storage#Tcl]]:
<
proc output_ppm {image filename} {
Line 2,078 ⟶ 2,467:
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;# ==> 255 \n 0 \n 0 \n
close $fh</
=={{header|UNIX Shell}}==
{{works with|ksh93}}
Line 2,085 ⟶ 2,473:
Add the following function to the <tt>Bitmap_t</tt> type
<
_.to_s > "$1"
}</
Then you can:
<
# do stuff to b, and save it:
b.write '$HOME/tmp/bitmap.ppm'</
=={{header|Vedit macro language}}==
Line 2,115 ⟶ 2,502:
Return
</pre>
=={{header|Visual Basic .NET}}==
<
Dim header As String = String.Format("P6{0}{1}{2}{3}{0}255{0}", vbLf, rasterBitmap.Width, " "c, rasterBitmap.Height)
Dim bufferSize As Integer = header.Length + (rasterBitmap.Width * rasterBitmap.Height * 3)
Line 2,134 ⟶ 2,520:
Next
My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)
End Sub</
=={{header|Wren}}==
{{libheader|DOME}}
{{libheader|Wren-str}}
<syntaxhighlight lang="wren">import "graphics" for Canvas, ImageData, Color
import "dome" for Window, Process
import "io" for FileSystem
import "./str" for Strs
class Bitmap {
construct new(name, width, height) {
Window.title = name
Window.resize(width, height)
Canvas.resize(width, height)
_bmp = ImageData.create(name, width, height)
// create bitmap
for (y in 0...height) {
for (x in 0...width) {
var c = Color.rgb(x % 256, y % 256, (x * y) % 256)
pset(x, y, c)
}
}
_w = width
_h = height
}
init() {
// write bitmap to a PPM file
var ppm = ["P6\n%(_w) %(_h)\n255\n"]
for (y in 0..._h) {
for (x in 0..._w) {
var c = pget(x, y)
ppm.add(String.fromByte(c.r))
ppm.add(String.fromByte(c.g))
ppm.add(String.fromByte(c.b))
}
}
FileSystem.save("output.ppm", Strs.concat(ppm))
Process.exit(0)
}
pset(x, y, col) { _bmp.pset(x, y, col) }
pget(x, y) { _bmp.pget(x, y) }
update() {}
draw(alpha) {}
}
var Game = Bitmap.new("Bitmap - write to PPM file", 320, 320)</syntaxhighlight>
=={{header|XPL0}}==
<
def Width=180, Height=135, Color=$123456;
Line 2,174 ⟶ 2,610:
WriteImage;
SetVid(3); \restore display to normal text mode
]</
=={{header|Yabasic}}==
<
wid = 150 : hei = 200
Line 2,206 ⟶ 2,641:
poke #fn, asc("\n")
close #fn</
=={{header|zkl}}==
<
// Read BMP file
Line 2,225 ⟶ 2,659:
}
File("foo.ppm","wb").write(ppm); // File.stdout isn't binary, let GC close file</
{{out}}
<pre>
Line 2,233 ⟶ 2,667:
-rw-r--r-- 1 craigd craigd 786476 Aug 30 01:31 foo.ppm
</pre>
{{omit from|PARI/GP}}
|