Bitmap/Write a PPM file: Difference between revisions

→‎Ada: Fixed tipo an better reference
m (Adjust color element names.)
(→‎Ada: Fixed tipo an better reference)
Tags: Mobile edit Mobile web edit
(69 intermediate revisions by 31 users not shown)
Line 1:
{{task|Raster graphics operations}}
[[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).
 
Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster images, write the image to a PPM file (binary P6 prefered). <BR>
(Read [[wp:Netpbm_format|the definition of PPM file]] on Wikipedia.)
<br><br>
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">T Colour
Byte r, g, b
 
F (r, g, b)
.r = r
.g = g
.b = b
 
F ==(other)
R .r == other.r & .g == other.g & .b == other.b
 
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}}==
<langsyntaxhighlight lang="ada">with Ada.Characters.Latin_1;
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 ⟶ 230:
end loop;
Character'Write (Stream (File), LF);
end Put_PPM;</langsyntaxhighlight>
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}}==
<syntaxhighlight lang="aime">integer i, h, j, w;
file f;
 
w = 640;
h = 320;
 
f.create("out.ppm", 00644);
f.form("P6\n~ ~\n255\n", w, h);
 
j = 0;
do {
srand(j >> 4);
i = 0;
do {
16.times(f_bytes, f, drand(255), drand(255), drand(255));
} while ((i += 16) < w);
} while ((j += 1) < h);</syntaxhighlight>
=={{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">
<lang AutoHotkey>
cyan := color(0,255,255) ; r,g,b
cyanppm := Bitmap(10, 10, cyan) ; width, height, background-color
Line 67 ⟶ 470:
return 0
}
</syntaxhighlight>
</lang>
 
 
 
=={{header|AWK}}==
<langsyntaxhighlight AWKlang="awk">#!/usr/bin/awk -f
BEGIN {
split("255,0,0,255,255,0",R,",");
Line 84 ⟶ 485:
}
close(outfile);
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> Width% = 200
Height% = 200
Line 117 ⟶ 517:
col% = TINT(x%*2,y%*2)
SWAP ?^col%,?(^col%+2)
= col%</langsyntaxhighlight>
=={{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 :
<langsyntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
 
Line 144 ⟶ 566:
(void) fclose(fp);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
 
This program writes whole array in one step :
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int main()
Line 184 ⟶ 606:
printf("OK - file %s saved\n", filename);
return 0;
}</langsyntaxhighlight>
 
 
Line 193 ⟶ 615:
Interface:
 
<langsyntaxhighlight lang="c">void output_ppm(FILE *fd, image img);</langsyntaxhighlight>
 
Implementation:
 
<langsyntaxhighlight lang="c">#include "imglib.h"
 
void output_ppm(FILE *fd, image img)
Line 206 ⟶ 628:
(void) fwrite(img->buf, sizeof(pixel), n, fd);
(void) fflush(fd);
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
class PPMWriter
Line 218 ⟶ 639:
//Use a streamwriter to write the text part of the encoding
var writer = new StreamWriter(file);
writer.WriteWriteLine("P6" + "\n");
writer.WriteWriteLine($"{bitmap.Width} + " " + {bitmap.Height + "\n}");
writer.WriteWriteLine("255" + "\n");
writer.Close();
//Switch to a binary writer to write the data
Line 234 ⟶ 655:
writerB.Close();
}
}</langsyntaxhighlight>
=={{header|C++}}==
{{trans|C}}
<syntaxhighlight lang="cpp">#include <fstream>
 
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>(i % 256)
<< static_cast<char>(j % 256)
<< static_cast<char>((i * j) % 256);
}</syntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun write-rgb-buffer-to-ppm-file (filename buffer)
(with-open-file (stream filename
:element-type '(unsigned-byte 8)
Line 265 ⟶ 702:
(write-byte green stream)
(write-byte blue stream)))))))
filename)</langsyntaxhighlight>
 
=={{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;
 
{$APPTYPE CONSOLE}
 
{$R *.res}
 
uses
System.SysUtils,
System.Classes,
Vcl.Graphics;
 
type
TBitmapHelper = class helper for TBitmap
public
procedure SaveAsPPM(FileName: TFileName);
end;
 
{ TBitmapHelper }
 
procedure TBitmapHelper.SaveAsPPM(FileName: TFileName);
var
i, j, color: Integer;
Header: AnsiString;
ppm: TMemoryStream;
begin
ppm := TMemoryStream.Create;
try
Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]);
writeln(Header);
ppm.Write(Tbytes(Header), Length(Header));
 
for i := 0 to Self.Height - 1 do
for j := 0 to Self.Width - 1 do
begin
color := ColorToRGB(Self.Canvas.Pixels[i, j]);
ppm.Write(color, 3);
end;
ppm.SaveToFile(FileName);
finally
ppm.Free;
end;
end;
 
begin
with TBitmap.Create do
begin
LoadFromFile('Input.bmp');
SaveAsPPM('Output.ppm');
Free;
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).
<syntaxhighlight lang="erlang">
-module(ppm).
 
-export([ppm/1, write/2]).
 
-define(WHITESPACE, <<10>>).
-define(SPACE, <<32>>).
 
% data structure introduced in task Bitmap (module ros_bitmap.erl)
-record(bitmap, {
pixels = nil,
shape = {0, 0}
}).
 
% create ppm image from bitmap record
ppm(Bitmap) ->
{Width, Height} = Bitmap#bitmap.shape,
Pixels = ppm_pixels(Bitmap),
Maxval = 255, % original ppm format maximum
list_to_binary([
header(), width_and_height(Width, Height), maxval(Maxval), Pixels]).
 
% write bitmap as ppm file
write(Bitmap, Filename) ->
Ppm = ppm(Bitmap),
{ok, File} = file:open(Filename, [binary, write]),
file:write(File, Ppm),
file:close(File).
 
