Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HTML support for showing images #49

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/ImageShow.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module ImageShow

import Base64
using FileIO
using ImageCore, OffsetArrays
import ImageBase: restrict
Expand Down
26 changes: 26 additions & 0 deletions src/showmime.jl
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,29 @@ end

_length1(A::AbstractArray) = length(eachindex(A))
_length1(A) = length(A)



const _HTML_IMAGE_MIMES = [
MIME("image/jpg"),
MIME("image/png"),
]

function Base.show(io::IO, ::MIME"text/html", img::ColorantMatrix)
_show_image_html(io, _HTML_IMAGE_MIMES, img)
end

function _show_image_html(io, mimes::Vector{<:MIME}, x)
for mime in _HTML_IMAGE_MIMES
lorenzoh marked this conversation as resolved.
Show resolved Hide resolved
if showable(mime, x)
_show_image_html(io, mime, x)
break
end
end
end

function _show_image_html(io, mime::MIME{Name}, x) where Name
buf = IOBuffer()
show(buf, mime, x)
print(io, """<img src="data:""", Name, ";base64,", Base64.base64encode(take!(buf)), "\" />")
end
9 changes: 9 additions & 0 deletions test/writemime.jl
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,15 @@ end
end
@test load(fn) == A[[1,1,2,2],[1,1,2,2]]
end
@testset "HTML display" begin
sshow(mime, x) = (io = IOBuffer(); show(io, mime, x); String(take!(io)))
@test startswith(
sshow(MIME("text/html"), zeros(Gray{Float32}, 1, 1)),
"<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAAAAABV")
@test startswith(
sshow(MIME("text/html"), zeros(RGB{Float32}, 1, 1)),
"<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/")
end
end
try
# if this fails, it is not our fault
Expand Down