Bitmap: Difference between revisions

36,730 bytes added ,  6 months ago
m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
(34 intermediate revisions by 14 users not shown)
Line 1:
{{task|Raster graphics operations}}
{{omit from|AWK}}
{{omit from|PARI/GP}}
 
Show a basic storage type to handle a simple RGB raster graphics image,
Line 19 ⟶ 17:
is available in the article [[write ppm file]].''
<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 = [[background] * width] * height
 
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 chardisplay()
V txt = .map.map(row -> row.map(bit -> (I bit == @@.background {‘ ’} E ‘@’)).join(‘’))
txt = txt.map(row -> ‘|’row‘|’)
txt.insert(0, ‘+’(‘-’ * .width)‘+’)
txt.append(‘+’(‘-’ * .width)‘+’)
print(reversed(txt).join("\n"))
 
F set(x, y, colour = black)
.map[y][x] = colour
 
F get(x, y)
R .map[y][x]
 
V bitmap = Bitmap(20, 10)
bitmap.fillrect(4, 5, 6, 3)
assert(bitmap.get(5, 5) == black)
assert(bitmap.get(0, 1) == white)
bitmap.set(0, 1, black)
assert(bitmap.get(0, 1) == black)
bitmap.chardisplay()</syntaxhighlight>
 
{{out}}
<pre>
+--------------------+
| |
| |
| @@@@@@ |
| @@@@@@ |
| @@@@@@ |
| |
| |
| |
|@ |
| |
+--------------------+
</pre>
=={{header|Action!}}==
Part of the solution can be found in [http://www.rosettacode.org/wiki/Category:Action!_Bitmap_tools#RGBIMAGE.ACT RGBIMAGE.ACT]
{{libheader|Action! Bitmap tools}}
<syntaxhighlight lang="action!">INCLUDE "H6:RGBIMAGE.ACT" ;from task Bitmap
 
RGB black,yellow,violet,blue
 
PROC DrawImage(RgbImage POINTER img BYTE x,y)
RGB c
BYTE i,j
 
FOR j=0 TO img.h-1
DO
FOR i=0 TO img.w-1
DO
GetRgbPixel(img,i,j,c)
IF RgbEqual(c,yellow) THEN
Color=1
ELSEIF RgbEqual(c,violet) THEN
Color=2
ELSEIF RgbEqual(c,blue) THEN
Color=3
ELSE
Color=0
FI
Plot(x+i,y+j)
OD
OD
RETURN
 
PROC Main()
RgbImage img
BYTE CH=$02FC,width=[80],height=[60]
BYTE ARRAY ptr(14400)
BYTE i,x,y,c
 
Graphics(7+16)
SetColor(0,13,12) ;yellow
SetColor(1,4,10) ;violet
SetColor(2,8,6) ;blue
SetColor(4,0,0) ;black
 
RgbBlack(black)
RgbYellow(yellow)
RgbViolet(violet)
RgbBlue(blue)
 
InitRgbImage(img,width,height,ptr)
FillRgbImage(img,blue)
 
FOR i=1 TO 1000
DO
c=Rand(3)
x=Rand(width)
y=Rand(height)
IF c=0 THEN
SetRgbPixel(img,x,y,yellow)
ELSEIF c=1 THEN
SetRgbPixel(img,x,y,violet)
ELSE
SetRgbPixel(img,x,y,black)
FI
OD
 
DrawImage(img,(160-width)/2,(96-height)/2)
 
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bitmap.png Screenshot from Atari 8-bit computer]
=={{header|ActionScript}}==
ActionScript 3 has a [http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html BitmapData class] (in the <code>flash.display</code> package) which can be used for storage and handling of bitmap images.
To display these images, the [http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/Bitmap.html Bitmap] class can be used.
 
<syntaxhighlight lang="actionscript3">
<lang ActionScript3>
// To import the BitmapData class:
import flash.display.BitmapData;
Line 47 ⟶ 186:
// Fill the bitmap with a given colour (as 0xAARRGGBB) after construction
bitmap.fillRect(bitmap.rect, 0xFF44FF44);
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
The package interface:
<langsyntaxhighlight lang="ada">package Bitmap_Store is
type Luminance is mod 2**8;
type Pixel is record
Line 67 ⟶ 205:
X, Y : Positive;
end record;
end Bitmap_Store;</langsyntaxhighlight>
The implementation of:
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
package body Bitmap_Store is
Line 88 ⟶ 226:
end Print;
 
end Bitmap_Store;</langsyntaxhighlight>
This can be used like:
<langsyntaxhighlight lang="ada">use Bitmap_Store; with Bitmap_Store;
...
X : Image (1..64, 1..64);
Line 96 ⟶ 234:
Fill (X, (255, 255, 255));
X (1, 2) := (R => 255, others => 0);
X (3, 4) := X (1, 2);</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
{{trans|ada}}
Line 107 ⟶ 244:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.6 algol68g-2.6].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: prelude/Bitmap.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
MODE PIXEL = STRUCT(#SHORT# BITS red,green,blue);
Line 154 ⟶ 291:
OP INIT = (REF IMAGE image)REF IMAGE: (init OF (CLASSOF image))(image);
 
SKIP</langsyntaxhighlight>'''File: test/Bitmap.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 164 ⟶ 301:
(fill OF class image) (x, white OF class image);
(print OF class image) (x)
)</langsyntaxhighlight>
{{out}} (A 16x16 white block)
<pre>
Line 184 ⟶ 321:
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
</pre>
=={{header|Applesoft BASIC}}==
The Bitmap Address (BA) of the image is 24576 in order to maximize available space for the image without clobbering hi-res graphics memory. Just enough room is allocated for a P6 header. The Bitmap Beginning (BB) is just after the header.
 
HIMEM is set to 8192 which is just below hi-res graphics memory. It isn't necessary to protect hi-res graphics memory, but it doesn't hurt. Larger images can be allocated by using a lower Bitmap Address.
<syntaxhighlight lang="gwbasic"> 100 W = 8
110 H = 8
120 BB = 24576 + LEN ( STR$ (W) + STR$ (H)) + 9: REM P6 HEADER
130 HIMEM: 8192
140 R = 255
150 G = 255
160 B = 0
170 C = R + G * 256 + B * 65536
180 GOSUB 600FILL
190 X = 4
200 Y = 5
210 R = 127
220 G = 127
230 B = 255
240 C = R + G * 256 + B * 65536
250 GOSUB 500"SET PIXEL"
260 X = 3
270 Y = 2
280 GOSUB 400"GET PIXEL"
290 PRINT "COLOR="C" RED="R" GREEN="G" BLUE="B;
300 END
400 A = BB + X * 3 + Y * W * 3
410 R = PEEK (A)
420 G = PEEK (A + 1)
430 B = PEEK (A + 2)
440 C = R + G * 256 + B * 65536
450 RETURN
500 R = C - INT (C / 256) * 256
510 B = INT (C / 65536)
520 G = INT (C / 256) - B * 256
530 A = BB + X * 3 + Y * W * 3
540 POKE A,R
550 POKE A + 1,G
560 POKE A + 2,B
570 RETURN
600 FOR Y = 0 TO H - 1
610 FOR X = 0 TO W - 1
620 GOSUB 500"SET PIXEL"
630 NEXT X,Y
640 RETURN</syntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|Game Boy Advance}}
The Game Boy Advance's video memory is located at address 0x06000000, and is 240 pixels by 160 pixels, with 16 bits defining the color of each pixel. This is a linear array of memory; storing 0xFFFF at 0x06000000 for example will immediately make the top-left pixel of the screen turn white. The following routines are intended for the bitmap screen modes, and have only been tested in screen mode 3. There is no need to allocate this video memory as it is always available thanks to the hardware.
 
<syntaxhighlight lang="arm assembly">
Bitmap_FloodFill:
;input:
;r0 = color to fill screen with (15-bit color)
STMFD sp!,{r0-r12,lr}
MOV R2,#160
MOV R4,#0x06000000
outerloop_floodfill:
MOV R1,#240 ;restore inner loop counter
innerloop_floodfill:
strH r0,[r4]
add r4,r4,#2 ;next pixel
subs r1,r1,#1 ;decrement loop counter
bne innerloop_floodfill
subs r2,r2,#1
bne outerloop_floodfill
LDMFD sp!,{r0-r12,pc}
Bitmap_Locate:
;given x and y coordinates, offsets vram addr to that pixel on screen.
;input:
;r0 = x
;r1 = y
;output: r2 = vram area
STMFD sp!,{r4-r12,lr}
mov r2,#0x06000000 ;vram base
 
mov r4,#240*2 ;240 pixels across, 2 bytes per pixel
mul r1,r4,r1
add r2,r2,r1 ;add y*480
add r2,r2,r0,lsl #1 ;add x*2
LDMFD sp!,{r4-r12,pc}
Bitmap_StorePixel:
;input: r3 = color
;r0 = x
;r1 = y
bl Bitmap_Locate
strH r3,[r2] ;store the pixel color in video memory
bx lr
Bitmap_GetPixel:
;retrieves the color of the pixel at [r2] and stores its color value in r3.
;r0 = x
;r1 = y
;output in r3
bl Bitmap_Locate
ldrH r3,[r2]
bx lr</syntaxhighlight>
=={{header|ATS}}==
 
Because this code will be used in other tasks, I have separated it into "static" and "dynamic" source files. The former is the equivalent of an "interface" file in some other languages, and the latter is equivalent of an "implementation" file. I included some test code that gets compiled if you put the correct option on the compiler command line.
 
===The ATS static file===
This file should be called <code>bitmap_task.sats</code>.
<syntaxhighlight lang="ats">
#define ATS_PACKNAME "Rosetta_Code.bitmap_task"
 
(*------------------------------------------------------------------*)
 
(* I am going to do this at the most primitive level. So here is the
"abstractified" type, or really a whole set of different types:
w-by-h pixmap of values of type a, with pixel storage at address
p. The type is linear (‘use it once and only once’). We will make
pixmap a boxed type, so its size will be equal to that of a
pointer. (This is actually a general 2-dimensional array type!
But let us ignore that.) *)
absvtype pixmap (a : t@ype, w : int, h : int, p : addr) = ptr
 
(* A shorthand for a pixmap with its pixel storage at "some"
address. *)
vtypedef pixmap (a : t@ype, w : int, h : int) =
[p : addr] pixmap (a, w, h, p)
 
(* A shorthand for a pixmap with "some" width and height, and with its
pixel storage at "some" address. *)
vtypedef pixmap (a : t@ype) = [w, h : int] pixmap (a, w, h)
 
(* A shorthand for a pixmap with "some" POSITIVE width and POSITIVE
height, and with its pixel storage at "some" address. *)
vtypedef pixmap1 (a : t@ype) = [w, h : pos] pixmap (a, w, h)
 
(*------------------------------------------------------------------*)
(* Here are definitions for a small set of operations, including the
ones requested in the task document.
 
But note that, in ATS, we are careful about uninitialized data. It
is POSSIBLE to create an uninitialized pixmap, but NOT possible to
set or get individual pixels, if the pixmap is not already fully
initialized by some other means (such as "fill" or "load"). *)
 
fn {}
pixmap_width :
{a : t@ype}
{w, h : int}
(!pixmap (a, w, h)) -<> size_t w
 
fn {}
pixmap_height :
{a : t@ype}
{w, h : int}
(!pixmap (a, w, h)) -<> size_t h
 
fn {a : t@ype}
pixmap_make_array :
(* Make a new pixmap from an existing array. The array may be
anywhere (for instance, a stack frame or the heap), and need not
be initialized. *)
{w, h : int} {p : addr}
(array_v (a, p, w * h) | size_t w, size_t h, ptr p) ->
pixmap (a, w, h, p)
 
fn {a : t@ype}
pixmap_unmake :
(* Essentially the reverse of pixmap_make_array. Temporarily treat a
pixmap as an array. The array will be organized as rows from left
to right, with the rows themselves going from top to bottom. Thus
an index would be i = x + (y * w). *)
{w, h : int} {p : addr}
pixmap (a, w, h, p) ->
@(array_v (a, p, w * h) | size_t w, size_t h, ptr p)
 
prfn
pixmap_prove_index_bounds :
(* A proof that i = x + (y * w) is within bounds of the array
returned by pixmap_unmake. *)
{w, h : int}
{x, y : nat | x < w; y < h}
() -<prf>
[0 <= x + (y * w);
x + (y * w) < w * h]
void
 
fn {a : t@ype}
pixmap_make_uninitized :
(* Make a new uninitialized pixmap, with the pixels stored in the
heap. *)
{w, h : int}
(size_t w, size_t h) ->
[p : addr | null < p] @(mfree_gc_v p | pixmap (a?, w, h, p))
 
fn {a : t@ype}
pixmap_make_elt :
(* Make a new pixmap, initialized with a given element, with the
pixels stored in the heap. *)
{w, h : int}
(size_t w, size_t h, a) ->
[p : addr | null < p] @(mfree_gc_v p | pixmap (a, w, h, p))
 
fn {}
pixmap_free_storage_return :
(* Free a pixmap, returning the storage array to the user. *)
{a : t@ype}
{w, h : int} {p : addr}
pixmap (a, w, h, p) -> @(array_v (a, p, w * h) | ptr p)
 
fn {}
pixmap_free_storage_free :
(* If a pixmap's pixels were allocated in the heap, then free its
storage. *)
{a : t@ype}
{w, h : int} {p : addr}
(mfree_gc_v p | pixmap (a, w, h, p)) -> void
 
fn {a : t@ype}
pixmap_fill_elt :
(* Fill a pixmap with the given element. (Technically speaking, the
value of the first argument is consumed, and replaced by a new
value. Its type before and after is linear.) *)
{w, h : int} {p : addr}
(* The question mark means that the pixmap elements can start out
uninitialized. *)
(!pixmap (a?, w, h, p) >> pixmap (a, w, h, p), a) -> void
 
fn {a : t@ype}
{tk : tkind}
pixmap_set_at_guint :
(* Set a pixel at unsigned integer coordinates. You can do this only
on a pixmap that has been initialized. (It would be prohibitively
tedious to safely work with randomly located pixels, if the array
were not already fully initialized.) *)
{w, h : int}
{x, y : int | x < w; y < h}
(!pixmap (a, w, h), g1uint (tk, x), g1uint (tk, y), a) -> void
 
fn {a : t@ype}
{tk : tkind}
pixmap_set_at_gint :
(* Set a pixel, but with signed integer coordinates. *)
{w, h : int}
{x, y : nat | x < w; y < h}
(!pixmap (a, w, h), g1int (tk, x), g1int (tk, y), a) -> void
 
fn {a : t@ype} {tk : tkind}
pixmap_get_at_guint :
(* Get a pixel at unsigned integer coordinates. You can do this only
on a pixmap that has been initialized. *)
{w, h : int}
{x, y : int | x < w; y < h}
(!pixmap (a, w, h), g1uint (tk, x), g1uint (tk, y)) -> a
 
fn {a : t@ype} {tk : tkind}
pixmap_get_at_gint :
(* Get a pixel, but with signed integer coordinates. *)
{w, h : int}
{x, y : nat | x < w; y < h}
(!pixmap (a, w, h), g1int (tk, x), g1int (tk, y)) -> a
 
fn {a : t@ype}
pixmap_dump :
(* Dump the contents of a pixmap to an output stream, row by row as
in a PPM. You must implement the pixmap$pixels_dump template
function. (We are anticipating the task to write a PPM file, and
wish to do it in a nice way. I am likely to end up actually using
this code, after all.) *)
{w, h : int}
(* I return a success-or-failure value, to avoid committing to using
an exception here. There are circumstances in which exceptions are
not the best approach. *)
(FILEref, !pixmap (a, w, h)) -> bool (* success *)
 
fn {a : t@ype}
pixmap$pixels_dump :
(* A function that the writes n pixels to an output stream. (It
could be one pixel, it could be the entire image. From the user's
standpoint, it makes no difference. It is an implementation
detail HOW the function is called by pixmap_dump.) *)
{n : int}
(FILEref, &array (a, n), size_t n) -> bool (* success *)
 
fn {a : t@ype}
pixmap_load :
(* Load the contents of a pixmap from an input stream, row by row as
in a PPM. You must implement the pixmap$pixels_load template
function. A value of type a has to be given, to initialize the
array with if the loading fails. *)
{w, h : int} {p : addr}
(FILEref, !pixmap (a?, w, h, p) >> pixmap (a, w, h, p), a) ->
bool (* success *)
 
fn {a : t@ype}
pixmap$pixels_load :
(* A function that the reads n pixels from an input stream. (It
could be one pixel, it could be the entire image. From the user's
standpoint, it makes no difference. It is an implementation
detail HOW the function is called by pixmap_load.) *)
{n : int}
(FILEref, &array (a?, n) >> array (a, n), size_t n, a) ->
bool (* success *)
 
overload pixmap_make with pixmap_make_array
overload pixmap_make with pixmap_make_uninitized
overload pixmap_make with pixmap_make_elt
 
overload pixmap_free with pixmap_free_storage_return
overload pixmap_free with pixmap_free_storage_free
overload free with pixmap_free_storage_free
 
overload fill with pixmap_fill_elt
 
overload pixmap_set_at with pixmap_set_at_guint
overload pixmap_set_at with pixmap_set_at_gint
overload [] with pixmap_set_at
 
overload pixmap_get_at with pixmap_get_at_guint
overload pixmap_get_at with pixmap_get_at_gint
overload [] with pixmap_get_at
 
overload dump with pixmap_dump
overload load with pixmap_load
 
overload width with pixmap_width
overload height with pixmap_height
 
(*------------------------------------------------------------------*)
(* Here is a type for 24-bit RGB data. An RGB pixmap type thus can be
written as "pixmap (rgb24, w, h, p)".
There are, though you cannot see it here (they are in the dynamic
file), default implementations of pixmap$pixels_dump<rgb24> and
pixmap$pixels_load<rgb24>. These implementations are for dumping
raw data in PPM format. *)
 
(* It is an abstract type, the size of a triple of uint8. (It is, in
fact, a triple of uint8, but we hide this fact, so the template
system will not confuse the type with other triples of uint8. It is
a subtle matter. *)
abst@ype rgb24 = @(uint8, uint8, uint8)
 
fn {tk : tkind}
rgb24_make_uint_uint_uint :
(g0uint tk, g0uint tk, g0uint tk) -<> rgb24
 
fn {tk : tkind}
rgb24_make_int_int_int :
(g0int tk, g0int tk, g0int tk) -<> rgb24
 
fn {}
rgb24_make_tuple : @(uint8, uint8, uint8) -<> rgb24
 
fn {}
rgb24_values : rgb24 -<> @(uint8, uint8, uint8)
 
overload rgb24_make with rgb24_make_uint_uint_uint
overload rgb24_make with rgb24_make_int_int_int
overload rgb24_make with rgb24_make_tuple
 
(*------------------------------------------------------------------*)
</syntaxhighlight>
 
===The ATS dynamic file===
This file should be called <code>bitmap_task.dats</code>.
<syntaxhighlight lang="ats">
(*------------------------------------------------------------------*)
 
#define ATS_DYNLOADFLAG 0
#define ATS_PACKNAME "Rosetta_Code.bitmap_task"
 
#include "share/atspre_staload.hats"
 
staload "bitmap_task.sats"
 
(*------------------------------------------------------------------*)
 
(* The actual type, normally not seen by the user, is a boxed
record. *)
datavtype _pixmap (a : t@ype, w : int, h : int, p : addr) =
| _pixmap of
@{
pf = array_v (a, p, w * h) |
w = size_t w,
h = size_t h,
p = ptr p
}
 
(* Here is one of the ways to tie an abstract type to its
implementation: *)
assume pixmap (a, w, h, p) = _pixmap (a, w, h, p)
(* Another way is to use casts. *)
 
(*------------------------------------------------------------------*)
 
implement {}
pixmap_width pix =
case+ pix of _pixmap record => record.w
 
implement {}
pixmap_height pix =
case+ pix of _pixmap record => record.h
 
implement {a}
pixmap_make_array (pf | w, h, p) =
_pixmap @{pf = pf | w = w, h = h, p = p}
 
implement {a}
pixmap_unmake pix =
case+ pix of
| ~ _pixmap @{pf = pf | w = w, h = h, p = p} => @(pf | w, h, p)
 
primplement
pixmap_prove_index_bounds {w, h} {x, y} () =
let
prval () = mul_gte_gte_gte {y, w} ()
prval () = mul_gte_gte_gte {h - (y + 1), w} ()
in
end
 
implement {a}
pixmap_make_uninitized {w, h} (w, h) =
let
prval () = lemma_g1uint_param w (* Proves w >= 0. *)
prval () = lemma_g1uint_param h (* Proves h >= 0. *)
prval () = mul_gte_gte_gte {w, h} () (* Proves w*h >= 0. *)
 
val @(pf, pfgc | p) = array_ptr_alloc<a> (w * h)
val pix = pixmap_make<a?> (pf | w, h, p)
in
@(pfgc | pix)
end
 
implement {a}
pixmap_make_elt (w, h, elt) =
let
val @(pfgc | pix) = pixmap_make<a> (w, h)
in
fill<a> (pix, elt);
@(pfgc | pix)
end
 
implement {}
pixmap_free_storage_return pix =
case+ pix of
| ~ _pixmap record => @(record.pf | record.p)
 
implement {}
pixmap_free_storage_free (pfgc | pix) =
let
val @(pf | p) = pixmap_free pix
in
array_ptr_free (pf, pfgc | p)
end
 
implement {a}
pixmap_fill_elt {w, h} {p} (pix, elt) =
case+ pix of
| @ _pixmap record =>
let
prval () = lemma_g1uint_param (record.w)
prval () = lemma_g1uint_param (record.h)
prval () = mul_gte_gte_gte {w, h} ()
stadef n = w * h
val n : size_t n = record.w * record.h
and p : ptr p = record.p
 
fun
loop {i : nat | i <= n}
.<n - i>.
(pf_lft : array_v (a, p, i),
pf_rgt : array_v (a?, p + (i * sizeof a), n - i) |
i : size_t i)
: @(array_v (a, p, n) | ) =
if i = n then
let
prval () = array_v_unnil pf_rgt
in
@(pf_lft | )
end
else
let
prval @(pf_elt, pf_rgt) = array_v_uncons pf_rgt
val () = ptr_set<a> (pf_elt | ptr_add<a> (p, i), elt)
prval pf_lft = array_v_extend (pf_lft, pf_elt)
in
loop (pf_lft, pf_rgt | succ i)
end
 
val @(pf | ) = loop (array_v_nil (), record.pf | i2sz 0)
prval () = record.pf := pf
prval () = fold@ pix
in
end
 
implement {a} {tk}
pixmap_set_at_guint {w, h} {x, y} (pix, x, y, elt) =
case+ pix of
| @ _pixmap record =>
let
prval () = lemma_g1uint_param x
prval () = lemma_g1uint_param y
 
stadef n = w * h
stadef i = x + (y * w)
 
prval () = pixmap_prove_index_bounds {w, h} {x, y} ()
prval () = prop_verify {0 <= i && i < n} ()
 
(* I purposely store the data in an order such that you can
write something such as a PPM without looping separately
over x and y. Also, even if you did do an outer loop over y
and an inner loop over x, you would get the advantage of
data locality. *)
val i : size_t i = g1u2u x + (g1u2u y * record.w)
macdef pixels = !(record.p)
val () = pixels[i] := elt
 
prval () = fold@ pix
in
end
 
implement {a} {tk}
pixmap_set_at_gint (pix, x, y, elt) =
pixmap_set_at_guint<a><sizeknd> (pix, g1i2u x, g1i2u y, elt)
 
implement {a} {tk}
pixmap_get_at_guint {w, h} {x, y} (pix, x, y) =
case+ pix of
| @ _pixmap record =>
let
prval () = lemma_g1uint_param x
prval () = lemma_g1uint_param y
 
stadef n = w * h
stadef i = x + (y * w)
 
prval () = pixmap_prove_index_bounds {w, h} {x, y} ()
prval () = prop_verify {0 <= i && i < n} ()
 
val i : size_t i = g1u2u x + (g1u2u y * record.w)
macdef pixels = !(record.p)
val elt = pixels[i]
 
prval () = fold@ pix
in
elt
end
 
implement {a} {tk}
pixmap_get_at_gint (pix, x, y) =
pixmap_get_at_guint<a><sizeknd> (pix, g1i2u x, g1i2u y)
 
implement {a}
pixmap_dump (outf, pix) =
case+ pix of
| @ _pixmap record =>
let
macdef pixels = !(record.p)
val n = record.w * record.h
val success = pixmap$pixels_dump<a> (outf, pixels, n)
prval () = fold@ pix
in
success
end
 
implement {a}
pixmap_load (inpf, pix, elt) =
case+ pix of
| @ _pixmap record =>
let
macdef pixels = !(record.p)
val n = record.w * record.h
val success = pixmap$pixels_load<a> (inpf, pixels, n, elt)
prval () = fold@ pix
in
success
end
 
(*------------------------------------------------------------------*)
 
typedef FILEstar = $extype"FILE *"
extern castfn FILEref2star : FILEref -<> FILEstar
 
implement
pixmap$pixels_dump<rgb24> (outf, pixels, n) =
let
val num_written =
$extfcall (size_t, "fwrite", addr@ pixels, sizeof<rgb24>, n,
FILEref2star outf)
in
num_written = n
end
 
implement
pixmap$pixels_load<rgb24> (inpf, pixels, n, elt) =
let
prval [n : int] EQINT () = eqint_make_guint n
val num_read =
$extfcall (size_t, "fread", addr@ pixels, sizeof<rgb24>, n,
FILEref2star inpf)
in
if num_read = n then
let
prval () = $UNSAFE.castvwtp2void{@[rgb24][n]} pixels
in
true
end
else
begin
array_initize_elt<rgb24> (pixels, n, elt);
false
end
end
 
(*------------------------------------------------------------------*)
 
assume rgb24 = @(uint8, uint8, uint8)
 
implement {tk}
rgb24_make_uint_uint_uint (r, g, b) =
let
(* The prelude tends to miss implementations for type conversions
to uint8, so let us at least implement conversion from uint to
uint8. (I do not wish to use a general unsafe cast, because
that sort of code has caused me bugs before. C does not always
know how to do a type conversion correctly.) The ats2-xprelude
package has a much more complete set of implementations
(generated en masse by m4 macros), but for this task I am
avoiding such dependencies. *)
implement
g0uint2uint<uintknd,uint8knd> i =
let
extern castfn g0uint2uint_uint_uint8 : uint -<> uint8
in
g0uint2uint_uint_uint8 i
end
in
rgb24_make_tuple @(g0u2u r, g0u2u g, g0u2u b)
end
 
implement {tk}
rgb24_make_int_int_int (r, g, b) =
let
(* See the comment in rgb24_make_uint_uint_uint. *)
implement
g0int2uint<intknd,uint8knd> i =
let
extern castfn g0int2uint_int_uint8 : int -<> uint8
in
g0int2uint_int_uint8 i
end
in
rgb24_make @(g0i2u r, g0i2u g, g0i2u b)
end
 
implement {}
rgb24_make_tuple tup = tup
 
implement {}
rgb24_values rgb = rgb
 
(*------------------------------------------------------------------*)
 
#ifdef BITMAP_TASK_TEST #then
 
%{^
#include <limits.h>
%}
 
fn
test_sizeof_rgb24 () : void =
(* We want to be sure rgb24 takes up exactly 24 bits. Our dump and
load implementations depend on that. (If it prove not the case on
some platform, one can write, for that unanticipated platform,
special implementations of dump and load.) *)
let
val- true = sizeof<rgb24> = i2sz 3
val- true = sizeof<rgb24> * $extval (size_t, "CHAR_BIT") = i2sz 24
in
end
 
fn
test_pixel_load_copy_dump () : void =
(* Test loading, copying, and dumping of raw 24-bit RGB data from
SIPI image "Peppers", 4.2.07.tiff:
https://sipi.usc.edu/database/database.php?volume=misc&image=13#top
I have the data stored as "4.2.07.raw". *)
let
val failure_color = rgb24_make (0xFF, 0x00, 0x00)
 
val @(pfgc1 | pix1) = pixmap_make<rgb24> (i2sz 512, i2sz 512)
val inpf = fileref_open_exn ("4.2.07.raw", file_mode_r)
val success = load<rgb24> (inpf, pix1, failure_color)
val () = fileref_close inpf
val- true = success
 
val @(pfgc2 | pix2) = pixmap_make<rgb24> (i2sz 512, i2sz 512,
failure_color)
fun
copy_pixels {x, y : nat | x <= 512; y <= 512}
.<512 - x, 512 - y>.
(pix1 : !pixmap (rgb24, 512, 512),
pix2 : !pixmap (rgb24, 512, 512),
x : int x,
y : int y) : void =
if x = 512 then
()
else if y = 512 then
copy_pixels (pix1, pix2, succ x, 0)
else
begin
pix2[x, y] := pix1[x, y];
copy_pixels (pix1, pix2, x, succ y)
end
val () = copy_pixels (pix1, pix2, 0, 0)
 
val outf = fileref_open_exn ("4.2.07.raw.dumped", file_mode_w)
val success = dump<rgb24> (outf, pix2)
val () = fileref_close outf
val- true = success
 
val status = $extfcall (int, "system",
"cmp 4.2.07.raw 4.2.07.raw.dumped")
val- true = status = 0
in
free (pfgc1 | pix1);
free (pfgc2 | pix2)
end
 
implement
main0 () =
begin
test_sizeof_rgb24 ();
test_pixel_load_copy_dump ()
end
 
#endif
 
(*------------------------------------------------------------------*)
</syntaxhighlight>
 
A test can be run if one has a 786432-byte file and names it <code>4.2.07.raw</code>. I used the raw data from a commonly used 512x512 test image. You can compile and run the test program thus:
<pre>$ patscc -std=gnu2x -g -O2 -DATS_MEMALLOC_LIBC -DATS BITMAP_TASK_TEST bitmap_task.sats bitmap_task.dats
$ ./a.out</pre>
You should end up with a copy of the data in a file named <code>4.2.07.raw.dumped</code>.
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">test:
blue := color(0,0,255) ; rgb
cyan := color(0,255,255)
Line 279 ⟶ 1,160:
{
return clr.R << 16 | clr.G << 8 | clr.B
}</langsyntaxhighlight>
 
=={{header|Axe}}==
Line 286 ⟶ 1,167:
Two bitmaps can be masked together to create 3- and 4-color grayscale.
 
<langsyntaxhighlight lang="axe">Buff(768)→Pic1
Fill(Pic1,768,255)
Pxl-Off(45,30,Pic1)
Line 295 ⟶ 1,176:
Pause 4500
 
Disp pxl-Test(50,50,Pic1)▶Dec,i</langsyntaxhighlight>
 
=={{header|BASIC256BASIC}}==
==={{header|BASIC256}}===
[[Image:BASIC256_bitmap.png|right]]
<langsyntaxhighlight BASIC256lang="basic256">graphsize 30,30
call fill(rgb(255,0,0))
call setpixel(10,10,rgb(0,255,255))
Line 316 ⟶ 1,198:
color c
plot x,y
end subroutine</langsyntaxhighlight>
{{out}}
<pre>pixel 10,10 is 4278255615
pixel 20,20 is 4294901760</pre>
 
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
BBC BASIC expects a bitmap always to be associated with a window;
for simplicity this code uses the main output window.
<langsyntaxhighlight lang="bbcbasic"> Width% = 200
Height% = 200
Line 358 ⟶ 1,240:
col% = TINT(x%*2,y%*2)
SWAP ?^col%,?(^col%+2)
= col%</langsyntaxhighlight>
 
=={{header|C}}==
 
Line 368 ⟶ 1,249:
Start from [[Bitmap| bitmap page]]
 
<langsyntaxhighlight lang="c">#ifndef _IMGLIB_0
#define _IMGLIB_0
 
Line 408 ⟶ 1,289:
color_component b );
#define GET_PIXEL(IMG, X, Y) (IMG->buf[ ((Y) * IMG->width + (X)) ])
#endif</langsyntaxhighlight>
 
<langsyntaxhighlight lang="c">image alloc_img(unsigned int width, unsigned int height)
{
image img;
Line 467 ⟶ 1,348:
if (x < img->width && y < img->height)
put_pixel_unsafe(img, x, y, r, g, b);
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
This implementation uses a multidemensional array to store the Color structure
Line 474 ⟶ 1,354:
No exception catching for out-of-bounds errors if they occur,
but provides Height and Width properties so a program using it can avoid them.
<langsyntaxhighlight lang="csharp">public class Bitmap
{
public struct Color
Line 505 ⟶ 1,385:
_imagemap[x, y] = color;
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
 
Line 512 ⟶ 1,391:
{{libheader|boost}}
 
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <boost/gil/gil_all.hpp>
int main()
Line 531 ⟶ 1,410:
rgb8_pixel_t px = const_view(img)(11, 20);
std::cout << "the pixel at 11, 20 is " << (unsigned)px[0] << ':' << (unsigned)px[1] << ':' << (unsigned)px[2] << '\n';
}</langsyntaxhighlight>
 
See also [[Basic bitmap storage/C++]]
 
=={{header|Clojure}}==
<langsyntaxhighlight Clojurelang="clojure">(import '[java.awt Color Graphics Image]
'[java.awt.image BufferedImage])
 
Line 551 ⟶ 1,429:
 
(defn get-pixel [image x y]
(Color. (.getRGB image x y)))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defpackage #:rgb-pixel-buffer
(:use #:common-lisp)
(:export #:rgb-pixel-component #:rgb-pixel #:rgb-pixel-buffer
Line 561 ⟶ 1,438:
#:make-rgb-pixel #:make-rgb-pixel-buffer #:rgb-pixel-buffer-width
#:rgb-pixel-buffer-height #:rgb-pixel-red #:rgb-pixel-green
#:rgb-pixel-blue #:fill-rgb-pixel-buffer))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">(in-package #:rgb-pixel-buffer)
 
(deftype rgb-pixel-component ()
Line 631 ⟶ 1,508:
:for x :of-type fixnum :upfrom 0 :below width
:do (setf (rgb-pixel buffer x y) pixel)))
buffer))</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight lang="lisp">(defvar *buffer* (make-rgb-pixel-buffer 10 10))
(fill-rgb-pixel-buffer *buffer* +white+)
(setf (rgb-pixel *buffer* 0 0) +red+)
(setf (rgb-pixel *buffer* 0 9) +red+)
(setf (rgb-pixel *buffer* 9 0) +red+)
(setf (rgb-pixel *buffer* 9 9) +red+)</langsyntaxhighlight>
 
=={{header|Crystal}}==
<langsyntaxhighlight lang="ruby">
class RGBColor
getter red, green, blue
Line 680 ⟶ 1,556:
bmap = Pixmap.new(5, 5)
pp bmap
</syntaxhighlight>
</lang>
 
=={{header|D}}==
This code is a little complex because many Tasks use this module for various purposes.
<langsyntaxhighlight lang="d">module bitmap;
 
import std.stdio, std.array, std.exception, std.string, std.conv,
Line 863 ⟶ 1,738:
img.textualShow;
}
}</langsyntaxhighlight>
Compiling it with <code>version=bitmap_main</code> prints:
{{out}}
Line 877 ⟶ 1,752:
##############################</pre>
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
<lang Delphi>
program BitmapTest;
 
Line 991 ⟶ 1,866:
end;
bmp.Free;
end.</langsyntaxhighlight>
 
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
This is a pure Delphi example using standard Delphi controls and libraries that already have raster and bitmap objects and operations built in.
 
Bascially, Delphi has a powerful set of tools for manipulating graphic objects. All graphic objects including Screens, Printers, Windows or Bitmaps, have a property called a "Canvas." As a consequence, the same code can draw on the Screen, the Printer, a Window or a Bitmap. A Canvas has powerful function that allow you to draw pixels, lines, rectangles, circles, elispes, polygons and text on any graphic object. The code below demonstrates many of the function available in a canvas.
[[File:DelphiBitmaps.png|frame|none]]
<syntaxhighlight lang="Delphi">
 
procedure ShowBitmapFunctions(Image: TImage);
{Code to demonstrate some of the main features the Delphi "TCanvas" object}
var I,X,Y: integer;
var C: TColor;
begin
{Draw red rectangle with 3 pixels wide lines}
Image.Canvas.Pen.Color:=clRed;
Image.Canvas.Pen.Width:=3;
Image.Canvas.Rectangle(50,50,500,300);
{Flood fill rectangle blue}
Image.Canvas.Brush.Color:=clBlue;
Image.Canvas.FloodFill(55,55,clRed,fsBorder);
{Draw random dots on the screen}
for I:=1 to 1000 do
begin
X:=trunc((Random * 450) + 50);
Y:=trunc((Random * 250) + 50);
C:=RGB(Random(255),Random(255),Random(255));
{draw 9 pixels for each point to make dots more visible}
Image.Canvas.Pixels[X-1,Y-1]:=C;
Image.Canvas.Pixels[X ,Y-1]:=C;
Image.Canvas.Pixels[X+1,Y-1]:=C;
Image.Canvas.Pixels[X-1,Y ]:=C;
Image.Canvas.Pixels[X ,Y ]:=C;
Image.Canvas.Pixels[X+1,Y ]:=C;
Image.Canvas.Pixels[X-1,Y+1]:=C;
Image.Canvas.Pixels[X ,Y+1]:=C;
Image.Canvas.Pixels[X+1,Y+1]:=C;
end;
{Draw lime-green line from corner to cornder}
Image.Canvas.Pen.Color:=clLime;
Image.Canvas.MoveTo(50,50);
Image.Canvas.LineTo(500,300);
{Sample pixel color at 51,51}
C:=Image.Canvas.Pixels[51,51];
{Display the color value }
Image.Canvas.Brush.Color:=clAqua;
Image.Canvas.Font.Size:=25;
Image.Canvas.Font.Color:=clRed;
Image.Canvas.TextOut(5,5,IntToHex(C,8));
{Tell Delphi to update the Window}
Image.Repaint;
end;
 
</syntaxhighlight>
{{out}}
<pre>
 
Elapsed Time: 39.038 ms.
 
</pre>
 
=={{header|E}}==
 
Line 997 ⟶ 1,935:
because it is most naturally written as a method on the image object.
 
<langsyntaxhighlight lang="e">def makeFlexList := <elib:tables.makeFlexList>
def format := <import:java.lang.makeString>.format
 
Line 1,093 ⟶ 2,031:
return flexImage
}</langsyntaxhighlight>
 
Examples/tests:
 
<langsyntaxhighlight lang="e">? def i := makeImage(3, 3)
# value: [000000 000000 000000 ]
# [000000 000000 000000 ]
Line 1,125 ⟶ 2,063:
# value: 808080
 
? i.writePPM(<import:java.io.makeFileOutputStream>(<file:~/Desktop/Rosetta.ppm>))</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'plot)
(define width 600)
Line 1,161 ⟶ 2,098:
(blue-at-xy 100 200)
→ 255
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
Translation of the erlang version of the code.
 
<langsyntaxhighlight lang="elixir">
defmodule RosBitmap do
defrecord Bitmap, pixels: nil, shape: {0, 0}
Line 1,195 ⟶ 2,131:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Erlang}}==
 
Stores pixels as a 1d array and colors as binaries.
 
<langsyntaxhighlight lang="erlang">
-module(ros_bitmap).
 
Line 1,227 ⟶ 2,162:
<<R:8, G:8, B:8>> = array:get(Index, Pixels),
{rgb, R, G, B}.
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">-- Some color constants:
constant
black = #000000,
Line 1,252 ⟶ 2,186:
-- Get pixel color
atom color
color = image[400][300] -- Now color is #FF0000</langsyntaxhighlight>
?color -- Should print out 16711680
 
=={{header|F Sharp|F#}}==
FSharp can accomplish this task in several ways. This version is purely functional. The bitmap data structure does not mutate. Set pixel, for example, simply transforms the input bitmap into a new bitmap with that pixel set to the input color. If you have Framework 4.5, you can use ImmutableArray to force this immutability.
 
'''Solution:'''
<langsyntaxhighlight lang="fsharp">
//pure functional version ... changing a pixel color provides a new Bitmap
type Color = {red: byte; green: byte; blue: byte}
Line 1,284 ⟶ 2,217:
| _ -> id)}
let fill color bitmap = {bitmap with color = bitmap.color |> Array.map (fun _ ->color)}
</syntaxhighlight>
</lang>
 
'''Tests:'''
<langsyntaxhighlight lang="fsharp">
//setups
//==check pixel for color function
Line 1,319 ⟶ 2,252:
let myBitmap6 = myBitmap5 |> setPixel {x=5u;y=10u} colorBlack
printfn "Is 5,10 black: %b" (check myBitmap4 colorBlack (5u,10u))
</syntaxhighlight>
</lang>
{{out}}Is empty: true
 
Line 1,338 ⟶ 2,271:
Is 5,10 black: true
'''Usage:'''
<langsyntaxhighlight lang="fsharp">
bitmap 14u 14u
|> fill {red = (byte) 200; green = (byte) 0; blue = (byte) 10}
Line 1,344 ⟶ 2,277:
|> getPixel {x=5u;y=10u}
|> printfn "%A"
</syntaxhighlight>
</lang>
{{out}}
Some {red = 0uy;
green = 0uy;
blue = 0uy;}
 
=={{header|Factor}}==
The image is a matrix of triples {R,G,B}.
Line 1,355 ⟶ 2,287:
most of them are not used right now, but we need them for drawing
so I put every thing here..
<langsyntaxhighlight lang="factor">USING: arrays fry kernel math.matrices sequences ;
IN: rosettacode.raster.storage
 
Line 1,380 ⟶ 2,312:
: set-pixel ( {R,G,B} {i,j} image -- ) set-Mi,j ; inline
: get-pixel ( {i,j} image -- pixel ) Mi,j ; inline
</syntaxhighlight>
</lang>
 
=={{header|FBSL}}==
Volatility in FBSL is a feature uncommon to most other languages. It is the ability of its intrinsic functions as well as its user-defined functions, DynAsm and DynC blocks, and functions imported from 3rd-party DLL's to preserve their return values between function calls in FBSL Variants that have the same names as their respective functions but use neither the parentheses nor the arguments.
Line 1,390 ⟶ 2,321:
 
'''Using pure FBSL's built-in graphics functions:'''
<langsyntaxhighlight lang="qbasic">#DEFINE WM_LBUTTONDOWN 513
#DEFINE WM_RBUTTONDOWN 516
#DEFINE WM_CLOSE 16
Line 1,411 ⟶ 2,342:
FBSL.RELEASEDC(ME, FBSL.GETDC)
END SELECT
END EVENTS</langsyntaxhighlight>
{{out}} [[File:FBSL_RC_Bitmap.PNG]]
 
=={{header|Forth}}==
This creates bitmaps on the heap (they may be deallocated with "FREE").
32-bit or greater cells are assumed, one pixel per cell.
This automatically word-aligns rows, so a separate ''stride'' field is not required.
<langsyntaxhighlight lang="forth">hex
0000ff constant red
00ff00 constant green
Line 1,461 ⟶ 2,391:
4 3 bitmap value test
red test bfill
test bshow cr</langsyntaxhighlight>
 
=={{header|Fortran}}==
See [[Basic bitmap storage/Fortran]]
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">Screenres 320, 240, 8
Dim Shared As Integer w, h
Screeninfo w, h
Const As Ubyte cyan = 3
Const As Ubyte red = 4
 
Sub rellenar(c As Integer)
Line (0,0) - (w/3, h/3), red, BF
End Sub
 
Sub establecePixel(x As Integer, y As Integer, c As Integer)
Pset (x,y), cyan
End Sub
 
rellenar(12)
establecePixel(10,10, cyan)
Locate 12
Print "pixel 10,10 es " & Point(10,10)
Print "pixel 20,20 es " & Point(20,10)
 
Bsave "FreeBASIC_bitmap.bmp", 0
Sleep</syntaxhighlight>
=={{header|Go}}==
===Standard library===
Line 1,473 ⟶ 2,424:
 
Here's how to use the standard packages to do what this task requires:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,529 ⟶ 2,480:
fmt.Printf("Pixel at %7v has R=%d, G=%d, B=%d\n",
image.Pt(30, 40), redc, greenc, bluec)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,541 ⟶ 2,492:
===DIY===
Not a complete working program. Presented here are just types and functions requested by the task.
<langsyntaxhighlight lang="go">// Raster package used with a number of RC tasks.
//
// For each task, documentation in package main source will list this
Line 1,660 ⟶ 2,611:
}
return p.Rgb(), true
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
We implement the <tt>Image</tt> type as an <tt>STArray</tt> so that we can use it in an imperative fashion in the <tt>ST</tt> monad.
 
<langsyntaxhighlight lang="haskell">module Bitmap(module Bitmap) where
import Control.Monad
Line 1,741 ⟶ 2,691:
mapImage :: (Color c, Color c') =>
(c -> c') -> Image s c -> ST s (Image s c')
mapImage f (Image i) = liftM Image $ mapArray f i</langsyntaxhighlight>
 
This module provides an instance of <tt>Color</tt>.
<langsyntaxhighlight lang="haskell">module Bitmap.RGB(module Bitmap.RGB) where
 
import Bitmap
Line 1,766 ⟶ 2,716:
toRGBImage :: Color c => Image s c -> ST s (Image s RGB)
toRGBImage = mapImage $ f . luminance
where f x = RGB (x, x, x)</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
The language has a built-in window data type with associated graphics primitives. A bitmap is just a window that isn't visible on-screen at the moment.
<langsyntaxhighlight Iconlang="icon">procedure makebitmap(width,height)
return open("bitmap", "g", "canvas=hidden",
"size="||width||","||height)
Line 1,784 ⟶ 2,733:
procedure getpixel(w,x,y)
return Pixel(w,x,y)
end</langsyntaxhighlight>
 
=={{header|J}}==
A number of addon packages are available for J that work with common image formats (including PPM), but here we will show a basic bitmap storage type as per the task description.
Line 1,797 ⟶ 2,745:
 
'''Solution:'''
<langsyntaxhighlight lang="j">makeRGB=: 0&$: : (($,)~ ,&3)
fillRGB=: makeRGB }:@$
setPixels=: (1&{::@[)`(<"1@(0&{::@[))`]}
getPixels=: <"1@[ { ]</langsyntaxhighlight>
 
