Skip to content

Instantly share code, notes, and snippets.

@pbouffard
Last active November 7, 2020 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pbouffard/3d48d3c47d9bd70e7c9f52f984d14245 to your computer and use it in GitHub Desktop.
Save pbouffard/3d48d3c47d9bd70e7c9f52f984d14245 to your computer and use it in GitHub Desktop.
Array as image in Pluto
### A Pluto.jl notebook ###
# v0.12.4
using Markdown
using InteractiveUtils
# ╔═╡ 9f663af6-2112-11eb-0b66-3f380137db7b
begin
struct BWImage
data::Array{UInt8, 2}
zoom::Int
end
function BWImage(data::Array{T, 2}; zoom::Int=1) where T <: Real
BWImage(floor.(UInt8, clamp.(((data .- minimum(data)) / (maximum(data) .- minimum(data))) * 255, 0, 255)), zoom)
end
import Base: show
function show(io::IO, ::MIME"image/bmp", i::BWImage)
orig_height, orig_width = size(i.data)
height, width = (orig_height, orig_width) .* i.zoom
datawidth = Integer(ceil(width / 4)) * 4
bmp_header_size = 14
dib_header_size = 40
palette_size = 256 * 4
data_size = datawidth * height * 1
# BMP header
write(io, 0x42, 0x4d)
write(io, UInt32(bmp_header_size + dib_header_size + palette_size + data_size))
write(io, 0x00, 0x00)
write(io, 0x00, 0x00)
write(io, UInt32(bmp_header_size + dib_header_size + palette_size))
# DIB header
write(io, UInt32(dib_header_size))
write(io, Int32(width))
write(io, Int32(-height))
write(io, UInt16(1))
write(io, UInt16(8))
write(io, UInt32(0))
write(io, UInt32(0))
write(io, 0x12, 0x0b, 0x00, 0x00)
write(io, 0x12, 0x0b, 0x00, 0x00)
write(io, UInt32(0))
write(io, UInt32(0))
# color palette
write(io, [[x, x, x, 0x00] for x in UInt8.(0:255)]...)
# data
padding = fill(0x00, datawidth - width)
for y in 1:orig_height
for z in 1:i.zoom
line = vcat(fill.(i.data[y,:], (i.zoom,))...)
write(io, line, padding)
end
end
end
end
# ╔═╡ a928879a-2112-11eb-01c3-834421d011dc
BWImage(randn(30,30), zoom=5)
# ╔═╡ Cell order:
# ╠═a928879a-2112-11eb-01c3-834421d011dc
# ╠═9f663af6-2112-11eb-0b66-3f380137db7b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment