Created
July 8, 2016 00:23
-
-
Save henricavalcante/4e62fca00eb7262d7a08e54abf856c07 to your computer and use it in GitHub Desktop.
Bitmap generator in erlang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(bmp). | |
-export([generate/0, header/2, i/2, c/1]). | |
header(FileSz, Offset) -> | |
<< | |
"BM", | |
FileSz:32/little, | |
0:32, | |
Offset:32/little | |
>>. | |
info(Width,Height,ImageSize) -> | |
<< | |
40:32/little, % Header size | |
Width:32/little, | |
Height:32/little, | |
1:16/little, % Planes | |
24:16/little, % Bits per pixel | |
0:32/little, % Compression | |
ImageSize:32/little, | |
0:32/little, % X Pixels per meter | |
0:32/little, % Y Pixels per meter | |
0:32/little, % Colors in color table | |
0:32/little % Important color count | |
>>. | |
padpx(N) when (N * 3) rem 4 =:= 0 -> 0; | |
padpx(N) -> 4 - ((N * 3) rem 4). | |
padrow(R, W) -> [R| lists:duplicate(padpx(W),0)]. | |
generate() -> | |
W = 3, | |
H = 3, | |
Matrix = [ | |
[<<213, 45, 133>>,<<64, 76, 32>>, <<0, 0, 0>>], | |
[<<76, 0, 0>>, <<234,32, 15>>, <<0, 0, 0>>], | |
[<<76, 0, 0>>, <<234,32, 15>>, <<0, 0, 0>>] | |
], | |
write_image(W, H, l(c(Matrix),1,1,<<128,128,128>>)). | |
write_image(W, H, Matrix) -> | |
MatrixReversed = lists:reverse(Matrix), | |
MatrixPadded = lists:map(fun(R) -> padrow(R,W) end, MatrixReversed), | |
Pixels = erlang:list_to_bitstring(MatrixPadded), | |
PixelsSize = erlang:bit_size(Pixels), | |
Offset = 14 + 40, % Header Size + InfoSize | |
Size = Offset + PixelsSize, | |
Header = header(Size, Offset), | |
Info = info(W, H, PixelsSize), | |
file:write_file("test.bmp", | |
[ | |
Header, | |
Info, | |
Pixels, | |
<<10:8/little>> | |
]). | |
whitePixel() -> <<255,255,255>>. | |
changePixel(L, P, E) -> | |
lists:sublist(L, P-1) ++ [E] ++ lists:nthtail(P,L). | |
% getPixel(Matrix, X, Y) -> | |
% lists:nth(X,lists:nth(Y,Matrix)). | |
% I M N | |
% Create MxN matrix. | |
i(M, N) -> lists:duplicate(N, lists:duplicate(M, whitePixel())). | |
% C | |
% Clean matrix | |
c(Matrix) when is_list(Matrix) -> | |
lists:map(fun(E) -> c(E) end, Matrix); | |
c(_) -> whitePixel(). | |
% L X Y C | |
% color pixel (X,Y) in color C. | |
l(Matrix, X, Y, C) -> | |
lists:sublist(Matrix, Y-1) ++ | |
[changePixel(lists:nth(Y, Matrix), X, C)] ++ | |
lists:nthtail(Y, Matrix). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment