从Ocaml Graphics中的文件加载图像



我正在阅读图形模块的文档,没有任何关于从文件加载图像的信息,只能从颜色数组加载图像。我将如何做到这一点?例如,假设我有file.png,我想在旋转z度的坐标(x, y)绘制它。

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

(基于库源代码中的示例。

但是,我不认为凸轮图像可以旋转 png。你可以滚动自己的旋转函数(改编自Dr. Dobb上的Mortimer代码(:

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

相关内容

  • 没有找到相关文章