%%%%%%%%%%%% four parts of ppm file %%%%%%%%%%%%%%%%%%%%%%
header() ->
[<<"P6">>, ?WHITESPACE].
 
width_and_height(Width, Height) ->
[encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE].
 
maxval(Maxval) ->
[encode_decimal(Maxval), ?WHITESPACE].
 
ppm_pixels(Bitmap) ->
% 24 bit color depth
array:to_list(Bitmap#bitmap.pixels).
 
%%%%%%%%%%%% Internals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
encode_decimal(Number) ->
integer_to_list(Number).
 
</syntaxhighlight>
=={{header|Euphoria}}==
{{trans|C}}
<langsyntaxhighlight lang="euphoria">constant dimx = 800, dimy = 800
constant fn = open("first.ppm","wb") -- b - binary mode
sequence color
Line 290 ⟶ 829:
end for
end for
close(fn)</langsyntaxhighlight>
 
Procedure writing [[Bitmap#Euphoria|bitmap]] data storage:
<langsyntaxhighlight lang="euphoria">procedure write_ppm(sequence filename, sequence image)
integer fn,dimx,dimy
dimy = length(image[1])
Line 306 ⟶ 845:
end for
close(fn)
end procedure</langsyntaxhighlight>
 
=={{header|FBSL}}==
This code converts a Windows BMP to a PPM. Uses FBSL volatiles for brevity.
Line 313 ⟶ 851:
'''24-bpp P.O.T.-size BMP solution:'''
[[File:FBSLWritePpm.PNG|right]]
<langsyntaxhighlight lang="qbasic">#ESCAPECHARS ON
 
DIM bmpin = ".\\LenaClr.bmp", ppmout = ".\\Lena.ppm", bmpblob = 54 ' Size of BMP file headers
Line 335 ⟶ 873:
WEND
 
FILEPUT(FILEOPEN(ppmout, BINARY_NEW), ppmdata): FILECLOSE(FILEOPEN)</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: write-ppm { bmp fid -- }
s" P6" fid write-line throw
bmp bdim swap
Line 351 ⟶ 888:
s" red.ppm" w/o create-file throw
test over write-ppm
close-file throw</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
It loads <code>RCImageBasicrgbimage_m</code> module, which is defined [[Basic bitmap storage#Fortran|here]].
<langsyntaxhighlight lang="fortran">moduleprogram RCImageIOmain
 
use RCImageBasic
use rgbimage_m
 
implicit none
 
integer :: nx, ny, i, j, k
contains
 
type(rgbimage) :: im
 
! init image of height nx, width ny
subroutine output_ppm(u, img)
nx = 400
integer, intent(in) :: u
ny = 300
type(rgbimage), intent(in) :: img
call im%init(nx, ny)
integer :: i, j
 
! set some random pixel data
write(u, '(A2)') 'P6'
do i = 1, nx
write(u, '(I0,'' '',I0)') img%width, img%height
write(u,do '(A)')j = 1, '255'ny
call im%set_pixel(i, j, [(nint(rand()*255), k=1,3)])
do j=1, img%height
do i=1, img%width
write(u, '(3A1)', advance='no') achar(img%red(i,j)), achar(img%green(i,j)), &
achar(img%blue(i,j))
end do
end do
end do
 
! output image into file
end subroutine output_ppm
call im%write('fig.ppm')
 
end program</syntaxhighlight>
end module RCImageIO</lang>
=={{header|GAP}}==
<langsyntaxhighlight lang="gap"># Dirty implementation
# Only P3 format, an image is a list of 3 matrices (r, g, b)
# Max color is always 255
Line 433 ⟶ 969:
PutPixel(g, 2, 2, [255, 255, 255]);
PutPixel(g, 2, 3, [0, 0, 0]);
WriteImage("example.ppm", g);</langsyntaxhighlight>
=={{header|Go}}==
Code below writes 8-bit P6 format only. See Bitmap task for additional file needed to build working raster package.
<langsyntaxhighlight lang="go">package raster
 
import (
Line 489 ⟶ 1,025:
}
return f.Close()
}</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="go">package main
 
// Files required to build supporting package raster are found in:
Line 509 ⟶ 1,045:
fmt.Println(err)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">{-# LANGUAGE ScopedTypeVariables #-}
 
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where
Line 561 ⟶ 1,096:
stToIO (getPixels i) >>= hPutStr h . toNetpbm
where magicNumber = netpbmMagicNumber (nil :: c)
maxval = netpbmMaxval (nil :: c)</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">require 'files'
 
NB. ($x) is height, width, colors per pixel
Line 571 ⟶ 1,105:
header=. 'P6',LF,(":1 0{$x),LF,'255',LF
(header,,x{a.) fwrite y
)</langsyntaxhighlight>
'''Example:'''
Using routines from [[Basic_bitmap_storage#J|Basic Bitmap Storage]]:
<langsyntaxhighlight lang="j"> NB. create 10 by 10 block of magenta pixels in top right quadrant of a 300 wide by 600 high green image
pixellist=: >,{;~i.10
myimg=: ((150 + pixellist) ; 255 0 255) setPixels 0 255 0 makeRGB 600 300
myimg writeppm jpath '~temp/myimg.ppm'
540015</langsyntaxhighlight>
=={{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}}
===Using Packages===
The <code>Images.jl</code> package supports <tt>PPM</tt> output, simplifying this task.
<lang Julia>
using Color, Images, FixedPointNumbers
 
<syntaxhighlight lang="julia">using Images, FileIO
w = 70
h = 50
 
h, w = 50, 70
a = zeros(RGB{Ufixed8}, h, w)
img = Imagezeros(aRGB{N0f8}, h, w)
img[10:40, 5:35] = colorant"skyblue"
for i in 26:50, j in (i-25):40
img["x", 10:40, "y", 5:35] = color("skyblue")
img[i, j] = colorant"sienna1"
for i in 45:65, j in (i-25):40
img["x", i, "y", j] = color("sienna1")
end
 
save("data/bitmapWrite.ppm", img)
imwrite(img, "bitmap_write.ppm")
save("data/bitmapWrite.png", img)</syntaxhighlight>
imwrite(img, "bitmap_write.png")
=={{header|Kotlin}}==
</lang>
For convenience, we repeat the code for the class used in the [[Bitmap]] task here.
<syntaxhighlight lang="scala">// Version 1.2.40
 
import java.awt.Color
{{out}}
import java.awt.Graphics
The files [https://github.com/MichaeLeroy/rosetta-code/blob/master/julia/completed/bitmap_write.ppm bitmap_write.ppm] and [https://raw.githubusercontent.com/MichaeLeroy/rosetta-code/master/julia/completed/bitmap_write.png bitmap_write.png] are available at github.
import java.awt.image.BufferedImage
===DIY===
import java.io.FileOutputStream
This entry expands that of [[http://rosettacode.org/wiki/Bitmap#Julia Bitmap]], adding <code>writeppm</code> to handle the output of the ppm file. See that entry for definitions the types and methods used here to create the image file.
 
class BasicBitmapStorage(width: Int, height: Int) {
'''The write function'''
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
<lang Julia>
function writeppm(fn::String, a::Image)
outf = open(fn, "w")
(w, h) = size(a.pic)
write(outf, "P6\n")
write(outf, @sprintf "%d %d\n" w h)
write(outf, @sprintf "%d\n" 255)
for i in 1:h
for j in 1:w
c = color(a, j, i)
write(outf, c.r)
write(outf, c.g)
write(outf, c.b)
end
end
close(outf)
end
</lang>
 
fun fill(c: Color) {
'''Setup and Invocation'''
val g = image.graphics
<lang Julia>
g.color = c
w = 500
g.fillRect(0, 0, image.width, image.height)
h = 300
}
a = Image(w, h)
 
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
purple = Color(0xff, 0, 0xff)
green = Color(0, 0xff, 0)
white = Color(0xff, 0xff, 0xff)
 
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
fill!(a, green)
}
for i in 20:220, j in 10:100
splat!(a, i, j, purple)
end
for i in 180:400, j in 80:200
splat!(a, i, j, white)
end
 
fun main(args: Array<String>) {
fn = "bitmap_write.ppm"
// create BasicBitmapStorage object
writeppm(fn, a)
val width = 640
</lang>
val height = 640
val bbs = BasicBitmapStorage(width, height)
for (y in 0 until height) {
for (x in 0 until width) {
val c = Color(x % 256, y % 256, (x * y) % 256)
bbs.setPixel(x, y, c)
}
}
 
// now write it to a PPM file
val fos = FileOutputStream("output.ppm")
val buffer = ByteArray(width * 3) // write one line at a time
fos.use {
val header = "P6\n$width $height\n255\n".toByteArray()
with (it) {
write(header)
for (y in 0 until height) {
for (x in 0 until width) {
val c = bbs.getPixel(x, y)
buffer[x * 3] = c.red.toByte()
buffer[x * 3 + 1] = c.green.toByte()
buffer[x * 3 + 2] = c.blue.toByte()
}
write(buffer)
}
}
}
}</syntaxhighlight>
=={{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===
<lang lua>
<syntaxhighlight lang="lua">
 
-- helper function, simulates PHP's array_fill function
Line 707 ⟶ 1,279:
end
 
function Bitmap:fill(x, y, width, heigthheight, color)
width = (width == nil) and self.width or width
height = (height == nil) and self.height or height
Line 757 ⟶ 1,329:
 
example_colorful_stripes():writeP6('p6.ppm')
</syntaxhighlight>
</lang>
===Alternate===
Uses the alternate Bitmap implementation [[Bitmap#Alternate|here]], extending it with..
<syntaxhighlight lang="lua">Bitmap.savePPM = function(self, filename)
local fp = io.open(filename, "wb")
if fp == nil then return false end
fp:write(string.format("P6\n%d %d\n%d\n", self.width, self.height, 255))
for y = 1, self.height do
for x = 1, self.width do
local pix = self.pixels[y][x]
fp:write(string.char(pix[1]), string.char(pix[2]), string.char(pix[3]))
end
end
fp:close()
return true
end</syntaxhighlight>
Example usage:
<syntaxhighlight lang="lua">local bitmap = Bitmap(11,5)
bitmap:clear({255,255,255})
for y = 1, 5 do
for x = 1, 11 do
if x==1 or x==5 or x==7 or (y>1 and (x==9 or x==11)) or (y==5 and x~=4 and x~=8 and x~=10) or (x==10 and (y==1 or y==3)) then
bitmap:set(x-1, y-1, {0,0,0}) -- creates "LUA" with 3x5 font
end
end
end
bitmap:savePPM("lua3x5.ppm")</syntaxhighlight>
=={{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) {
if x<1 or y<1 then Error "Wrong dimensions"
structure rgb {
red as byte
green as byte
blue as byte
}
m=len(rgb)*x mod 4
if m>0 then m=4-m ' add some bytes to raster line
m+=len(rgb) *x
Structure rasterline {
{
pad as byte*m
}
\\ union pad+hline
hline as rgb*x
}
Structure Raster {
magic as integer*4
w as integer*4
h as integer*4
lines as rasterline*y
}
Buffer Clear Image1 as Raster
\\ 24 chars as header to be used from bitmap render build in functions
Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2)
\\ fill white (all 255)
\\ Str$(string) convert to ascii, so we get all characters from words width to byte width
Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y))
Buffer Clear Pad as Byte*4
SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{
where=alines+3*x+blines*y
if c>0 then c=color(c)
c-!
Return Pad, 0:=c as long
Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte
}
GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{
where=alines+3*x+blines*y
=color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte))
}
StrDib$=Lambda$ Image1, Raster -> {
=Eval$(Image1, 0, Len(Raster))
}
CopyImage=Lambda Image1 (image$) -> {
if left$(image$,12)=Eval$(Image1, 0, 24 ) Then {
Return Image1, 0:=Image$
} Else Error "Can't Copy Image"
}
Export2File=Lambda Image1, x, y (f) -> {
\\ use this between open and close
Print #f, "P3"
Print #f,"# Created using M2000 Interpreter"
Print #f, x;" ";y
Print #f, 255
x2=x-1
where=24
For y1= 0 to y-1 {
a$=""
For x1=0 to x2 {
Print #f, a$;Eval(Image1, where +2 as byte);" ";
Print #f, Eval(Image1, where+1 as byte);" ";
Print #f, Eval(Image1, where as byte);
where+=3
a$=" "
}
Print #f
m=where mod 4
if m<>0 then where+=4-m
}
}
Group Bitmap {
SetPixel=SetPixel
GetPixel=GetPixel
Image$=StrDib$
Copy=CopyImage
ToFile=Export2File
}
=Bitmap
}
A=Bitmap(10, 10)
Call A.SetPixel(5,5, color(128,0,255))
Open "A2.PPM" for Output as #F
Call A.ToFile(F)
Close #f
' is the same as this one
Try {
Open "A.PPM" for Output as #F
Print #f, "P3"
Print #f,"# Created using M2000 Interpreter"
Print #f, 10;" ";10
Print #f, 255
For y=10-1 to 0 {
a$=""
For x=0 to 10-1 {
rgb=-A.GetPixel(x, y)
Print #f, a$;Binary.And(rgb, 0xFF); " ";
Print #f, Binary.And(Binary.Shift(rgb, -8), 0xFF); " ";
Print #f, Binary.Shift(rgb, -16);
a$=" "
}
Print #f
}
Close #f
}
}
Checkit
 
</syntaxhighlight>
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
<lang Mathematica>Export["file.ppm",image,"PPM"]</lang>
 
{{out}}
<pre style="height:30ex;overflow:scroll">
P3
# Created using M2000 Interpreter
10 10
255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 128 0 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255 255
</pre >
 
===P6 type===
<syntaxhighlight lang="m2000 interpreter">
Module PPMbinaryP6 {
If Version<9.4 then 1000
If Version=9.4 Then if Revision<19 then 1000
Module Checkit {
Function Bitmap {
def x as long, y as long
If match("NN") then {
Read x, y
} else.if Match("N") Then {
E$="Not a ppm file"
Read f as long
buffer whitespace as byte
if not Eof(f) then {
get #f, whitespace : iF eof(f) then Error E$
P6$=eval$(whitespace)
get #f, whitespace : iF eof(f) then Error E$
P6$+=eval$(whitespace)
def boolean getW=true, getH=true, getV=true
def long v
\\ str$("P6") has 2 bytes. "P6" has 4 bytes
If p6$=str$("P6") Then {
do {
get #f, whitespace
if Eval$(whitespace)=str$("#") then {
do {
iF eof(f) then Error E$
get #f, whitespace
} until eval(whitespace)=10
} else {
select case eval(whitespace)
case 32, 9, 13, 10
{
if getW and x<>0 then {
getW=false
} else.if getH and y<>0 then {
getH=false
} else.if getV and v<>0 then {
getV=false
}
}
case 48 to 57
{
if getW then {
x*=10
x+=eval(whitespace, 0)-48
} else.if getH then {
y*=10
y+=eval(whitespace, 0)-48
} else.if getV then {
v*=10
v+=eval(whitespace, 0)-48
}
}
End Select
}
iF eof(f) then Error E$
} until getV=false
} else Error "Not a P6 ppm"
}
} else Error "No proper arguments"
if x<1 or y<1 then Error "Wrong dimensions"
structure rgb {
red as byte
green as byte
blue as byte
}
m=len(rgb)*x mod 4
if m>0 then m=4-m ' add some bytes to raster line
m+=len(rgb) *x
Structure rasterline {
{
pad as byte*m
}
\\ union pad+hline
hline as rgb*x
}
\\ we use union linesB and lines
\\ so we can address linesb as bytes
Structure Raster {
magic as integer*4
w as integer*4
h as integer*4
{
linesB as byte*len(rasterline)*y
}
lines as rasterline*y
}
Buffer Clear Image1 as Raster
\\ 24 chars as header to be used from bitmap render build in functions
Return Image1, 0!magic:="cDIB", 0!w:=Hex$(x,2), 0!h:=Hex$(y, 2)
\\ fill white (all 255)
\\ Str$(string) convert to ascii, so we get all characters from words width to byte width
if not valid(f) then Return Image1, 0!lines:=Str$(String$(chrcode$(255), Len(rasterline)*y))
Buffer Clear Pad as Byte*4
SetPixel=Lambda Image1, Pad,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x, y, c) ->{
where=alines+3*x+blines*y
if c>0 then c=color(c)
c-!
Return Pad, 0:=c as long
Return Image1, 0!where:=Eval(Pad, 2) as byte, 0!where+1:=Eval(Pad, 1) as byte, 0!where+2:=Eval(Pad, 0) as byte
}
GetPixel=Lambda Image1,aLines=Len(Raster)-Len(Rasterline), blines=-Len(Rasterline) (x,y) ->{
where=alines+3*x+blines*y
=color(Eval(image1, where+2 as byte), Eval(image1, where+1 as byte), Eval(image1, where as byte))
}
StrDib$=Lambda$ Image1, Raster -> {
=Eval$(Image1, 0, Len(Raster))
}
CopyImage=Lambda Image1 (image$) -> {
if left$(image$,12)=Eval$(Image1, 0, 24 ) Then {
Return Image1, 0:=Image$
} Else Error "Can't Copy Image"
}
Export2File=Lambda Image1, x, y (f) -> {
\\ use this between open and close
Print #f, "P6";chr$(10);
Print #f,"# Created using M2000 Interpreter";chr$(10);
Print #f, x;" ";y;" 255";chr$(10);
x2=x-1
where=0
Buffer pad as byte*3
For y1= 0 to y-1 {
For x1=0 to x2 {
\\ use linesB which is array of bytes
Return pad, 0:=eval$(image1, 0!linesB!where, 3)
Push Eval(pad, 2)
Return pad, 2:=Eval(pad, 0), 0:=Number
Put #f, pad
where+=3
}
m=where mod 4
if m<>0 then where+=4-m
}
}
if valid(F) then {
x0=x-1
where=0
Buffer Pad1 as byte*3
For y1=y-1 to 0 {
For x1=0 to x0 {
Get #f, Pad1 ' Read binary
\\ reverse rgb
Push Eval(pad1, 2)
Return pad1, 2:=Eval(pad1, 0), 0:=Number
Return Image1, 0!linesB!where:=Eval$(Pad1)
where+=3
}
m=where mod 4
if m<>0 then where+=4-m
}
}
Group Bitmap {
SetPixel=SetPixel
GetPixel=GetPixel
Image$=StrDib$
Copy=CopyImage
ToFile=Export2File
}
=Bitmap
}
A=Bitmap(10, 10)
Call A.SetPixel(5,5, color(128,0,255))
Open "A.PPM" for Output as #F
Call A.ToFile(F)
Close #f
Print "Saved"
Open "A.PPM" for Input as #F
C=Bitmap(f)
Copy 400*twipsx,200*twipsy use C.Image$()
Close #f
}
Checkit
End
1000 Error "Need Version 9.4, Revision 19 or higher"
}
PPMbinaryP6
 
</syntaxhighlight>
=={{header|Mathematica}}/ {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Export["file.ppm",image,"PPM"]</syntaxhighlight>
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">R=[255,0,0;255,255,0];
G=[0,255,0;255,255,0];
B=[0,0,255;0,0,0];
Line 774 ⟶ 1,687:
fprintf(fid,'P6\n%i %i\n255\n',size(R));
fwrite(fid,[r,g,b]','uint8');
fclose(fid);</langsyntaxhighlight>
 
 
=={{header|Modula-3}}==
<code>Bitmap</code> is the module from [[Basic_bitmap_storage#Modula-3|Basic Bitmap Storage]].
<langsyntaxhighlight lang="modula3">INTERFACE PPM;
 
IMPORT Bitmap, Pathname;
Line 785 ⟶ 1,696:
PROCEDURE Create(imgfile: Pathname.T; img: Bitmap.T);
 
END PPM.</langsyntaxhighlight>
<langsyntaxhighlight lang="modula3">MODULE PPM;
 
IMPORT Bitmap, Wr, FileWr, Pathname;
Line 815 ⟶ 1,726:
BEGIN
END PPM.</langsyntaxhighlight>
 
== {{Header|Nim}} ==
<syntaxhighlight lang="nim">import bitmap
<lang nim>proc writePPM(img: Image, f: TFile) =
import streams
f.writeln "P6\n", img.w, " ", img.h, "\n255"
 
#---------------------------------------------------------------------------------------------------
for x,y in img.indices:
f.write char(img[x,y].r)
f.write char(img[x,y].g)
f.write char(img[x,y].b)</lang>
 
proc writePPM*(img: Image, stream: Stream) =
== {{Header|OCaml}} ==
## Write an image to a PPM stream.
 
stream.writeLine("P6 ", $img.w, " ", $img.h, " 255")
<lang ocaml>let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) =
 
for x, y in img.indices:
stream.write(chr(img[x, y].r))
stream.write(chr(img[x, y].g))
stream.write(chr(img[x, y].b))
 
#---------------------------------------------------------------------------------------------------
 
proc writePPM*(img: Image; filename: string) =
## Write an image in a PPM file.
 
var file = openFileStream(filename, fmWrite)
img.writePPM(file)
file.close()
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
when isMainModule:
var image = newImage(100, 50)
image.fill(color(255, 0, 0))
for row in 10..20:
for col in 0..<image.w:
image[col, row] = color(0, 255, 0)
for row in 30..40:
for col in 0..<image.w:
image[col, row] = color(0, 0, 255)
image.writePPM("output.ppm")</syntaxhighlight>
 
=={{Header|OCaml}}==
 
<syntaxhighlight lang="ocaml">let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) =
let width = Bigarray.Array2.dim1 r_channel
and height = Bigarray.Array2.dim2 r_channel in
Line 841 ⟶ 1,781:
output_char oc '\n';
flush oc;
;;</langsyntaxhighlight>
 
=={{header|Oz}}==
As a function in the module <code>BitmapIO.oz</code>:
<langsyntaxhighlight lang="oz">functor
import
Bitmap
Line 883 ⟶ 1,822:
end
end
end</langsyntaxhighlight>
 
=={{header|Perl}}==
{{libheader|Imager}}
<syntaxhighlight lang="perl">use Imager;
 
$image = Imager->new(xsize => 200, ysize => 200);
{{libheader|Imlib2}}
$image->box(filled => 1, color => red);
 
$image->box(filled => 1, color => black,
Imlib2 can handle several formats, among these JPG, PNG, PNM/PPM... (but it depends on how the Imlib2 was built on the system, since the ability to load or save in these formats depends on other external libraries, like <tt>libpng</tt> e.g.)
xmin => 50, ymin => 50,
 
xmax => 150, ymax => 150);
<lang perl>#! /usr/bin/perl
$image->write(file => 'bitmap.ppm') or die $image->errstr;</syntaxhighlight>
 
use strict;
use Image::Imlib2;
 
my $img = Image::Imlib2->new(100,100);
$img->set_color(100,200,0, 255);
$img->fill_rectangle(0,0,100,100);
 
$img->save("out0.ppm");
$img->save("out0.jpg");
$img->save("out0.png");
 
exit 0;</lang>
 
Normally Image::Imlib2 understands which output format to use from the extension; to override its guess, you can use:
 
<lang perl>$img->image_set_format("jpeg"); # or png, tiff, ppm ...</lang>
 
=={{header|Perl 6}}==
{{works with|Rakudo|2016-01}}
 
<lang perl6>class Pixel { has uint8 ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
has Pixel @!data;
 
method fill(Pixel $p) {
@!data = $p.clone xx ($!width*$!height)
}
method pixel(
$i where ^$!width,
$j where ^$!height
--> Pixel
) is rw { @!data[$i*$!height + $j] }
 
method data { @!data }
}
 
role PPM {
method P6 returns Blob {
"P6\n{self.width} {self.height}\n255\n".encode('ascii')
~ Blob.new: flat map { .R, .G, .B }, self.data
}
}
 
my Bitmap $b = Bitmap.new(width => 125, height => 125) but PPM;
for flat ^$b.height X ^$b.width -> $i, $j {
$b.pixel($i, $j) = Pixel.new: :R($i*2), :G($j*2), :B(255-$i*2);
}
 
$*OUT.write: $b.P6;</lang>
Converted to a png. (ppm files not locally supported)
 
[[File:Ppm-perl6.png‎]]
 
=={{header|Phix}}==
Copy of [[Bitmap/Write_a_PPM_file#Euphoria|Euphoria]]. Included as demo\rosetta\Bitmap_write_ppm.exw The results may be verified with demo\rosetta\viewppm.exw
<syntaxhighlight lang="phix">-- demo\rosetta\Bitmap_write_ppm.exw
<lang Phix>constant dimx = 512, dimy = 512
constant dimx = 512, dimy = 512
constant fn = open("first.ppm","wb") -- b - binary mode
sequence color
Line 961 ⟶ 1,848:
end for
end for
close(fn)</syntaxhighlight>
The following more general purpose routine is used in several other examples (via include ppm.e):
</lang>
<syntaxhighlight lang="phix">global procedure write_ppm(string filename, sequence image)
The following more general purpose routine is used in several other examples:
integer fn = open(filename,"wb"),
<lang Phix>procedure write_ppm(sequence filename, sequence image)
dimx = length(image),
integer fn,dimx,dimy
dimy = length(image[1])
sequence colour_triple
fn = open(filename,"wb")
dimx = length(image)
dimy = length(image[1])
printf(fn, "P6\n%d %d\n255\n", {dimx,dimy})
for y = 1 to dimy do
for x = 1 to dimx do
colour_tripleinteger pixel = sq_div(sq_and_bits(image[x][y], {#FF0000,#FF00 -- red,#FF})green,blue
sequence r_g_b = sq_and_bits(pixel,{#010000FF0000,#0100FF00,#01FF})
puts r_g_b = sq_floor_div(fnr_g_b, colour_triple{#010000,#0100,#01})
puts(fn,r_g_b)
end for
end for
close(fn)
end procedure</langsyntaxhighlight>
 
=={{header|PHP}}==
Writes a P6 binary file
<langsyntaxhighlight PHPlang="php">class Bitmap {
public $data;
public $w;
Line 1,034 ⟶ 1,918:
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
$b->writeP6('p6.ppm');</langsyntaxhighlight>
=={{header|PicoLisp}}==
 
<syntaxhighlight lang="picolisp">(de ppmWrite (Ppm File)
(out File
(prinl "P6")
(prinl (length (car Ppm)) " " (length Ppm))
(prinl 255)
(for Y Ppm (for X Y (apply wr X))) ) )</syntaxhighlight>
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">/* BITMAP FILE: write out a file in PPM format, P6 (binary). 14/5/2010 */
test: procedure options (main);
declare image (0:19,0:19) bit (24);
Line 1,083 ⟶ 1,973:
write file (out) from (ch);
end put_integer;
end test;</langsyntaxhighlight>
=={{header|Prolog}}==
This is an extremely straight forward way to write in Prolog, more complicated methods might use DCGs:
<syntaxhighlight lang="prolog">
:- module(bitmapIO, [
write_ppm_p6/2]).
 
:- use_module(library(lists)).
=={{header|PicoLisp}}==
 
<lang PicoLisp>(de ppmWrite (Ppm File)
%write_ppm_p6(File,Bitmap)
(out File
write_ppm_p6(Filename,[[X,Y],Pixels]):-
(prinl "P6")
open(Filename,write,Output,[encoding(octet)]),
(prinl (length (car Ppm)) " " (length Ppm))
%write p6 header
(prinl 255)
writeln(Output, 'P6'),
(for Y Ppm (for X Y (apply wr X))) ) )</lang>
atomic_list_concat([X, Y], ' ', Dimensions),
writeln(Output, Dimensions),
writeln(Output, '255'),
%write bytes
maplist(maplist(maplist(put_byte(Output))),Pixels),
close(Output).
</syntaxhighlight>
 
usage:
 
<syntaxhighlight lang="prolog">
:- use_module(bitmap).
:- use_module(bitmapIO).
 
write :-
new_bitmap(AllBlack,[50,50],[0,0,0]),
set_pixel0(AlmostAllBlack,AllBlack,[25,25],[255,255,255]),
write_ppm_p6('AlmostAllBlack.ppm',AlmostAllBlack).
 
</syntaxhighlight>
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure SaveImageAsPPM(Image, file$, Binary = 1)
; Author Roger Rösch (Nickname Macros)
IDFiIe = CreateFile(#PB_Any, file$)
Line 1,127 ⟶ 2,041:
CloseFile(IDFiIe)
EndIf
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
{{works with|Python|3.1}}
 
Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
<langsyntaxhighlight lang="python">
# String masquerading as ppm file (version P3)
import io
Line 1,196 ⟶ 2,109:
bitmap.writeppm(ppmfileout)
ppmfileout.close()
</syntaxhighlight>
</lang>
 
=={{header|R}}==
{{libheader|pixmap}}
<syntaxhighlight lang="r">
<lang r>
# View the existing code in the library
library(pixmap)
Line 1,207 ⟶ 2,119:
#Usage
write.pnm(theimage, filename)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
;P3
(define (bitmap->ppm bitmap output-port)
Line 1,252 ⟶ 2,163:
;or any other output port
 
</syntaxhighlight>
</lang>
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2016-01}}
 
<syntaxhighlight lang="raku" line>class Pixel { has uint8 ($.R, $.G, $.B) }
=={{header|REXX}}==
class Bitmap {
<lang rexx>/*REXX program to write a PPM formatted image file, P6 (binary). */
has UInt ($.width, $.height);
oFID = 'IMAGE.PPM' /*name of the output file. */
has Pixel @!data;
green = '00 ff 00'x
image. = green /*define all IMAGE RGB's to green*/
width = 20 /*define the width of IMAGE. */
height = 20 /* " " height " " */
sep = '9'x
call put 'P6'width||sep||height||sep||255||sep /*write header info.*/
 
method fill(Pixel $p) {
do j =1 for width
do@!data k=1 $p.clone forxx ($!width*$!height)
}
call put image.j.k /*write IMAGE, 3 bytes at a time.*/
method pixel(
end /*k*/
$i where ^$!width,
end /*j*/
$j where ^$!height
exit /*stick a fork in it, we're done.*/
--> Pixel
/*─────────────────────────────────────subroutines──────────────────────*/
) is rw { @!data[$i*$!height + $j] }
put: call charout oFID,arg(1); return /*write out character(s) to file.*/</lang>
 
method data { @!data }
}
 
role PPM {
method P6 returns Blob {
"P6\n{self.width} {self.height}\n255\n".encode('ascii')
~ Blob.new: flat map { .R, .G, .B }, self.data
}
}
 
my Bitmap $b = Bitmap.new(width => 125, height => 125) but PPM;
for flat ^$b.height X ^$b.width -> $i, $j {
$b.pixel($i, $j) = Pixel.new: :R($i*2), :G($j*2), :B(255-$i*2);
}
 
$*OUT.write: $b.P6;</syntaxhighlight>
Converted to a png. (ppm files not locally supported)
 
[[File:Ppm-perl6.png‎]]
=={{header|REXX}}==
<syntaxhighlight lang="rexx">/*REXX program writes a PPM formatted image file, also known as a P6 (binary) file. */
green = 00ff00 /*define a pixel with the color green. */
parse arg oFN width height color . /*obtain optional arguments from the CL*/
if oFN=='' | oFN=="," then oFN='IMAGE' /*Not specified? Then use the default.*/
if width=='' | width=="," then width= 20 /* " " " " " " */
if height=='' | height=="," then height= 20 /* " " " " " " */
if color=='' | color=="," then color= green /* " " " " " " */
oFID= oFN'.PPM' /*define oFID by adding an extension.*/
@. = x2c(color) /*set all pixels of image a hex color. */
$ = '9'x /*define the separator (in the header).*/
# = 255 /* " " max value for all colors. */
call charout oFID, , 1 /*set the position of the file's output*/
call charout oFID,'P6'width || $ || height || $ || # || $ /*write file header info. */
_=
do j =1 for width
do k=1 for height; _= _ || @.j.k /*write the PPM file, 1 pixel at a time*/
end /*k*/ /* ↑ a pixel contains three bytes, */
end /*j*/ /* └────which defines the pixel's color*/
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. */</syntaxhighlight>
<br><br>
=={{header|Ruby}}==
Extending [[Basic_bitmap_storage#Ruby]]
<langsyntaxhighlight lang="ruby">class RGBColour
def values
[@red, @green, @blue]
Line 1,294 ⟶ 2,245:
end
alias_method :write, :save
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::path::Path;
use std::io::Write;
use std::fs::File;
Line 1,359 ⟶ 2,309:
pub fn write_file(&self, filename: &str) -> std::io::Result<()> {
let path = Path::new(filename);
let mut file = try!(File::create(&path))?;
let header = format!("P6 {} {} 255\n", self.width, self.height);
try!(file.write(header.as_bytes()))?;
try!(file.write(&self.data))?;
Ok(())
}
}</langsyntaxhighlight>
 
=={{header|Scala}}==
Extends Pixmap class from task [[Read_ppm_file#Scala|Read PPM file]].
<langsyntaxhighlight lang="scala">object Pixmap {
def save(bm:RgbBitmap, filename:String)={
val out=new DataOutputStream(new FileOutputStream(filename))
Line 1,381 ⟶ 2,330:
}
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<langsyntaxhighlight lang="scheme">(define (write-ppm image file)
(define (write-image image)
(define (write-row row)
Line 1,406 ⟶ 2,354:
(display 255)
(newline)
(write-image image)))))</langsyntaxhighlight>
Example using definitions in [[Basic bitmap storage#Scheme]]:
<langsyntaxhighlight lang="scheme">(define image (make-image 800 600))
(image-fill! image *black*)
(image-set! image 400 300 *blue*)
(write-ppm image "out.ppm")</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "draw.s7i";
include "color.s7i";
Line 1,438 ⟶ 2,385:
close(ppmFile);
end if;
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl 6Raku}}
<langsyntaxhighlight lang="ruby">subset Int < Number {|n| n.is_int }
subset UintUInt < Int {|n| n >= 0 }
subset Uint8UInt8 < Int {|n| n ~~ ^256 }
 
struct Pixel {
R < Uint8UInt8,
G < Uint8UInt8,
B < Uint8UInt8
}
 
class Bitmap(width < UintUInt, height < UintUInt) {
has data = []
 
Line 1,459 ⟶ 2,405:
}
 
method setpixel(i < UintUInt, j < UintUInt, Pixel p) {
 
subset WidthLimit < UintUInt { |n| n ~~ ^width }
subset HeightLimit < UintUInt { |n| n ~~ ^height }
 
func (w < WidthLimit, h < HeightLimit) {
Line 1,470 ⟶ 2,416:
 
method p6 {
<<-EOT + data.map {|p| [p.R, p.G, p.B].pack('C3') }.join
"P6\n#{width} #{height}\n255\n" +
P6
data.map {|p| [p.R, p.G, p.B].pack('C3') }.join
#{width} #{height}
255
EOT
}
}
Line 1,481 ⟶ 2,430:
}
 
var file = File(%f"palette.ppm".write(b.p6, :raw)</syntaxhighlight>
=={{header|Stata}}==
var fh = file.open('>:raw')
fh.print(b.p6)
fh.close</lang>
 
P3 format only, with Mata.
 
<syntaxhighlight lang="stata">mata
void writeppm(name, r, g, b) {
n = rows(r)
p = cols(r)
f = fopen(name, "w")
fput(f, "P3")
fput(f, strofreal(p) + " " + strofreal(n) + " 255")
for (i = 1; i <= n; i++) {
for (j = 1; j <= p; j++) {
fput(f, strofreal(r[i,j]) + " " + strofreal(g[i,j]) + " " + strofreal(b[i,j]))
}
}
fclose(f)
}
 
r = J(1, 6, (0::5) * 51)
g = J(6, 1, (0..5) * 51)
b = J(6, 6, 255)
writeppm("image.ppm", r, g, b)
end</syntaxhighlight>
=={{header|Tcl}}==
{{libheader|Tk}}
Referring to [[Basic bitmap storage#Tcl]]:
<langsyntaxhighlight lang="tcl">package require Tk
 
proc output_ppm {image filename} {
Line 1,507 ⟶ 2,476:
binary scan [read $fh 3] c3 pixel
foreach colour $pixel {puts [expr {$colour & 0xff}]} ;# ==> 255 \n 0 \n 0 \n
close $fh</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|ksh93}}
Line 1,514 ⟶ 2,482:
 
Add the following function to the <tt>Bitmap_t</tt> type
<langsyntaxhighlight lang="bash"> function write {
_.to_s > "$1"
}</langsyntaxhighlight>
Then you can:
<langsyntaxhighlight lang="bash">Bitmap_t b
# do stuff to b, and save it:
b.write '$HOME/tmp/bitmap.ppm'</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
<lang vbnet>Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)
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)
Dim bytes(bufferSize - 1) As Byte
Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)
Dim index As Integer = header.Length
For y As Integer = 0 To rasterBitmap.Height - 1
For x As Integer = 0 To rasterBitmap.Width - 1
Dim color As Rgb = rasterBitmap.GetPixel(x, y)
bytes(index) = color.R
bytes(index + 1) = color.G
bytes(index + 2) = color.B
index += 3
Next
Next
My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)
End Sub</lang>
 
=={{header|Vedit macro language}}==
 
Line 1,564 ⟶ 2,511:
Return
</pre>
=={{header|Visual Basic .NET}}==
 
<syntaxhighlight lang="vbnet">Public Shared Sub SaveRasterBitmapToPpmFile(ByVal rasterBitmap As RasterBitmap, ByVal filepath As String)
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)
Dim bytes(bufferSize - 1) As Byte
Buffer.BlockCopy(Encoding.ASCII.GetBytes(header.ToString), 0, bytes, 0, header.Length)
Dim index As Integer = header.Length
For y As Integer = 0 To rasterBitmap.Height - 1
For x As Integer = 0 To rasterBitmap.Width - 1
Dim color As Rgb = rasterBitmap.GetPixel(x, y)
bytes(index) = color.R
bytes(index + 1) = color.G
bytes(index + 2) = color.B
index += 3
Next
Next
My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)
End Sub</syntaxhighlight>
=={{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}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def Width=180, Height=135, Color=$123456;
 
Line 1,603 ⟶ 2,619:
WriteImage;
SetVid(3); \restore display to normal text mode
]</langsyntaxhighlight>
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">clear screen
 
wid = 150 : hei = 200
open window wid, hei
window origin "cc"
color 255, 0, 0
fill circle 0, 0, 50
color 0, 255, 0
fill circle 0, 0, 35
color 0, 0, 255
fill circle 0, 0, 20
window origin "lt"
 
header$ = "P6\n" + str$(wid) + " " + str$(hei) + "\n255\n"
 
fn = open("exmaple.PPM", "wb")
 
print #fn header$
 
for x = 0 to hei - 1
for y = 0 to wid - 1
c$ = right$(getbit$(y, x, y, x), 6)
poke #fn, dec(left$(c$, 2))
poke #fn, dec(right$(c$, 2))
poke #fn, dec(mid$(c$, 3, 2))
next y
next x
 
poke #fn, asc("\n")
close #fn</syntaxhighlight>
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">// convert Windows BMP (bit map) image to PPM
 
// Read BMP file
Line 1,622 ⟶ 2,668:
}
 
File("foo.ppm","wb").write(ppm); // File.stdout isn't binary, let GC close file</langsyntaxhighlight>
{{out}}
<pre>
Line 1,630 ⟶ 2,676:
-rw-r--r-- 1 craigd craigd 786476 Aug 30 01:31 foo.ppm
</pre>
 
{{omit from|PARI/GP}}
14

edits