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 automatic image detection #264

Merged
merged 6 commits into from
Mar 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
15 changes: 15 additions & 0 deletions lib/kino/render.ex
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,18 @@ defimpl Kino.Render, for: PID do
end
end
end

defimpl Kino.Render, for: BitString do
def to_livebook(string) do
case Kino.Utils.get_image_type(string) do
nil ->
Kino.Output.inspect(string)

type ->
raw = Kino.Inspect.new(string)
image = Kino.Image.new(string, type)
tabs = Kino.Layout.tabs(Image: image, Raw: raw)
Kino.Render.to_livebook(tabs)
end
end
end
14 changes: 14 additions & 0 deletions lib/kino/utils.ex
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,18 @@ defmodule Kino.Utils do
do: true,
else: (_ -> false)
end

@doc """
Determines image type looking for the magic number in the binary.
"""
@spec get_image_type(binary()) :: Kino.Image.common_image_type() | nil
def get_image_type(<<0xFF, 0xD8, 0xFF, 0xE0, _rest::binary>>), do: :jpeg
def get_image_type(<<0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, _rest::binary>>), do: :png
def get_image_type(<<0x3C, 0x3F, 0x78, 0x6D, 0x6C, 0x20, _rest::binary>>), do: :svg

def get_image_type(<<0x47, 0x49, 0x46, 0x38, x::8, 0x61, _rest::binary>>)
when x in [0x37, 0x39],
do: :gif

def get_image_type(_image), do: nil
end