我正在阅读the documentation for the Graphics module,并且没有任何关于从文件加载图像的信息,只有彩色数据。我该怎么做呢?例如,假设我有file.png
,并且我希望在(x, y)
度旋转的坐标z
上绘制它。
答案 0 :(得分:2)
camlimages库可以加载png文件(如果它们没有以RGBA或CMYK格式表示)。一个简单的例子:
open Images
let () = Graphics.open_graph "";;
let img = Png.load "png.png" [];;
let g = Graphic_image.of_image img;;
Graphics.draw_image g 0 0;;
Unix.sleep 10;;
运行:
opam install graphics camlimages
ocamlfind ocamlc -o test -package graphics -package unix \
-package camlimages.png -package camlimages.graphics \
-linkpkg test.ml
wget https://bytebucket.org/camlspotter/camlimages/raw/1611545463f493462aeafab65839c1112162559a/test/images/png.png
./test
(基于example in the library source code。)
但是,我不认为camlimages可以旋转pngs。您可以滚动自己的旋转功能(改编自Mortimer's code on Dr. Dobb's):
let rotate src dst angle =
let sh, sw = Array.(float (length src), float (length src.(0))) in
let dh, dw = Array.(length dst, length dst.(0)) in
let dx, dy = float dw /. 2., float dh /. 2. in
let scale = min (float dh /. sh) (float dw /. sw) in
let duCol = sin(-.angle) *. (1. /. scale) in
let dvCol = cos(-.angle) *. (1. /. scale) in
let rec col dst x u v =
if x < dw then (
dst.(x) <- if (0. <= u && u < sw) && (0. <= v && v < sh)
then src.(truncate v).(truncate u)
else Graphics.white;
col dst (x + 1) (u +. dvCol) (v -. duCol))
in
let rec row y rowu rowv =
if y < dh then (col dst.(y) 0 rowu rowv;
row (y + 1) (rowu +. duCol) (rowv +. dvCol))
in
row 0 ((sw /. 2.) -. (dx *. dvCol +. dy *. duCol))
((sh /. 2.) -. (dx *. (-.duCol) +. dy *. dvCol))
并使用
从上面的示例代码中调用它let dg = Graphics.dump_image g
let dgr =Array.(make_matrix (length dg) (length dg.(0)) Graphics.white);;
rotate dg dgr (4. *. atan 1. /. 2);;
let g = Graphics.make_image dgr;;
或者,您可以使用类似OCamlSDL的Sdlgfx.rotozoomSurface
功能。
一个简单的例子:
let png = Sdlloader.load_image "png.png"
let png_rot = Sdlgfx.rotozoomSurface png 45.0 1.0 true;;
Sdl.init [`VIDEO];;
let screen = Sdlvideo.set_video_mode ~w:250 ~h:166 [];;
Sdlvideo.(blit_surface ~dst_rect:{ r_x = 0; r_y = 0; r_w = 250; r_h = 166}
~src:png_rot ~dst:screen ());;
Sdlvideo.flip screen;
Sdltimer.delay 10000;
Sdl.quit ();;
在您的系统上安装适当的SDL软件包后(并不总是那么简单......),运行:
opam install ocamlsdl
ocamlfind ocamlc -o test -package sdl -package sdl.sdlimage \
-package sdl.sdlgfx -linkpkg test.ml
./test