This commit is contained in:
Ingy döt Net 2013-04-10 16:19:29 -07:00
parent e5e8880e41
commit 518da4a923
1019 changed files with 15877 additions and 0 deletions

10
Task/Bitmap/0DESCRIPTION Normal file
View file

@ -0,0 +1,10 @@
Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions.
If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions:
* one to fill an image with a plain RGB color,
* one to set a given pixel with a color,
* one to get the color of a pixel.
(If there are specificities about the storage or the allocation, explain those.)
''These functions are used as a base for the articles in the category [[Raster_graphics_operations|raster graphics operations]], and a basic output function to check the results is available in the article [[write ppm file]].''

2
Task/Bitmap/1META.yaml Normal file
View file

@ -0,0 +1,2 @@
---
note: Raster graphics operations

View file

@ -0,0 +1,54 @@
MODE PIXEL = STRUCT(#SHORT# BITS red,green,blue);
MODE POINT = STRUCT(INT x,y);
MODE IMAGE = [0,0]PIXEL; # instance attributes #
MODE CLASSIMAGE = STRUCT ( # class attributes #
PIXEL black, red, green, blue, white,
PROC (REF IMAGE)REF IMAGE init,
PROC (REF IMAGE, PIXEL)VOID fill,
PROC (REF IMAGE)VOID print,
# virtual: #
REF PROC (REF IMAGE, POINT, POINT, PIXEL)VOID line,
REF PROC (REF IMAGE, POINT, INT, PIXEL)VOID circle,
REF PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID cubic bezier
);
CLASSIMAGE class image = (
# black = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16r00),
# red = # (#SHORTEN# 16rff, #SHORTEN# 16r00, #SHORTEN# 16r00),
# green = # (#SHORTEN# 16r00, #SHORTEN# 16rff, #SHORTEN# 16r00),
# blue = # (#SHORTEN# 16r00, #SHORTEN# 16r00, #SHORTEN# 16rff),
# white = # (#SHORTEN# 16rff, #SHORTEN# 16rff, #SHORTEN# 16rff),
# PROC init = # (REF IMAGE self)REF IMAGE:
BEGIN
(fill OF class image)(self, black OF class image);
self
END,
# PROC fill = # (REF IMAGE self, PIXEL color)VOID:
FOR x FROM 1 LWB self TO 1 UPB self DO
FOR y FROM 2 LWB self TO 2 UPB self DO
self[x,y] := color
OD
OD,
# PROC print = # (REF IMAGE self)VOID:
printf(($n(UPB self)(3(16r2d))l$, self)),
# virtual: #
# REF PROC line = # LOC PROC (REF IMAGE, POINT, POINT, PIXEL)VOID,
# REF PROC circle = # LOC PROC (REF IMAGE, POINT, INT, PIXEL)VOID,
# REF PROC cubic bezier = # LOC PROC (REF IMAGE, POINT, POINT, POINT, POINT, PIXEL, UNION(INT, VOID))VOID
);
OP CLASSOF = (IMAGE image)CLASSIMAGE: class image;
OP INIT = (REF IMAGE image)REF IMAGE: (init OF (CLASSOF image))(image);
BOOL test = TRUE;
IF test THEN
###
The test program
###
REF IMAGE x := INIT LOC[1:16, 1:16]PIXEL;
(fill OF class image) (x, white OF class image);
(print OF class image) (x)
FI

View file

@ -0,0 +1,17 @@
package Bitmap_Store is
type Luminance is mod 2**8;
type Pixel is record
R, G, B : Luminance;
end record;
Black : constant Pixel := (others => 0);
White : constant Pixel := (others => 255);
type Image is array (Positive range <>, Positive range <>) of Pixel;
procedure Fill (Picture : in out Image; Color : Pixel);
procedure Print (Picture : Image);
type Point is record
X, Y : Positive;
end record;
end Bitmap_Store;

View file

@ -0,0 +1,28 @@
with Ada.Text_IO; use Ada.Text_IO;
package body Bitmap_Store is
procedure Fill (Picture : in out Image; Color : Pixel) is
begin
for I in Picture'Range (1) loop
for J in Picture'Range (2) loop
Picture (I, J) := Color;
end loop;
end loop;
end Fill;
procedure Print (Picture : Image) is
begin
for I in Picture'Range (1) loop
for J in Picture'Range (2) loop
if Picture (I, J) = White then
Put (' ');
else
Put ('H');
end if;
end loop;
New_Line;
end loop;
end Print;
end Bitmap_Store;

View file

@ -0,0 +1,7 @@
use Bitmap_Store; with Bitmap_Store;
...
X : Image (1..64, 1..64);
begin
Fill (X, (255, 255, 255));
X (1, 2) := (R => 255, others => 0);
X (3, 4) := X (1, 2);

View file

@ -0,0 +1,93 @@
test:
blue := color(0,0,255) ; rgb
cyan := color(0,255,255)
blue_square := Bitmap(10, 10, blue)
cyanppm := Bitmap(10, 10, cyan)
x := blue_square[4,4] ; get pixel(4,4)
msgbox % "blue: 4,4,R,G,B, RGB: " x.R ", " x.G ", " x.B ", " x.rgb()
blue_square[4,4] := cyan ; set pixel(4,4)
x := blue_square[4,4] ; get pixel(4,4)
blue_square.write("blue.ppm")
return
Bitmap(width = 1, height = 1, background = 0)
{
global black
black := color(0,0,0)
if !background
background := black
static BitmapType
if !BitmapType
BitmapType
:= Object("fill", "Bitmap_Fill"
,"write", "Bitmap_write_ppm3")
img := Object("width", width
,"height", height
, "base" , BitmapType)
img._SetCapacity(height) ; an array of rows
img.fill(background)
Return img
}
Bitmap_Fill(bitmap, color)
{
r := color.r
g := color.g
b := color.b
loop % bitmap.height
{
height := A_Index
loop % bitmap.width
{
width := A_Index
bitmap[height, width] := color(r, g, b)
}
}
return bitmap
}
Bitmap_write_ppm3(bitmap, filename)
{
file := FileOpen(filename, 0x11) ; utf-8, write
file.seek(0,0)
file.write("P3`n"
. bitmap.width . " " . bitmap.height . "`n"
. "255`n")
loop % bitmap.height
{
height := A_Index
loop % bitmap.width
{
width := A_Index
color := bitmap[height, width]
file.Write(color.R . " ")
file.Write(color.G . " ")
file.Write(color.B . " ")
}
file.write("`n")
}
file.close()
return 0
}
Color(r, g, b)
{
static ColorType
if !ColorType
ColorType
:= Object("rgb" , "Color_rgb")
return Object("r" , r, "g", g, "b", b
, "base" , ColorType)
; return Object("r" , r, "g", g, "b", b, "rgb", "Color_rgb")
}
Color_rgb(clr)
{
return clr.R << 16 | clr.G << 8 | clr.B
}

View file

@ -0,0 +1,18 @@
graphsize 30,30
call fill(rgb(255,0,0))
call setpixel(10,10,rgb(0,255,255))
print "pixel 10,10 is " + pixel(10,10)
print "pixel 20,20 is " + pixel(20,10)
imgsave "BASIC256_bitmap.png"
end
subroutine fill(c)
color c
rect 0,0,graphwidth, graphheight
end subroutine
subroutine setpixel(x,y,c)
color c
plot x,y
end subroutine

View file

@ -0,0 +1,34 @@
Width% = 200
Height% = 200
REM Set window size:
VDU 23,22,Width%;Height%;8,16,16,128
REM Fill with an RGB colour:
PROCfill(100,150,200)
REM Set a pixel:
PROCsetpixel(100,100,255,255,0)
REM Get a pixel:
rgb% = FNgetpixel(100,100)
PRINT RIGHT$("00000" + STR$~rgb%, 6)
END
DEF PROCfill(r%,g%,b%)
COLOUR 1,r%,g%,b%
GCOL 1+128
CLG
ENDPROC
DEF PROCsetpixel(x%,y%,r%,g%,b%)
COLOUR 1,r%,g%,b%
GCOL 1
LINE x%*2,y%*2,x%*2,y%*2
ENDPROC
DEF FNgetpixel(x%,y%)
LOCAL col%
col% = TINT(x%*2,y%*2)
SWAP ?^col%,?(^col%+2)
= col%

41
Task/Bitmap/C/bitmap-1.c Normal file
View file

@ -0,0 +1,41 @@
#ifndef _IMGLIB_0
#define _IMGLIB_0
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <math.h>
#include <sys/queue.h>
typedef unsigned char color_component;
typedef color_component pixel[3];
typedef struct {
unsigned int width;
unsigned int height;
pixel * buf;
} image_t;
typedef image_t * image;
image alloc_img(unsigned int width, unsigned int height);
void free_img(image);
void fill_img(image img,
color_component r,
color_component g,
color_component b );
void put_pixel_unsafe(
image img,
unsigned int x,
unsigned int y,
color_component r,
color_component g,
color_component b );
void put_pixel_clip(
image img,
unsigned int x,
unsigned int y,
color_component r,
color_component g,
color_component b );
#define GET_PIXEL(IMG, X, Y) (IMG->buf[ ((Y) * IMG->width + (X)) ])
#endif

58
Task/Bitmap/C/bitmap-2.c Normal file
View file

@ -0,0 +1,58 @@
image alloc_img(unsigned int width, unsigned int height)
{
image img;
img = malloc(sizeof(image_t));
img->buf = malloc(width * height * sizeof(pixel));
img->width = width;
img->height = height;
return img;
}
void free_img(image img)
{
free(img->buf);
free(img);
}
void fill_img(
image img,
color_component r,
color_component g,
color_component b )
{
unsigned int i, n;
n = img->width * img->height;
for (i=0; i < n; ++i)
{
img->buf[i][0] = r;
img->buf[i][1] = g;
img->buf[i][2] = b;
}
}
void put_pixel_unsafe(
image img,
unsigned int x,
unsigned int y,
color_component r,
color_component g,
color_component b )
{
unsigned int ofs;
ofs = (y * img->width) + x;
img->buf[ofs][0] = r;
img->buf[ofs][1] = g;
img->buf[ofs][2] = b;
}
void put_pixel_clip(
image img,
unsigned int x,
unsigned int y,
color_component r,
color_component g,
color_component b )
{
if (x < img->width && y < img->height)
put_pixel_unsafe(img, x, y, r, g, b);
}

View file

@ -0,0 +1,16 @@
(import '[java.awt Color Graphics Image]
'[java.awt.image BufferedImage])
(defn blank-bitmap [width height]
(BufferedImage. width height BufferedImage/TYPE_3BYTE_BGR))
(defn fill [image color]
(doto (.getGraphics image)
(.setColor color)
(.fillRect 0 0 (.getWidth image) (.getHeight image))))
(defn set-pixel [image x y color]
(.setRGB image x y (.getRGB color)))
(defn get-pixel [image x y]
(Color. (.getRGB image x y)))

View file

@ -0,0 +1,44 @@
hex
0000ff constant red
00ff00 constant green
ff0000 constant blue
decimal
1 cells constant pixel
: pixels cells ;
: bdim ( bmp -- w h ) 2@ ;
: bheight ( bmp -- h ) @ ;
: bwidth ( bmp -- w ) bdim drop ;
: bdata ( bmp -- addr ) 2 cells + ;
: bitmap ( w h -- bmp )
2dup * pixels bdata allocate throw
dup >r 2! r> ;
: bfill ( pixel bmp -- )
dup bdata swap bdim * pixels
bounds do
dup i !
pixel +loop
drop ;
: bxy ( x y bmp -- addr )
dup >r bwidth * + pixels r> bdata + ;
: b@ ( x y bmp -- pixel ) bxy @ ;
: b! ( pixel x y bmp -- ) bxy ! ;
: bshow ( bmp -- )
hex
dup bdim
0 do cr
dup 0 do
over i j rot b@ if [char] * else bl then emit \ 7 u.r
loop
loop
2drop decimal ;
4 3 bitmap value test
red test bfill
test bshow cr

120
Task/Bitmap/Go/bitmap.go Normal file
View file

@ -0,0 +1,120 @@
// Raster package used with a number of RC tasks.
//
// For each task, documentation in package main source will list this
// file and others that are necessary to build a raster package with
// sufficient functionality for the task. To build a working program,
// build a raster package from the files listed, install the package,
// and then compile and link the package main that completes the task.
//
// Alternatively, files in the raster package can be combined as desired
// to build a package that meets the needs of multiple tasks.
package raster
// Rgb is a 24 bit color value represented with a 32 bit int
// in the conventional way. This is expected to be convenient
// for the programmer in many cases.
type Rgb int32
// Pixel has r, g, and b as separate fields. This is used as
// the in-memory representation of a bitmap.
type Pixel struct {
R, G, B byte
}
// Pixel returns a new Pixel from a Rgb value
func (c Rgb) Pixel() Pixel {
return Pixel{R: byte(c >> 16), G: byte(c >> 8), B: byte(c)}
}
// Rgb returns a single Rgb value computed from rgb fields of a Pixel
// of a Pixel.
func (p Pixel) Rgb() Rgb {
return Rgb(p.R)<<16 | Rgb(p.G)<<8 | Rgb(p.B)
}
// Bitmap is the in-memory representation, or image storage type of a bitmap.
// Zero value for type is a valid zero-size bitmap.
// The only exported field is Comments. Remaining fields have interdepencies
// that are managed by package code and so should not be directly accessed
// from outside the package.
type Bitmap struct {
Comments []string
rows, cols int
px []Pixel // all pixels as a single slice, row major order
pxRow [][]Pixel // rows of pixels as slices of px
}
const creator = "# Creator: Rosetta Code http://rosettacode.org/"
// New is a Bitmap "constructor." Parameters x and y are extents.
// That is, the new bitmap will have x columns and y rows.
func NewBitmap(x, y int) (b *Bitmap) {
b = &Bitmap{
Comments: []string{creator},
rows: y, // named fields here to prevent possible mix-ups.
cols: x,
px: make([]Pixel, x*y),
pxRow: make([][]Pixel, y),
}
// Note rows of pixels are not allocated separately.
// Rather the whole bitmap is allocted in one chunk as px.
// This simplifies allocation and maintains locality.
x0, x1 := 0, x
for i := range b.pxRow {
b.pxRow[i] = b.px[x0:x1] // slice operation. does no allocation.
x0, x1 = x1, x1+x
}
return b
}
// Extent returns bitmap dimensions.
func (b *Bitmap) Extent() (cols, rows int) {
return b.cols, b.rows
}
// Fill entire bitmap with solid color.
func (b *Bitmap) Fill(p Pixel) {
for i := range b.px {
b.px[i] = p
}
}
func (b *Bitmap) FillRgb(c Rgb) {
b.Fill(c.Pixel())
}
// Set a single pixel color value.
// Clips to bitmap boundaries.
// Returns true if pixel was set, false if clipped.
func (b *Bitmap) SetPx(x, y int, p Pixel) bool {
defer func() { recover() }()
b.pxRow[y][x] = p
return true
}
func (b *Bitmap) SetPxRgb(x, y int, c Rgb) bool {
return b.SetPx(x, y, c.Pixel())
}
// Note: Clipping to bitmap boundaries is needed for program correctness
// but is otherwise not required by the task. It is implemented with the
// combination of pxRow and the deferred recover. SetPx, GetPx return the
// clipping result as a way for higher level graphics functions to track
// plotting and clipping status. As this is not required by tasks though,
// it is generally not implemented.
// Get a single pixel color value.
// Returns pixel and ok=true if coordinates are within bitmap boundaries.
// Returns ok=false if coordinates are outside bitmap boundaries.
func (b *Bitmap) GetPx(x, y int) (p Pixel, ok bool) {
defer func() { recover() }()
return b.pxRow[y][x], true
}
func (b *Bitmap) GetPxRgb(x, y int) (Rgb, bool) {
p, ok := b.GetPx(x, y)
if !ok {
return 0, false
}
return p.Rgb(), true
}

View file

@ -0,0 +1,77 @@
module Bitmap(module Bitmap) where
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
newtype Pixel = Pixel (Int, Int) deriving Eq
instance Ord Pixel where
compare (Pixel (x1, y1)) (Pixel (x2, y2)) =
case compare y1 y2 of
EQ -> compare x1 x2
v -> v
instance Ix Pixel where
{- This instance differs from the one for (Int, Int) in that
the ordering of indices is
(0,0), (1,0), (2,0), (0,1), (1,1), (2,1)
instead of
(0,0), (0,1), (1,0), (1,1), (2,0), (2,1). -}
range (Pixel (xa, ya), Pixel (xz, yz)) =
[Pixel (x, y) | y <- [ya .. yz], x <- [xa .. xz]]
index (Pixel (xa, ya), Pixel (xz, _)) (Pixel (xi, yi)) =
(yi - ya)*(xz - xa + 1) + (xi - xa)
inRange (Pixel (xa, ya), Pixel (xz, yz)) (Pixel (xi, yi)) =
not $ xi < xa || xi > xz || yi < ya || yi > yz
rangeSize (Pixel (xa, ya), Pixel (xz, yz)) =
(xz - xa + 1) * (yz - ya + 1)
instance Show Pixel where
show (Pixel p) = show p
class Ord c => Color c where
luminance :: c -> Int
-- The Int should be in the range [0 .. 255].
black, white :: c
toNetpbm :: [c] -> String
fromNetpbm :: [Int] -> [c]
netpbmMagicNumber, netpbmMaxval :: c -> String
{- The argument to these two functions is ignored; the
parameter is only for typechecking. -}
newtype Color c => Image s c = Image (STArray s Pixel c)
image :: Color c => Int -> Int -> c -> ST s (Image s c)
{- Creates a new image with the given width and height, filled
with the given color. -}
image w h = liftM Image .
newArray (Pixel (0, 0), Pixel (w - 1, h - 1))
listImage :: Color c => Int -> Int -> [c] -> ST s (Image s c)
{- Creates a new image with the given width and height, with
each pixel set to the corresponding element of the given list. -}
listImage w h = liftM Image .
newListArray (Pixel (0, 0), Pixel (w - 1, h - 1))
dimensions :: Color c => Image s c -> ST s (Int, Int)
dimensions (Image i) = do
(_, Pixel (x, y)) <- getBounds i
return (x + 1, y + 1)
getPix :: Color c => Image s c -> Pixel -> ST s c
getPix (Image i) = readArray i
getPixels :: Color c => Image s c -> ST s [c]
getPixels (Image i) = getElems i
setPix :: Color c => Image s c -> Pixel -> c -> ST s ()
setPix (Image i) = writeArray i
fill :: Color c => Image s c -> c -> ST s ()
fill (Image i) c = getBounds i >>= mapM_ f . range
where f p = writeArray i p c
mapImage :: (Color c, Color c') =>
(c -> c') -> Image s c -> ST s (Image s c')
mapImage f (Image i) = liftM Image $ mapArray f i

View file

@ -0,0 +1,23 @@
module Bitmap.RGB(module Bitmap.RGB) where
import Bitmap
import Control.Monad.ST
newtype RGB = RGB (Int, Int, Int) deriving (Eq, Ord)
instance Color RGB where
luminance (RGB (r, g, b)) = round x
where x = 0.2126*r' + 0.7152*g' + 0.0722*b'
(r', g', b') = (toEnum r, toEnum g, toEnum b)
black = RGB (0, 0, 0)
white = RGB (255, 255, 255)
toNetpbm = concatMap f
where f (RGB (r, g, b)) = [toEnum r, toEnum g, toEnum b]
fromNetpbm [] = []
fromNetpbm (r : g : b : rest) = RGB (r, g, b) : fromNetpbm rest
netpbmMagicNumber _ = "P6"
netpbmMaxval _ = "255"
toRGBImage :: Color c => Image s c -> ST s (Image s RGB)
toRGBImage = mapImage $ f . luminance
where f x = RGB (x, x, x)

View file

@ -0,0 +1,36 @@
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
public class BasicBitmapStorage
{
private BufferedImage image;
public BasicBitmapStorage(final int width, final int height)
{
image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
}
public void fill(final Color c)
{
Graphics g = image.getGraphics();
g.setColor(c);
g.fillRect(0, 0, image.getWidth(), image.getHeight());
}
public void setPixel(final int x, final int y, final Color c)
{
image.setRGB(x, y, c.getRGB());
}
public Color getPixel(final int x, final int y)
{
return new Color(image.getRGB(x, y));
}
public Image getImage()
{
return image;
}
}

View file

@ -0,0 +1,19 @@
import java.awt.Color;
import junit.framework.TestCase;
public class BasicBitmapStorageTest extends TestCase
{
public static final int WIDTH = 640, HEIGHT = 480;
BasicBitmapStorage bbs = new BasicBitmapStorage(WIDTH, HEIGHT);
public void testHappy()
{
bbs.fill(Color.cyan);
bbs.setPixel(WIDTH / 2, HEIGHT / 2, Color.BLACK);
Color c1 = bbs.getPixel(WIDTH / 2, HEIGHT / 2);
Color c2 = bbs.getPixel(20, 20);
assertEquals(Color.BLACK, c1);
assertEquals(Color.CYAN, c2);
}
}

View file

@ -0,0 +1,22 @@
function Allocate_Bitmap( width, height )
local bitmap = {}
for i = 1, width do
bitmap[i] = {}
for j = 1, height do
bitmap[i][j] = {}
end
end
return bitmap
end
function Fill_Bitmap( bitmap, color )
for i = 1, #bitmap do
for j = 1, #bitmap[1] do
bitmap[i][j] = color
end
end
end
function Get_Pixel( bitmap, x, y )
return bitmap[x][y]
end

View file

@ -0,0 +1,4 @@
bitmap = Allocate_Bitmap( 100, 50 )
Fill_Bitmap( bitmap, { 15, 200, 80 } )
pixel = Get_Pixel( bitmap, 20, 25 )
print( pixel[1], pixel[2], pixel[3] )

View file

@ -0,0 +1,159 @@
%Bitmap class
%
%Implements a class to manage bitmap images without the need for the
%various conversion and display functions
%
%Available functions:
%
%fill(obj,color)
%setPixel(obj,pixel,color)
%getPixel(obj,pixel,[optional: color channel])
%display(obj)
%disp(obj)
%plot(obj)
%image(obj)
%save(obj)
%open(obj)
classdef Bitmap
%% Public Properties
properties
%Channel arrays
red;
green;
blue;
end
%% Public Methods
methods
%Creates image and defaults it to black
function obj = Bitmap(width,height)
obj.red = zeros(height,width,'uint8');
obj.green = zeros(height,width,'uint8');
obj.blue = zeros(height,width,'uint8');
end % End Bitmap Constructor
%Fill the image with a specified color
%color = [red green blue] max for each is 255
function fill(obj,color)
obj.red(:,:) = color(1);
obj.green(:,:) = color(2);
obj.blue(:,:) = color(3);
assignin('caller',inputname(1),obj); %saves the changes to the object
end
%Set a pixel to a specified color
%pixel = [x y]
%color = [red green blue]
function setPixel(obj,pixel,color)
obj.red(pixel(2),pixel(1)) = color(1);
obj.green(pixel(2),pixel(1)) = color(2);
obj.blue(pixel(2),pixel(1)) = color(3);
assignin('caller',inputname(1),obj); %saves the changes to the object
end
%Get pixel color
%pixel = [x y]
%varargin can be:
% no input for all channels
% 'r' or 'red' for red channel
% 'g' or 'green' for green channel
% 'b' or 'blue' for blue channel
function color = getPixel(obj,pixel,varargin)
if( ~isempty(varargin) )
switch (varargin{1})
case {'r','red'}
color = obj.red(pixel(2),pixel(1));
case {'g','green'}
color = obj.red(pixel(2),pixel(1));
case {'b','blue'}
color = obj.red(pixel(2),pixel(1));
end
else
color = [obj.red(pixel(2),pixel(1)) obj.green(pixel(2),pixel(1)) obj.blue(pixel(2),pixel(1))];
end
end
%Display the image
%varargin can be:
% no input for all channels
% 'r' or 'red' for red channel
% 'g' or 'green' for green channel
% 'b' or 'blue' for blue channel
function display(obj,varargin)
if( ~isempty(varargin) )
switch (varargin{1})
case {'r','red'}
image(obj.red)
case {'g','green'}
image(obj.green)
case {'b','blue'}
image(obj.blue)
end
colormap bone;
else
bitmap = cat(3,obj.red,obj.green,obj.blue);
image(bitmap);
end
end
%Overload several commonly used display functions
function disp(obj,varargin)
display(obj,varargin{:});
end
function plot(obj,varargin)
display(obj,varargin{:});
end
function image(obj,varargin)
display(obj,varargin{:});
end
%Saves the image
function save(obj)
%Open file dialogue
[fileName,pathName,success] = uiputfile({'*.bmp','Bitmap Image (*.bmp)'},'Save Bitmap As');
if( not(success == 0) )
imwrite(cat(3,obj.red,obj.green,obj.blue),[pathName fileName],'bmp'); %Write image file to disk
disp('Save Complete');
end
end
%Opens an image and overwrites what is currently stored
function success = open(obj)
%Open file dialogue
[fileName,pathName,success] = uigetfile({'*.bmp','Bitmap Image (*.bmp)'},'Open Bitmap ');
if( not(success == 0) )
channels = imread([pathName fileName], 'bmp'); %returns color indexed data
%Store each channel
obj.red = channels(:,:,1);
obj.green = channels(:,:,2);
obj.blue = channels(:,:,3);
assignin('caller',inputname(1),obj); %saves the changes to the object
success = true;
return
else
success = false;
return
end
end
end %methods
end %classdef

View file

@ -0,0 +1,18 @@
>> img = Bitmap(20,30);
>> img.fill([30 30 150]);
>> img.setPixel([10 15],[20 130 66]);
>> disp(img)
>> img.getPixel([10 15])
ans =
20 130 66
>> img.getPixel([10 15],'red')
ans =
20
>> img.save()
Save Complete

View file

@ -0,0 +1,39 @@
class Bitmap {
public $data;
public $w;
public $h;
public function __construct($w = 16, $h = 16){
$white = array_fill(0, $w, array(255,255,255));
$this->data = array_fill(0, $h, $white);
$this->w = $w;
$this->h = $h;
}
//Fills a rectangle, or the whole image with black by default
public function fill($x = 0, $y = 0, $w = null, $h = null, $color = array(0,0,0)){
if (is_null($w)) $w = $this->w;
if (is_null($h)) $h = $this->h;
$w += $x;
$h += $y;
for ($i = $y; $i < $h; $i++){
for ($j = $x; $j < $w; $j++){
$this->setPixel($j, $i, $color);
}
}
}
public function setPixel($x, $y, $color = array(0,0,0)){
if ($x >= $this->w) return false;
if ($x < 0) return false;
if ($y >= $this->h) return false;
if ($y < 0) return false;
$this->data[$y][$x] = $color;
}
public function getPixel($x, $y){
return $this->data[$y][$x];
}
}
$b = new Bitmap(16,16);
$b->fill();
$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)

View file

@ -0,0 +1,27 @@
#! /usr/bin/perl
use strict;
use Image::Imlib2;
# create the "canvas"
my $img = Image::Imlib2->new(200,200);
# fill with a plain RGB(A) color
$img->set_color(255, 0, 0, 255);
$img->fill_rectangle(0,0, 200, 200);
# set a pixel to green (at 40,40)
$img->set_color(0, 255, 0, 255);
$img->draw_point(40,40);
# "get" pixel rgb(a)
my ($red, $green, $blue, $alpha) = $img->query_pixel(40,40);
undef $img;
# another way of creating a canvas with a bg colour (or from
# an existing "raw" data)
my $col = pack("CCCC", 255, 255, 0, 0); # a, r, g, b
my $img = Image::Imlib2->new_using_data(200, 200, $col x (200 * 200));
exit 0;

View file

@ -0,0 +1,17 @@
# Create an empty image of 120 x 90 pixels
(setq *Ppm (make (do 90 (link (need 120)))))
# Fill an image with a given color
(de ppmFill (Ppm R G B)
(for Y Ppm
(map
'((X) (set X (list R G B)))
Y ) ) )
# Set pixel with a color
(de ppmSetPixel (Ppm X Y R G B)
(set (nth Ppm Y X) (list R G B)) )
# Get the color of a pixel
(de ppmGetPixel (Ppm X Y)
(get Ppm Y X) )

19
Task/Bitmap/R/bitmap.r Normal file
View file

@ -0,0 +1,19 @@
# See the class definitions and constructors with, e.g.
getClass("pixmapIndexed", package=pixmap)
pixmapIndexed
# Image with all one colour
plot(p1 <- pixmapIndexed(matrix(0, nrow=3, ncol=4), col="red"))
# Image with one pixel specified
cols <- rep("blue", 12); cols[7] <- "red"
plot(p2 <- pixmapIndexed(matrix(1:12, nrow=3, ncol=4), col=cols))
# Retrieve colour of a pixel
getcol <- function(pm, i, j)
{
pmcol <- pm@col
dim(pmcol) <- dim(pm@index)
pmcol[i,j]
}
getcol(p2, 3, 4) #red

View file

@ -0,0 +1,35 @@
/*REXX program shows how to handle a simple RGB raster graphics image. */
image.='00 00 00'x /*set entire array to hex zeroes.*/
red='00000000 00000000 11111111'b /*define a red value. */
image.=red /*set the entire array to red. */
blue='11111111 00000000 00000000'b /*define a blue value. */
blue='ff 00 00'x /*another way to define blue. */
image.10.40=blue /*set a particular pixel. */
x=20
y=50
aPIXcolor=image.x.y /*obtain the color of a pixel. */
hexv=c2x(aPixcolor) /*get the binary value of 20,50. */
binv=x2b(hexv) /*get the binary value of 20,50. */
say 'pixel' x","y '=' binv /*show the binary value of 20,50 */
bin3v=left(binv,8) substr(binv,9,8) right(binv,8)
say 'pixel' x","y '=' bin3v /*show again, but with spaces. */
say 'pixel' x","y '=' hexv /*show again, but in hexadecimal.*/
hex3v=left(hexv,2) substr(hexv,3,2) right(hexv,2)
say 'pixel' x","y '=' hex3v /*show again, but with spaces. */
RGB= /*start with a clean slate. */
xSize=500 /*size of the X axis. */
YSize=800 /* " " " Y " */
do x=1 to xSize
do y=1 to Ysize
RGB=RGM || image.x.y /*build RBG one pixel at a time.*/
end /*y*/
end /*x*/
return RGM /*return the RGB image to invoker*/

View file

@ -0,0 +1,41 @@
#lang racket
;; The racket/draw libraries provide imperative drawing functions.
;; http://docs.racket-lang.org/draw/index.html
(require racket/draw)
;; To create an image with width and height, use the make-bitmap
;; function.
;; For example, let's make a small image here:
(define bm (make-bitmap 640 480))
;; We use a drawing context handle, a "dc", to operate on the bitmap.
(define dc (send bm make-dc))
;; We can fill the bitmap with a color by using a combination of
;; setting the background, and clearing.
(send dc set-background (make-object color% 0 0 0)) ;; Color it black.
(send dc clear)
;; Let's set a few pixels to a greenish color with set-pixel:
(define aquamarine (send the-color-database find-color "aquamarine"))
(for ([i 480])
(send dc set-pixel i i aquamarine))
;; We can get at the color of a bitmap pixel by using the get-pixel
;; method. However, it may be faster to use get-argb-pixels if we
;; need a block of the pixels. Let's use get-argb-pixels and look
;; at a row starting at (0, 42)
(define buffer (make-bytes (* 480 4))) ;; alpha, red, green, blue
(send dc get-argb-pixels 0 42 480 1 buffer)
;; We can inspect the buffer
(bytes-ref buffer 0) ;; and see that the first pixel's alpha is 255,
(bytes-ref buffer 1) ;; and the red, green, and blue components are 0.
(bytes-ref buffer 2)
(bytes-ref buffer 3)
;; If we are using DrRacket, we can just print the bm as a toplevel expression
;; to view the final image:
bm

View file

@ -0,0 +1,49 @@
class RGBColour
def initialize(red, green, blue)
unless red.between?(0,255) and green.between?(0,255) and blue.between?(0,255)
raise ArgumentError, "invalid RGB parameters: #{[red, green, blue].inspect}"
end
@red, @green, @blue = red, green, blue
end
attr_reader :red, :green, :blue
alias_method :r, :red
alias_method :g, :green
alias_method :b, :blue
RED = RGBColour.new(255,0,0)
GREEN = RGBColour.new(0,255,0)
BLUE = RGBColour.new(0,0,255)
BLACK = RGBColour.new(0,0,0)
WHITE = RGBColour.new(255,255,255)
end
class Pixmap
def initialize(width, height)
@width = width
@height = height
@data = fill(RGBColour::WHITE)
end
attr_reader :width, :height
def fill(colour)
@data = Array.new(@width) {Array.new(@height, colour)}
end
def validate_pixel(x,y)
unless x.between?(0, @width-1) and y.between?(0, @height-1)
raise ArgumentError, "requested pixel (#{x}, #{y}) is outside dimensions of this bitmap"
end
end
def [](x,y)
validate_pixel(x,y)
@data[x][y]
end
alias_method :get_pixel, :[]
def []=(x,y,colour)
validate_pixel(x,y)
@data[x][y] = colour
end
alias_method :set_pixel, :[]=
end

View file

@ -0,0 +1,15 @@
import java.awt.image.BufferedImage
import java.awt.Color
class RgbBitmap(val width:Int, val height:Int) {
val image=new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
def fill(c:Color)={
val g=image.getGraphics()
g.setColor(c)
g.fillRect(0, 0, width, height)
}
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))
}

View file

@ -0,0 +1,8 @@
val img=new RgbBitmap(50, 50);
img.fill(Color.CYAN)
img.setPixel(5, 5, Color.BLUE)
assert(img.getPixel(1,1)==Color.CYAN)
assert(img.getPixel(5,5)==Color.BLUE)
assert(img.width==50)
assert(img.height==50)

View file

@ -0,0 +1,18 @@
(define (make-list length object)
(if (= length 0)
(list)
(cons object (make-list (- length 1) object))))
(define (list-fill! list object)
(if (not (null? list))
(begin (set-car! list object) (list-fill! (cdr list) object))))
(define (list-set! list element object)
(if (= element 1)
(set-car! list object)
(list-set! (cdr list) (- element 1) object)))
(define (list-get list element)
(if (= element 1)
(car list)
(list-get (cdr list) (- element 1))))

View file

@ -0,0 +1,14 @@
(define (make-image columns rows)
(if (= rows 0)
(list)
(cons (make-list columns (list)) (make-image columns (- rows 1)))))
(define (image-fill! image colour)
(if (not (null? image))
(begin (list-fill! (car image) colour) (image-fill! (cdr image) colour))))
(define (image-set! image column row colour)
(list-set! (list-get image row) column colour))
(define (image-get image column row)
(list-get (list-get image row) column))

View file

@ -0,0 +1,5 @@
(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))

View file

@ -0,0 +1,5 @@
(define image (make-image 3 2))
(image-fill! image *black*)
(image-set! image 2 1 *blue*)
(display image)
(newline)

View file

@ -0,0 +1 @@
(((0 0 0) (0 0 255) (0 0 0)) ((0 0 0) (0 0 0) (0 0 0)))

View file

@ -0,0 +1,30 @@
package require Tcl 8.5
package require Tk
namespace path ::tcl::mathfunc ;# for [max] function
proc newImage {width height} {
return [image create photo -width $width -height $height]
}
proc fill {image colour} {
$image put $colour -to 0 0 [$image cget -width] [$image cget -height]
}
proc setPixel {image colour point} {
lassign $point x y
$image put $colour -to [max 0 $x] [max 0 $y]
}
proc getPixel {image point} {
lassign $point x y
# [$img get] returns a list: {r g b}; this proc should return a colour value
format {#%02x%02x%02x} {*}[$image get $x $y]
}
# create the image and display it
set img [newImage 150 150]
label .l -image $img
pack .l
fill $img red
setPixel $img green {40 40}
set rbg [getPixel $img {40 40}]