Skip to content

Useful Code Scraps

Dehann Fourie edited this page Aug 24, 2020 · 17 revisions

Plot image in Gadfly

https://github.com/GiovineItalia/Gadfly.jl/issues/288#issuecomment-462754808

Images and Bytes

Converting a Julia image to PNG byte stream

using TestImages
img = testimage("mandrill")

using ImageMagick, FileIO
# convert image
io = IOBuffer()
pngSm = Stream(format"PNG", io)
FileIO.save(pngSm, img)
pngBytes = take!(io)

The png can be converted back to bitmap (array) format:

rgb = ImageMagick.readblob(pngBytes);

using ImageView
imshow(rgb)

Alternatively, ImageMagick/FileIO can work through files for lazy convert:

using FileIO
# Lazy convert to PNG 
save("/tmp/test.png", img)

# Lazy convert to bytes
pngBytes = open(read, "/tmp/test.png")
# alternative
# pngBytes = Vector{UInt8}(undef, stat(f).size ÷ sizeof(UInt8))
# fid = open("/tmp/something.png", "r")
# read!(fid, pngBytes)
# close(fid)

Make Gadfly Movie Video

PL = [Gadfly.plot(y=randn(10), Geom.line) for i in 1:10];

using ImageMagick, RoMEPlotting
PLi = convert.(Matrix{RGB}, PL)

using Images, Caesar
writevideo("/tmp/test.avi", PLi)