Reputation: 14109
I'm reading the documentation for the Graphics module, and there isn't any information on loading images from a file, only from a colour array. How would I go about doing this? For example, suppose I have file.png
, and I want to draw it at co-ordinates (x, y)
with z
degrees rotation.
Upvotes: 2
Views: 2357
Reputation: 1299
The camlimages library can load png files (if they are not represented in RGBA or CMYK format). A simple example:
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;;
To run:
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
(Based on the example in the library source code.)
But, I don't think camlimages can rotate pngs. You could roll your own rotate function (adapted from 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))
And call it from the example code above with
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;;
Or, you could use something like the Sdlgfx.rotozoomSurface
function of OCamlSDL.
A simple example:
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 ();;
After installing the appropriate SDL packages on your system (not always easy...), to run:
opam install ocamlsdl
ocamlfind ocamlc -o test -package sdl -package sdl.sdlimage \
-package sdl.sdlgfx -linkpkg test.ml
./test
Upvotes: 3