Bitmap/Write a PPM file: Difference between revisions
m
syntax highlighting fixup automation
m (→{{header|BQN}}: Trivial simplifications: +¨ to +, and combine 256| of a list) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 10:
{{trans|Python}}
<
Byte r, g, b
Line 77:
print(bitmap.writeppmp3())
File(‘tmp.ppm’, ‘w’).write_bytes(bitmap.writeppmp6())</
{{out}}
Line 93:
=={{header|Action!}}==
{{libheader|Action! Bitmap tools}}
<
PROC SaveHeader(RgbImage POINTER img
Line 184:
PrintF("Loading %S...%E%E",path3)
Load(path3)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Write_a_PPM_file.png Screenshot from Atari 8-bit computer]
Line 204:
=={{header|Ada}}==
<
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
Line 229:
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 249:
16.times(f_bytes, f, drand(255), drand(255), drand(255));
} while ((i += 16) < w);
} while ((j += 1) < h);</
=={{header|Applesoft BASIC}}==
<
110 H = 8
120 BA = 24576
Line 269:
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</
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L|45}}
<
cyan := color(0,255,255) ; r,g,b
cyanppm := Bitmap(10, 10, cyan) ; width, height, background-color
Line 304:
return 0
}
</syntaxhighlight>
=={{header|AWK}}==
<
BEGIN {
split("255,0,0,255,255,0",R,",");
Line 319:
}
close(outfile);
}</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
Height% = 200
Line 352:
col% = TINT(x%*2,y%*2)
SWAP ?^col%,?(^col%+2)
= col%</
=={{header|BQN}}==
<
4 8
255
Line 369:
image_ppm ↩ @ + ⥊ image_ppm # deshape, convert to chars (uint8_t)
bytes_ppm ← header_ppm ∾ image_ppm
"small.ppm" •file.Bytes bytes_ppm</
{{trans|C}}
<
800 800
255
"
image_ppm ← @ + ⥊ > {256|𝕨‿𝕩‿(𝕨×𝕩)}⌜˜ ↕800
"first_bqn.ppm" •file.Bytes header_ppm ∾ image_ppm</
=={{header|C}}==
This is one file program which writes one color in each step :
<
#include <stdio.h>
Line 403:
(void) fclose(fp);
return EXIT_SUCCESS;
}</
This program writes whole array in one step :
<
int main()
Line 443:
printf("OK - file %s saved\n", filename);
return 0;
}</
Line 452:
Interface:
<
Implementation:
<
void output_ppm(FILE *fd, image img)
Line 465:
(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 493:
writerB.Close();
}
}</
=={{header|C++}}==
{{trans|C}}
<
#include <cstdio>
Line 514:
return EXIT_SUCCESS;
}</
=={{header|Common Lisp}}==
<
(with-open-file (stream filename
:element-type '(unsigned-byte 8)
Line 545:
(write-byte green stream)
(write-byte blue stream)))))))
filename)</
=={{header|D}}==
Line 552:
=={{header|Delphi}}==
Helper class to enable bitmap export to ppm.
<
program btm2ppm;
Line 604:
end;
end.
</syntaxhighlight>
=={{header|E}}==
Line 612:
=={{header|Erlang}}==
Writes a bitmap to PPM file. Uses 24 bit color depth (color max value 255).
<
-module(ppm).
Line 659:
integer_to_list(Number).
</syntaxhighlight>
=={{header|Euphoria}}==
{{trans|C}}
<
constant fn = open("first.ppm","wb") -- b - binary mode
sequence color
Line 677:
end for
end for
close(fn)</
Procedure writing [[Bitmap#Euphoria|bitmap]] data storage:
<
integer fn,dimx,dimy
dimy = length(image[1])
Line 693:
end for
close(fn)
end procedure</
=={{header|FBSL}}==
Line 700:
'''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 722:
WEND
FILEPUT(FILEOPEN(ppmout, BINARY_NEW), ppmdata): FILECLOSE(FILEOPEN)</
=={{header|Forth}}==
<
s" P6" fid write-line throw
bmp bdim swap
Line 738:
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 768:
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 821:
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 878:
}
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 898:
fmt.Println(err)
}
}</
=={{header|Haskell}}==
<
module Bitmap.Netpbm(readNetpbm, writeNetpbm) where
Line 950:
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 960:
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}}==
Line 973:
See [[Basic_bitmap_storage#Java|Basic Bitmap Storage]] for the <tt>BasicBitmapStorage</tt> class.
<
import java.io.File;
import java.io.FileOutputStream;
Line 1,001:
}
}
}</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
h, w = 50, 70
Line 1,016:
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 1,071:
}
}
}</
=={{header|Lua}}==
===Original===
<
-- helper function, simulates PHP's array_fill function
Line 1,183:
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 1,198:
fp:close()
return true
end</
Example usage:
<
bitmap:clear({255,255,255})
for y = 1, 5 do
Line 1,209:
end
end
bitmap:savePPM("lua3x5.ppm")</
=={{header|LiveCode}}==
LiveCode has built in support for importing and exporting PBM, JPEG, GIF, BMP or PNG graphics formats
<
export image "test" to file "~/Test.PPM" as paint -- paint format is one of PBM, PGM, or PPM
</syntaxhighlight>
Line 1,222:
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===
<
Module Checkit {
Function Bitmap (x as long, y as long) {
Line 1,335:
Checkit
</syntaxhighlight>
{{out}}
Line 1,356:
===P6 type===
<
Module PPMbinaryP6 {
If Version<9.4 then 1000
Line 1,535:
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,552:
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,562:
PROCEDURE Create(imgfile: Pathname.T; img: Bitmap.T);
END PPM.</
<
IMPORT Bitmap, Wr, FileWr, Pathname;
Line 1,592:
BEGIN
END PPM.</
=={{Header|Nim}}==
<
import streams
Line 1,630:
for col in 0..<image.w:
image[col, row] = color(0, 0, 255)
image.writePPM("output.ppm")</
=={{Header|OCaml}}==
<
let width = Bigarray.Array2.dim1 r_channel
and height = Bigarray.Array2.dim2 r_channel in
Line 1,647:
output_char oc '\n';
flush oc;
;;</
=={{header|Oz}}==
As a function in the module <code>BitmapIO.oz</code>:
<
import
Bitmap
Line 1,689:
end
end
end</
=={{header|Perl}}==
{{libheader|Imager}}
<
$image = Imager->new(xsize => 200, ysize => 200);
Line 1,700:
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]]. The results may be verified with demo\rosetta\viewppm.exw
<
constant dimx = 512, dimy = 512
constant fn = open("first.ppm","wb") -- b - binary mode
Line 1,717:
end for
end for
close(fn)</
The following more general purpose routine is used in several other examples (via include ppm.e):
<
integer fn = open(filename,"wb"),
dimx = length(image),
Line 1,733:
end for
close(fn)
end procedure</
=={{header|PHP}}==
Writes a P6 binary file
<
public $data;
public $w;
Line 1,788:
$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,845:
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,866:
maplist(maplist(maplist(put_byte(Output))),Pixels),
close(Output).
</syntaxhighlight>
usage:
<
:- use_module(bitmap).
:- use_module(bitmapIO).
Line 1,879:
write_ppm_p6('AlmostAllBlack.ppm',AlmostAllBlack).
</syntaxhighlight>
=={{header|PureBasic}}==
<
; Author Roger Rösch (Nickname Macros)
IDFiIe = CreateFile(#PB_Any, file$)
Line 1,915:
CloseFile(IDFiIe)
EndIf
EndProcedure</
=={{header|Python}}==
Line 1,921:
Extending the example given [[Basic_bitmap_storage#Alternative_version|here]]
<
# String masquerading as ppm file (version P3)
import io
Line 1,984:
bitmap.writeppm(ppmfileout)
ppmfileout.close()
</syntaxhighlight>
=={{header|R}}==
{{libheader|pixmap}}
<syntaxhighlight lang=r>
# View the existing code in the library
library(pixmap)
Line 1,995:
#Usage
write.pnm(theimage, filename)
</syntaxhighlight>
=={{header|Racket}}==
<
;P3
(define (bitmap->ppm bitmap output-port)
Line 2,040:
;or any other output port
</syntaxhighlight>
=={{header|Raku}}==
Line 2,046:
{{works with|Rakudo|2016-01}}
<syntaxhighlight lang=raku
class Bitmap {
has UInt ($.width, $.height);
Line 2,075:
}
$*OUT.write: $b.P6;</
Converted to a png. (ppm files not locally supported)
Line 2,081:
=={{header|REXX}}==
<
green = 00ff00 /*define a pixel with the color green. */
parse arg oFN width height color . /*obtain optional arguments from the CL*/
Line 2,101:
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 2,125:
end
alias_method :write, :save
end</
=={{header|Rust}}==
<
use std::io::Write;
use std::fs::File;
Line 2,196:
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 2,212:
}
}
}</
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<
(define (write-image image)
(define (write-row row)
Line 2,237:
(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 2,269:
close(ppmFile);
end if;
end func;</
=={{header|Sidef}}==
{{trans|Raku}}
<
subset UInt < Int {|n| n >= 0 }
subset UInt8 < Int {|n| n ~~ ^256 }
Line 2,315:
}
%f"palette.ppm".write(b.p6, :raw)</
=={{header|Stata}}==
Line 2,321:
P3 format only, with Mata.
<
void writeppm(name, r, g, b) {
n = rows(r)
Line 2,340:
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,363:
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}}==
Line 2,370:
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,403:
=={{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,419:
Next
My.Computer.FileSystem.WriteAllBytes(filepath, bytes, False)
End Sub</
=={{header|Wren}}==
{{libheader|DOME}}
This takes a while to run as DOME needs to build up the file contents in string form before saving them to a PPM file. It is not currently possible to write files a line at a time.
<
import "dome" for Window, Process
import "io" for FileSystem
Line 2,469:
}
var Game = Bitmap.new("Bitmap - write to PPM file", 320, 320)</
=={{header|XPL0}}==
<
def Width=180, Height=135, Color=$123456;
Line 2,509:
WriteImage;
SetVid(3); \restore display to normal text mode
]</
=={{header|Yabasic}}==
<
wid = 150 : hei = 200
Line 2,541:
poke #fn, asc("\n")
close #fn</
=={{header|zkl}}==
<
// Read BMP file
Line 2,560:
}
File("foo.ppm","wb").write(ppm); // File.stdout isn't binary, let GC close file</
{{out}}
<pre>
|