'''Examples:'''
 
<langsyntaxhighlight lang="j"> myimg=: makeRGB 5 8 NB. create a bitmap with height 5 and width 8 (black)
myimg=: 255 makeRGB 5 8 NB. create a white bitmap with height 5 and width 8
myimg=: 127 makeRGB 5 8 NB. create a gray bitmap with height 5 and width 8
Line 1,819 ⟶ 2,767:
 
}:$ myimg NB. get height and width of the image
5 8</langsyntaxhighlight>
 
<code>getPixels</code> and <code>setPixels</code> are generalized to set and get lists/arrays of pixels.
 
<langsyntaxhighlight lang="j">pixellist=: ,"0/~ i. 10 NB. row and column indices for 10 by 10 block of pixels
 
NB. create 10 by 10 block of magenta pixels in the middle of a 300 by 300 green image
Line 1,829 ⟶ 2,777:
 
NB. get pixel color for 10x10 block offset from magenta block
subimg=: (140 + pixellist) getPixels myimg</langsyntaxhighlight>
 
To display the image in a window at any point for verification:
 
<langsyntaxhighlight lang="j">require 'viewmat'
viewRGB=: [: viewrgb 256&#.
 
viewRGB myimg</langsyntaxhighlight>
 
Note that height comes before width here. This is inconsistent with marketing of display resolutions, but matches J's treatment of dimensions.
 
=={{header|Java}}==
Solution {{libheader|AWT}}
<langsyntaxhighlight lang="java">import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
Line 1,872 ⟶ 2,819:
return image;
}
}</langsyntaxhighlight>
 
Test Program {{libheader|JUnit}}
<langsyntaxhighlight lang="java">import static org.junit.Assert.assertEquals;
 
import java.awt.Color;
Line 1,896 ⟶ 2,843:
assertEquals(Color.CYAN, c2);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
 
JavaScript can interact with a drawing context using the HTML5 Canvas API.
 
<langsyntaxhighlight lang="javascript">
// Set up the canvas
var canvas = document.createElement("canvas"),
Line 1,931 ⟶ 2,877:
ctx.fillStyle = "black";
ctx.fillRect(width / 2, height / 2, 1, 1);
</syntaxhighlight>
</lang>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
'''Using packages''' ([https://github.com/JuliaImages/Images.jl Images.jl], [https://github.com/JuliaGraphics/Colors.jl Colors.jl]):
<langsyntaxhighlight lang="julia">using Images, Colors
 
Base.hex(p::RGB{T}) where T = join(hex(c(p), 2) for c in (red, green, blue))
Line 1,960 ⟶ 2,905:
img[2, 3] = cfore
println("\nImage with a pixel set for foreground color:")
showhex(img)</langsyntaxhighlight>
 
{{out}}
Line 1,989 ⟶ 2,934:
FF00FF FF00FF FF00FF FF00FF FF00FF
FF00FF FF00FF FF00FF FF00FF FF00FF</pre>
 
=={{header|KonsolScript}}==
<langsyntaxhighlight KonsolScriptlang="konsolscript">function main() {
Var:Number shape;
Line 2,003 ⟶ 2,947:
Screen:Render()
}
}</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
import java.awt.Color
Line 2,041 ⟶ 2,984:
println(if (c2 == Color.cyan) "cyan" else "unknown")
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,048 ⟶ 2,991:
The color of the pixel at (120, 120) is cyan
</pre>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- Creates a new image object of size 640x480 pixel and 32-bit color depth
img = image(640, 480, 32)
 
Line 2,060 ⟶ 3,002:
 
-- Changes the color of the pixel at point (320, 240) to black
img.setPixel(320, 240, rgb(0,0,0))</langsyntaxhighlight>
 
=={{header|LiveCode}}==
LiveCode has built in support for importing and exporting PBM, JPEG, GIF, BMP or PNG graphics formats
 
<syntaxhighlight lang="livecode">
<lang LiveCode>
-- create an image container box at the center of the current stack window with default properties
create image "test"
Line 2,086 ⟶ 3,027:
-- the next line is copy of the Write a PPM task:
export image "test" to file "~/Test.PPM" as paint -- paint format is one of PBM, PGM, or PPM
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
===Original===
<langsyntaxhighlight lang="lua">function Allocate_Bitmap( width, height )
local bitmap = {}
for i = 1, width do
Line 2,111 ⟶ 3,051:
function Get_Pixel( bitmap, x, y )
return bitmap[x][y]
end</langsyntaxhighlight>
This can be used like:
<langsyntaxhighlight lang="lua">bitmap = Allocate_Bitmap( 100, 50 )
Fill_Bitmap( bitmap, { 15, 200, 80 } )
pixel = Get_Pixel( bitmap, 20, 25 )
print( pixel[1], pixel[2], pixel[3] )</langsyntaxhighlight>
===Alternate===
A more object-oriented and extensible approach for easier re-use elsewhere.
<langsyntaxhighlight lang="lua">local Bitmap = {
new = function(self, width, height)
local instance = setmetatable({ width=width, height=height }, self)
Line 2,157 ⟶ 3,097:
}
Bitmap.__index = Bitmap
setmetatable(Bitmap, { __call = function (t, ...) return t:new(...) end })</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="lua">local bitmap = Bitmap(32,32)
 
-- default pixel representation is 32-bit packed ARGB on [0,255]
Line 2,186 ⟶ 3,126:
print(string.format("pixel at 0,0 = %s", bitmap:get(0,0)))
print(string.format("pixel at 1,1 = %s", bitmap:get(1,1)))
print(string.format("pixel at 2,2 = %s", bitmap:get(2,2)))</langsyntaxhighlight>
Caveat: Just be aware that ''as currently written'' the storage of complex types are referenced rather than copied. So, for example, using the clear() method with a table representing an RGB-tuple, will store the same identical reference throughout the bitmap - so direct modification of any one pixel's internal components would affect all other pixels as well. You should override the clear() method as appropriate to better support your desired pixel representation if this is not the behavior you desire.
{{out}}
Line 2,198 ⟶ 3,138:
pixel at 1,1 = green
pixel at 2,2 = blue</pre>
 
=={{header|M2000 Interpreter}}==
The easy way is to make a function to return an object with all functions on it, for specific image. We have to make the image in a way to render it to screen. The render statement get data in a string using a header of 12 characters (24 bytes). Raster lines are in down-top order. So last raster line is the top one. Also RGB is BGR in this data structure. Raster lines has to be aligned proper, so we may have add some bytes.
Line 2,207 ⟶ 3,146:
 
===P3 ppm===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
\ Bitmap width in pixels, height in pixels
\ Return a group object with some lambda as members: SetPixel, GetPixel, Image$
Line 2,281 ⟶ 3,220:
copy 500*twipsx,50*twipsy use A1.Image$()
 
</syntaxhighlight>
</lang>
 
===P6 ppm===
Need Version 9.4, Rev >=19
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module P6 {
Function Bitmap {
Line 2,445 ⟶ 3,384:
}
P6
</syntaxhighlight>
</lang>
Export using M2000 code for ppm is slower than using internal jpg and bmp encoders. Jpg encoder has a 100% quality, and because this image is black and white we get the best compression. Time 0.304sec is for three exports, two jpg and one bmp.
 
Line 2,457 ⟶ 3,396:
0.3040944sec
</pre>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">allocateImg := proc(width, height)
return Array(1..width, 1..height, 1..3);
end proc:
Line 2,481 ⟶ 3,419:
end do:
return rgb:
end proc:</langsyntaxhighlight>
{{Out|Use}}
<pre>a := allocateImg(200,200);
Line 2,489 ⟶ 3,427:
#Output the image
ImageTools:-Embed(ImageTools:-Create(a))</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
In Mathematica 7/8:
<langsyntaxhighlight Mathematicalang="mathematica">img = Image[ConstantArray[{1, 0, 0}, {1000, 1000}]];
img = ReplacePart[img, {1, 1, 1} -> {0, 0, 1}];
ImageValue[img, {1, 1}]</langsyntaxhighlight>
In Mathematica 9:
<langsyntaxhighlight Mathematicalang="mathematica">img = Image[ConstantArray[{1, 0, 0}, {1000, 1000}]];
img = ReplacePixelValue[img, {1, 1} -> {0, 0, 1}];
ImageValue[img, {1, 1}]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
Save this in a file named Bitmap.mat in a folder named @Bitmap in your MATLAB root directory.
<syntaxhighlight lang="matlab">
<lang MATLAB>
%Bitmap class
%
Line 2,662 ⟶ 3,598:
end %methods
end %classdef
</syntaxhighlight>
</lang>
 
Sample Usage:
<syntaxhighlight lang="matlab">
<lang MATLAB>
>> img = Bitmap(20,30);
>> img.fill([30 30 150]);
Line 2,684 ⟶ 3,620:
>> img.save()
Save Complete
</syntaxhighlight>
</lang>
 
=={{header|MAXScript}}==
 
MAXScript provides a built-in Bitmap class.
<langsyntaxhighlight lang="maxscript">local myBitmap = bitmap 512 512</langsyntaxhighlight>
 
Filling the image with a single colour can be accomplished at creation time by setting the color property.
<langsyntaxhighlight lang="maxscript">local myBitmap = bitmap 512 512 color:(color 128 128 128)</langsyntaxhighlight>
 
Use setPixels to set the colour of a pixel. This function takes an array of colours and is optimised to set the colours of a whole row of pixels.
<langsyntaxhighlight lang="maxscript">setPixels myBitmap [256, 256] #((color 255 255 255))</langsyntaxhighlight>
 
Use getPixels to retrieve the colour of a pixel. As with setPixels, this function is optimised to retrieve one row at a time as an array of colour values.
<langsyntaxhighlight lang="maxscript">local myPixel = getPixels myBitmap [256, 256] 1</langsyntaxhighlight>
 
=={{header|MiniScript}}==
This GUI implementation is for use with [http://miniscript.org/MiniMicro Mini Micro].
<syntaxhighlight lang="miniscript">
// MiniMicro version of MiniScript has all the
// necessary methods built-in to complete this task.
width = 256
height = 256
colr = color.aqua
 
// Create the image with specified width/heigh. With
// no parameters, it defaults width/height to 64 and
// color to black
img = Image.create(width, height, colr)
 
// Create a diagonal line of multiple colors. Uses
// Cartesian coordinates so (0, 0) is lower left corner.
for i in range(0, 255)
img.setPixel i, i, color.rgb(i, i, i)
end for
 
// Get pixel color as RGBA hex values
print "Color at pixel (100, 100): " + img.pixel(100, 100)
print "Color at pixel (0, 0): " + img.pixel(0, 0)
print "Color at pixel (127, 127): " + img.pixel(127, 127)
print "Color at pixel (255, 255): " + img.pixel(255, 255)
 
// Display the image, resizing it to 127 x 127
gfx.drawImage img, 0, 0, 127, 127
 
// Save the file - accepted file extensions:
// tga, jpg, jpeg, and png (retains transparency)
// Optional third parameter is JPG compression quality.
file.saveImage "/usr/test.png", img
</syntaxhighlight>
 
=={{header|Modula-3}}==
Since this code is for use with other tasks, it uses an interface as well as the implementation module.
<langsyntaxhighlight lang="modula3">INTERFACE Bitmap;
 
TYPE UByte = BITS 8 FOR [0 .. 16_FF];
Line 2,725 ⟶ 3,695:
PROCEDURE SetPixel(VAR pic: T; point: Point; color: Pixel);
 
END Bitmap.</langsyntaxhighlight>
<langsyntaxhighlight lang="modula3">MODULE Bitmap;
 
PROCEDURE NewImage(height, width: UByte): T RAISES {BadImage} =
Line 2,773 ⟶ 3,743:
BEGIN
END Bitmap.</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type
Luminance* = uint8
Index* = int
Line 2,839 ⟶ 3,808:
img[1, 2] = color(255, 0, 0)
img[3, 4] = img[1, 2]
img.print</langsyntaxhighlight>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let new_img ~width ~height =
let all_channels =
let kind = Bigarray.int8_unsigned
Line 2,857 ⟶ 3,825:
r_channel,
g_channel,
b_channel)</langsyntaxhighlight>
 
and here is the type of the raster image this function returns:
Line 2,873 ⟶ 3,841:
A more naive form would be this one:
 
<langsyntaxhighlight lang="ocaml">let new_img ~width ~height =
let r_channel, g_channel, b_channel =
let kind = Bigarray.int8_unsigned
Line 2,884 ⟶ 3,852:
(r_channel,
g_channel,
b_channel)</langsyntaxhighlight>
 
Here are the functions to fill with a color and to set one given pixel:
 
<langsyntaxhighlight lang="ocaml">let fill_img ~img:(_, r_channel, g_channel, b_channel) ~color:(r,g,b) =
Bigarray.Array2.fill r_channel r;
Bigarray.Array2.fill g_channel g;
Bigarray.Array2.fill b_channel b;
;;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ocaml">let put_pixel_unsafe (_, r_channel, g_channel, b_channel) (r,g,b) =
(fun x y ->
r_channel.{x,y} <- r;
g_channel.{x,y} <- g;
b_channel.{x,y} <- b;
)</langsyntaxhighlight>
 
<langsyntaxhighlight lang="ocaml">let get_pixel_unsafe (_, r_channel, g_channel, b_channel) =
(fun x y ->
(r_channel.{x,y},
g_channel.{x,y},
b_channel.{x,y})
)</langsyntaxhighlight>
 
we can overload these functions to make some bound checks:
 
<langsyntaxhighlight lang="ocaml">let put_pixel img color x y =
let _, r_channel,_,_ = img in
let width = Bigarray.Array2.dim1 r_channel
Line 2,933 ⟶ 3,901:
if (y < 0) || (y >= height) then invalid_arg "y out of bounds";
get_pixel_unsafe img x y;
;;</langsyntaxhighlight>
 
and a function to get the dimensions:
 
<langsyntaxhighlight lang="ocaml">let get_dims ~img:(_, r_channel, _, _) =
let width = Bigarray.Array2.dim1 r_channel
and height = Bigarray.Array2.dim2 r_channel in
(width, height)</langsyntaxhighlight>
 
=={{header|Octave}}==
In Octave, images are matrix. A grayscale W×H image is stored as a W×H matrix, and RGB W×H image is stored as a W×H×3 image. Possible levels depend on the class of the storage: if it is double, the intensity is a floating point double number between 0 and 1; if it is uint8, the intensity is from 0 to 255; if it is uint16, the intensity is between 0 and 65535.
 
<langsyntaxhighlight lang="octave">im = zeros(W, H, 3, "uint8"); % create an RGB image of width W and height H
% and intensity from 0 to 255; black (all zeros)
im(:,:,1) = 255; % set R to 255
Line 2,954 ⟶ 3,921:
% at W/3, H/3
p = im(40,40,:); % or just store it in the vector p, so that
% p(1) is R, p(2) G and p(3) is B</langsyntaxhighlight>
 
We can hide this in helper functions like:
 
<langsyntaxhighlight lang="octave">function im = create_rgb_image(w, h)
im = zeros(w, h, 3, "uint8");
endfunction
Line 2,978 ⟶ 3,945:
g = im(coord(1), coord(2), 2)
b = im(coord(1), coord(2), 3)
endfunction</langsyntaxhighlight>
 
The only thing to note is that indexing start from 1.
 
<langsyntaxhighlight lang="octave">%example
im = create_rgb_image(200,200);
for x = 1:128
Line 2,989 ⟶ 3,956:
 
% it seems like saveimage wants double class on [0,1]
saveimage("image.ppm", double(im)./256, "ppm");</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
<langsyntaxhighlight lang="oxygenbasic">
'GENERIC BITMAP
 
Line 3,034 ⟶ 4,000:
 
del m
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
We first create a 2D array data type as a functor in a file "Array2D.oz":
<langsyntaxhighlight lang="oz">functor
export
New
Line 3,074 ⟶ 4,039:
 
%% omitted: Clone, Map, Fold, ForAll
end</langsyntaxhighlight>
 
Based on this, we create a functor "Bitmap.oz":
<langsyntaxhighlight lang="oz">%% For real task prefer QTk's images:
%% http://www.mozart-oz.org/home/doc/mozart-stdlib/wp/qtk/html/node38.html
 
Line 3,108 ⟶ 4,073:
 
%% Omitted: MaxValue, ForAllPixels, Transform
end</langsyntaxhighlight>
 
Some functions that are used in other tasks were omitted. See here for the complete module definitions: [[Basic bitmap storage/Oz]]
 
=={{header|Pascal}}==
<langsyntaxhighlight Pascallang="pascal">Interface
uses crt, { GetDir }
graph; { function GetPixel }
Line 3,244 ⟶ 4,208:
end; { with bmpInfoHeader, bmpFileHeader }
end; { procedure }
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
{{libheader|Imlib2}}
<langsyntaxhighlight lang="perl">#! /usr/bin/perl
 
use strict;
Line 3,274 ⟶ 4,237:
my $img = Image::Imlib2->new_using_data(200, 200, $col x (200 * 200));
 
exit 0;</langsyntaxhighlight>
 
=={{header|Phix}}==
Copy of [[Bitmap#Euphoria|Euphoria]]
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>-- Some colour constants:
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
constant black = #000000,
<span style="color: #000080;font-style:italic;">-- Some colour constants:</span>
-- blue = #0000FF,
<span style="color: #008080;">constant</span> <span style="color: #000000;">black</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">#000000</span><span style="color: #0000FF;">,</span>
-- green = #00FF00,
<span style="color: #000080;font-style:italic;">-- red blue = #FF00000000FF,
-- whitegreen = #FFFFFF00FF00,
-- red = #FF0000,</span>
<span style="color: #000000;">white</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">#FFFFFF</span>
-- Create new image filled with some colour
function new_image(integer width, integer height, integer fill_colour=black)
<span style="color: #000080;font-style:italic;">-- Create new image filled with some colour</span>
return repeat(repeat(fill_colour,height),width)
<span style="color: #008080;">function</span> <span style="color: #000000;">new_image</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">fill_colour</span><span style="color: #0000FF;">=</span><span style="color: #000000;">black</span><span style="color: #0000FF;">)</span>
end function
<span style="color: #008080;">return</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fill_colour</span><span style="color: #0000FF;">,</span><span style="color: #000000;">height</span><span style="color: #0000FF;">),</span><span style="color: #000000;">width</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
-- Usage example:
sequence image = new_image(800,600)
<span style="color: #000080;font-style:italic;">-- Usage example:</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">image</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">new_image</span><span style="color: #0000FF;">(</span><span style="color: #000000;">800</span><span style="color: #0000FF;">,</span><span style="color: #000000;">600</span><span style="color: #0000FF;">)</span>
-- Set pixel color:
image[400][300] = white
<span style="color: #000080;font-style:italic;">-- Set pixel color:</span>
 
<span style="color: #000000;">image</span><span style="color: #0000FF;">[</span><span style="color: #000000;">400</span><span style="color: #0000FF;">][</span><span style="color: #000000;">300</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">white</span>
-- Get pixel color
integer colour = image[400][300] -- Now colour is #FF0000</lang>
<span style="color: #000080;font-style:italic;">-- Get pixel color</span>
 
<span style="color: #004080;">integer</span> <span style="color: #000000;">colour</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">image</span><span style="color: #0000FF;">[</span><span style="color: #000000;">400</span><span style="color: #0000FF;">][</span><span style="color: #000000;">300</span><span style="color: #0000FF;">]</span> <span style="color: #000080;font-style:italic;">-- Now colour is #FFFFFF</span>
<!--</syntaxhighlight>-->
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">class Bitmap {
public $data;
public $w;
Line 3,338 ⟶ 4,302:
$b->fill(2, 2, 18, 18, array(240,240,240));
$b->setPixel(0, 15, array(255,0,0));
print_r($b->getPixel(3,3)); //(240,240,240)</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
For time critical applications this would be done with inline-C in PicoLisp,
but especially for small bitmaps the following makes sense.
<langsyntaxhighlight PicoLisplang="picolisp"># Create an empty image of 120 x 90 pixels
(setq *Ppm (make (do 90 (link (need 120)))))
 
Line 3,359 ⟶ 4,322:
# Get the color of a pixel
(de ppmGetPixel (Ppm X Y)
(get Ppm Y X) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Declaration for an image, suitable for BMP files. */
declare image(0:500, 0:500) bit (24) aligned;
Line 3,389 ⟶ 4,351:
 
declare image(*,*) controlled bit (24) aligned;
</syntaxhighlight>
</lang>
 
=={{header|Processing}}==
<langsyntaxhighlight lang="java">PGraphics bitmap = createGraphics(100,100); // Create the bitmap
bitmap.beginDraw();
bitmap.background(255, 0, 0); // Fill bitmap with red rgb color
Line 3,401 ⟶ 4,362:
color c = get(50, 50); // Get the color of same pixel
if(b == c) print("Color changed correctly"); // Verify
</syntaxhighlight>
</lang>
 
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">
:- module(bitmap, [
new_bitmap/3,
Line 3,457 ⟶ 4,416:
replace0(X,Row,RGB,New_Row),
replace0(Y,Pixels,New_Row,New_Pixels).
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">w=800 : h=600
CreateImage(1,w,h)
;1 is internal id of image
Line 3,472 ⟶ 4,430:
; check if we set it right (should be 255)
Debug Blue(Point(10,10))
</syntaxhighlight>
</lang>
 
=={{header|Python}}==
See [[Basic bitmap storage/Python]]
 
=={{header|QBasic}}==
{{works with|QBasic|1.1}}
<syntaxhighlight lang="qbasic">SUB establecePixel (x AS INTEGER, y AS INTEGER, c AS INTEGER)
PSET (x, y), cyan
END SUB
 
SUB rellenar (c AS INTEGER)
SHARED w, h
LINE (0, 0)-(w / 3, h / 3), red, BF
END SUB
 
SCREEN 13
w = 320: h = 200
CONST cyan = 3, red = 4
 
rellenar (12)
CALL establecePixel(10, 10, cyan)
LOCATE 12
PRINT "pixel 10,10 is "; POINT(10, 10)
PRINT "pixel 20,20 is "; POINT(20, 10)</syntaxhighlight>
 
=={{header|R}}==
Line 3,482 ⟶ 4,460:
R can write to most bitmap image formats by default (mostly for the purpose of saving graphs), however there is no built-in way of manipulating images. The pixmap package reads, writes and manipulates portable bitmap file types: PBM, PGM, PPM.
See also, the image function, and the rimage and ReadImage packages, which use libjpeg to read JPEG and PNG files.
<langsyntaxhighlight lang="r"># See the class definitions and constructors with, e.g.
getClass("pixmapIndexed", package=pixmap)
pixmapIndexed
Line 3,500 ⟶ 4,478:
pmcol[i,j]
}
getcol(p2, 3, 4) #red</langsyntaxhighlight>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 3,545 ⟶ 4,522:
;; to view the final image:
bm
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>class Pixel { has UInt ($.R, $.G, $.B) }
class Bitmap {
has UInt ($.width, $.height);
Line 3,577 ⟶ 4,553:
$b.set-pixel( 7, 5, Pixel.new( R => 100, G => 200, B => 0) );
 
say $b.perl;</langsyntaxhighlight>
 
Thanks to the <tt>rw</tt> trait on the <tt>pixel</tt> method, we don't actually need to define two separate methods, <tt>set-pixel</tt> and <tt>get-pixel</tt>, but that is an explicit requirement of the task. (Beware your presuppositions! In Raku, accessors only determine identity, not use. In particular, identity is considered orthogonal to lvalue/rvalue context.)
 
=={{header|RapidQ}}==
 
Line 3,587 ⟶ 4,562:
The commands to draw on the canvas are in the procedure PaintCanvas, which is executed each time the canvas need to be (re)painted.
 
<langsyntaxhighlight lang="rapidq">DECLARE SUB PaintCanvas
 
CREATE form AS QForm
Line 3,610 ⟶ 4,585:
END SUB
 
form.ShowModal</langsyntaxhighlight>
 
=={{header|REXX}}==
===version 1===
Line 3,619 ⟶ 4,593:
 
The image (raster) created was also written to a file &nbsp; ('''image.PPM''') &nbsp; to show verification of the image.
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates how to process/display a simple RGB raster graphics image. */
red/* = 'ff 00 00'x /*a methodsimple to defineRGB a raster graphics red valueimage. */
bluered = 'ff 00 00 ff'x /*" " " " "a method to bluedefine a "red value. */
@. blue = '00 00 ff'x /*' ' ' ' ' blue ' /*define entire @. array to nulls. */
outFN pixel= 'image' /*the filenamedefine ofentire the outputpixel. imagearray PPMto nulls.*/
sWidthoutFN = 500; sHeight= 500 'image' /*the screenfilename widthof the andoutput heightimage inPPM pixels*/
sWidth = 500; sHeight= 500 /*the screen width and height in pixels*/
call RGBfill red /*set the entire image to red. */
Call RGBfill x= 10; y= 40 red /*set pixel's coördinates.the entire image to red. */
call RGBset x,=10; y,=40 blue /*set pixel's coördinates. /*set a pixel (at 10,40) to blue. */
colorCall =RGBset RGBget(x, y) ,blue /*get the color ofset a pixel. (at 10,40) to blue. */
hexV color = c2xRGBget(colorx,y) /*get the color of a pixel. /*get hex value of pixel's color. */
binVhexV = x2bc2x(hexVcolor) /*get " binary " " " hex "value of pixel's color. */
binV = x2b(hexV) /* " binary " " " " */
bin3V = left(binV, 8) substr(binV, 9, 8) right(binV, 8)
hex3Vbin3V = left(hexVbinV, 28) substr(hexVbinV, 39, 28) right(hexVbinV, 28)
hex3V = left(hexV,2) substr(hexV,3,2) right(hexV,2)
xy= '(' || x","y')' /*create a handy─dandy literal for SAY.*/
say xy= '('||x','y')' pixel in binary: ' binV /*show the binary value of 20,50 create a handy-dandy literal for SAY.*/
say Say xy ' pixel in binary: ' bin3V binV /*show again, but with spaces. the binary value of 20,50 */
Say xy ' pixel in binary: ' bin3V /*show again,but with spaces. */
say /*show a blank between binary and hex. */
saySay xy ' pixel in hex: ' hexV /*show again,a butblank in hexadecimal.between bin & hex. */
say Say xy ' pixel in hex: ' hex3V hexV /*show again, but within spaceshexadecimal. */
Say xy ' pixel in hex: ' hex3V /*show again,but with spaces. */
call PPMwrite outFN, sWidth, sHeight /*create a PPM (output) file of image. */ /* ◄■■■■■■■■ not part of this task.*/
Call PPMwrite outFN,sWidth,sHeight /*create a PPM (output) file */
say /*show a blank. */
/* ?¦¦¦¦¦¦¦¦ not part of this task.*/
say 'The file ' outFN".PPM was created." /*inform user that a file was created. */
exitSay /*show a blank. /*stick a fork in it, we're all done. */
Say 'The file ' outFN'.PPM was created.' /*inform user */
/*──────────────────────────────────────────────────────────────────────────────────────*/
RGBfill:Exit @.=arg(1); return /*stick a fork in it, we're all done. /*fill image with a color.*/
/*---------------------------------------------------------------------*/
RGBget: parse arg px,py; return @.px.py /*get a pixel's color. */
RGBsetRGBfill: parse pixel.=arg px,py,p$(1); @.px.py=p$; Return return /*set " " " fill image with a color.*/
RGBget: Parse arg px,py; Return pixel.px.py /*get a pixel's color. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
RGBset: Parse arg px,py,psep; pixel.px.py=psep; Return /*set a pixel */
PPMwrite: parse arg oFN, width, height /*obtain output filename, width, height*/
/*---------------------------------------------------------------------*/
oFID= oFN'.PPM'; $='9'x; #=255 /*fileID; separator; max color value.*/
PPMwrite: Parse arg oFN,width,height
call charout oFID, , 1 /*set the position of the file's output*/
oFID= oFN'.PPM' /* fileID call charout oFID,'P6'width || $ || height || $ || # || $ /*write hdr info.*/
sep='9'x; /* separator do j=1 for width*/
maxcol=255 do k=1 for height; /* callmax charoutcolor oFID, @value.j.k */
Call charout oFID,,1 end /*k*/set the position /* ↑ writeof the PPM file, ···'s output*/
Call charout oFID,'P6'width||sep||height||sep||maxcol||sep /* header */
end /*j*/ /* └───────── ··· one pixel at a time.*/
Do i=1 To width
call charout oFID; return /*close the output file just to be safe*/</lang>
Do j=1 To height;
Call charout oFID,pixel.i.j
End
End
Call charout oFID /* close the output file just to be safe */
Return</syntaxhighlight>
{{out|output}}
<pre>
Line 3,670 ⟶ 4,650:
===version 2===
This program actually creates a BMP file
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Draw a picture from pixels
* 16.06.2014 Walter Pachl
Line 3,780 ⟶ 4,760:
i=w3*(y-1)+3*(x-1)
say 'color at pixel' x'/'y'='c2x(substr(pic,i+1,3))
Return c2x(substr(pic,i+1,3))</langsyntaxhighlight>
{{out}}
<pre>lend: 600 -> 58020000 => 600
Line 3,790 ⟶ 4,770:
 
and have a look at the file pic.bmp created by this program</pre>
 
=={{header|Ruby}}==
I haven't been able to find any kind of package for manipulating bitmap images, so let's roll one
<langsyntaxhighlight lang="ruby">class RGBColour
def initialize(red, green, blue)
unless red.between?(0,255) and green.between?(0,255) and blue.between?(0,255)
Line 3,841 ⟶ 4,820:
end
alias_method :set_pixel, :[]=
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Rgb {
pub r: u8,
Line 3,925 ⟶ 4,903:
}
assert_eq!(Some(&Rgb::new(0, 155, 20)), image.get(3, 4));
}</langsyntaxhighlight>
 
=={{header|Scala}}==
===Java translation===
{{trans|Java}}
<langsyntaxhighlight lang="scala">import java.awt.image.BufferedImage
import java.awt.Color
 
Line 3,944 ⟶ 4,921:
def setPixel(x:Int, y:Int, c:Color)=image.setRGB(x, y, c.getRGB())
def getPixel(x:Int, y:Int)=new Color(image.getRGB(x, y))
}</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="scala">val img=new RgbBitmap(50, 50);
img.fill(Color.CYAN)
img.setPixel(5, 5, Color.BLUE)
Line 3,953 ⟶ 4,930:
assert(img.getPixel(5,5)==Color.BLUE)
assert(img.width==50)
assert(img.height==50)</langsyntaxhighlight>
===Scala idiom===
A more Scalesque version could be with the use of its idiom:
{{Out}}
Best experienced in your browser [https://scastie.scala-lang.org/cy2uZB9DSaWVMnZjTJgQNA with Scastie (remote JVM)].
<langsyntaxhighlight lang="scala">import java.awt.image.BufferedImage
import java.awt.Color
 
Line 3,999 ⟶ 4,976:
assert(img0.height == 60)
println("Tests successfully completed with no errors found.")
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
 
Definitions of list procedures:
<langsyntaxhighlight lang="scheme">(define (make-list length object)
(if (= length 0)
(list)
Line 4,022 ⟶ 4,998:
(if (= element 1)
(car list)
(list-get (cdr list) (- element 1))))</langsyntaxhighlight>
Definitions of image procedures:
<langsyntaxhighlight lang="scheme">(define (make-image columns rows)
(if (= rows 0)
(list)
Line 4,037 ⟶ 5,013:
 
(define (image-get image column row)
(list-get (list-get image row) column))</langsyntaxhighlight>
Definitions of some colours:
<langsyntaxhighlight lang="scheme">(define *black* (list 0 0 0))
(define *white* (list 255 255 255))
(define *red* (list 255 0 0))
(define *green* (list 0 255 0))
(define *blue* (list 0 0 255))</langsyntaxhighlight>
This creates a small image with a black background and a single blue pixel:
<langsyntaxhighlight lang="scheme">(define image (make-image 3 2))
(image-fill! image *black*)
(image-set! image 2 1 *blue*)
(display image)
(newline)</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">(((0 0 0) (0 0 255) (0 0 0)) ((0 0 0) (0 0 0) (0 0 0)))</langsyntaxhighlight>
 
=={{header|Seed7}}==
The types and functions requested are predefined in the libraries
Line 4,063 ⟶ 5,038:
*The color of a pixel can be retrieved with [http://seed7.sourceforge.net/libraries/draw.htm#getPixelColor(in_PRIMITIVE_WINDOW,in_integer,in_integer) getPixelColor].
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "draw.s7i";
 
Line 4,076 ⟶ 5,051:
myColor := getPixelColor(myPixmap, 20, 30);
writeln(myColor.redLight <& " " <& myColor.greenLight <& " " <& myColor.blueLight);
end func;</langsyntaxhighlight>
 
=={{header|SequenceL}}==
<langsyntaxhighlight lang="seed7">RGB ::= (R: int(0), G: int(0), B: int(0));
 
newBitmap: int * int -> RGB(2);
Line 4,116 ⟶ 5,090:
redCenter := setColorAt(filledGreen, width / 2, height / 2, lightRed);
in
getColorAt(redCenter, width / 2, height / 2);</langsyntaxhighlight>
 
{{out}}
<pre>cmd:> main.exe
(B:51,G:51,R:255)</pre>
 
=={{header|Smalltalk}}==
<lang{{works with|Smalltalk>/X}}
<syntaxhighlight lang="smalltalk">|img1 img2|
|img|
"a depth24 RGB image"
img := Image width:100 height:200 depth:24.
img1 := Image width:100 height:200 depth:24.
img fillRectangle:(0@0 corner:100@100) with:Color red.
img1 fillRectangle:(0@0 corner:100@100) with:Color red.
img saveOn:'sampleFile.png'.
img1 fillRectangle:(0@100 corner:100@100) with:(Color rgbValue: 16rFF00FF).
img1 colorAt:(10 @ 10) put:(Color green).
img1 saveOn:'sampleFile.png'.
 
img1 displayOn:Transcript window graphicsContext.
Transcript showCR:(img1 colorAt:(100 @ 10) ).
 
"a depth8 palette image"
img displayOn:Transcript window graphicsContext.
img2 := Image width:100 height:200 depth:8.
</lang>
img2 colorMap:{ Color black. Color red . Color green }.
img2 fillRectangle:(0@0 corner:100@100) with:Color red.
img2 fillRectangle:(0@100 corner:100@100) with: 16r02.
img2 colorAt:(10 @ 10) put:(Color green).
img2 saveOn:'sampleFile.gif'.
 
img2 displayOn:Transcript window graphicsContext.
Transcript showCR:(img2 colorAt:(100 @ 10) ).
</syntaxhighlight>
=={{header|Tcl}}==
{{libheader|Tk}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require Tk
namespace path ::tcl::mathfunc ;# for [max] function
Line 4,163 ⟶ 5,150:
setPixel $img green {40 40}
 
set rbg [getPixel $img {40 40}]</langsyntaxhighlight>
 
=={{header|TI-89 BASIC}}==
 
TI-89 BASIC does not have user-defined data structures. The Rosetta Code tasks which use this image type have instead been implemented using the TI-89's graph screen.
 
=={{header|UNIX Shell}}==
{{works with|ksh93}}
<langsyntaxhighlight lang="bash">typeset -T RGBColor_t=(
integer r g b
function to_s {
Line 4,244 ⟶ 5,229:
b.setpixel 2 1 "$(color.black)"
echo "$(b.getpixel 0 0)"
b.to_s</langsyntaxhighlight>
 
{{out}}
Line 4,253 ⟶ 5,238:
255 0 0 0 255 0 0 0 255
255 255 0 255 255 255 0 0 0</pre>
 
=={{header|Vedit macro language}}==
 
An edit buffer is used to store pixel data. In order to allow unlimited image size, a temporary file (here pixel.data) can be assosicated to the buffer. You could directly open the image file you are creating (as in the task [[Dragon_curve#Vedit_macro_language|Dragon_curve]], but here we first create just the plain pixel data so that the required image file format can be decided later.
<langsyntaxhighlight lang="vedit">#11 = 400 // Width of the image
#12 = 300 // Height of the image
 
Line 4,323 ⟶ 5,307:
#6 = Cur_Char(1)
#7 = Cur_Char(2)
Return</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
 
<langsyntaxhighlight lang="vbnet">' The StructLayout attribute allows fields to overlap in memory.
<System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)> _
Public Structure Rgb
Line 4,349 ⟶ 5,332:
End Sub
 
End Structure</langsyntaxhighlight>
 
<langsyntaxhighlight lang="vbnet">Public Class RasterBitmap
 
Private m_pixels() As Rgb
Line 4,389 ⟶ 5,372:
End Function
 
End Class</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|DOME}}
The above library's ImageData class fits the bill here (version 1.3.0 or later).
<langsyntaxhighlight ecmascriptlang="wren">import "graphics" for Canvas, ImageData, Color
import "dome" for Window
 
Line 4,427 ⟶ 5,409:
 
static draw(alpha) {}
}</langsyntaxhighlight>
 
{{out}}
Line 4,436 ⟶ 5,418:
=={{header|Xojo}}==
 
<langsyntaxhighlight lang="vb">Function CreatePicture(width As Integer, height As Integer) As Picture
Return New Picture(width, height)
End Function
Line 4,452 ⟶ 5,434:
p.RGBSurface.Pixel(x, y) = pColor
End Sub
</syntaxhighlight>
</lang>
 
=={{header|XPL0}}==
[[File:BitmapXPL0.png|right]]
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \include 'code' declarations
def Width=180, Height=135, Color=$123456;
int X, Y;
Line 4,466 ⟶ 5,447:
X:= ChIn(1); \wait for keystroke
SetVid(3); \restore display to normal text mode
]</langsyntaxhighlight>
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Bitmap
// by Galileo, 07/2022
 
open window 200, 200
backcolor 255, 0, 0 // red
 
clear window
 
color 0, 255, 0 // green
dot 100, 100
 
c$ = getbit$(100, 100, 100, 100) // get color area 1x1 pixel
print c$
</syntaxhighlight>
{{out}}
<pre>rgb 1,1:00ff00
---Program done, press RETURN---</pre>
=={{header|zkl}}==
This solution creates a PPM image. No error checking or clipping.
<langsyntaxhighlight lang="zkl">class PPM{ // (0,0) is logically bottom left
fcn init(width,height){
sz:=width*height*3;
Line 4,488 ⟶ 5,486:
out.close();
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">ppm:=PPM(256,256);
ppm.fill(0x00FF88);
foreach x in ([50..200]){ ppm[x,50]=0xff|00|00; } // horizontal red line
 
ppm.write(File("foo.ppm","wb"));</langsyntaxhighlight>
{{out}}
<pre>
Line 4,505 ⟶ 5,503:
...
</pre>
{{omit from|AWK}}
{{omit from|PARI/GP}}
9,479

edits