Skip to content

Instantly share code, notes, and snippets.

@speeddragon
Last active October 18, 2018 11:21
Show Gist options
  • Save speeddragon/e836b64cff8a39f537078fa507a32e5b to your computer and use it in GitHub Desktop.
Save speeddragon/e836b64cff8a39f537078fa507a32e5b to your computer and use it in GitHub Desktop.
Image Validation in Elixir
defmodule ImageValidation do
@doc """
JPG magic bytes: 0xffd8
"""
@spec is_jpg?(binary()) :: boolean()
def is_jpg?(file) do
with <<head::binary-size(2)>> <> _ = file.binary,
<<255, 216>> <- head do
true
else
_ -> false
end
end
@spec is_jpg_by_filepath?(String.t()) :: boolean()
def is_jpg_by_filepath(file) do
with {:ok, file_content} <- :file.open(file, [:read, :binary]),
{:ok, <<255, 216>>} <- :file.read(file_content, 2) do
true
else
_error ->
false
end
end
@doc """
PNG magic bytes: 0x89504e470d0a1a0a
"""
@spec is_png?(binary()) :: boolean()
def is_png?(file) do
with <<head::binary-size(8)>> <> _ = file.binary,
<<137, 80, 78, 71, 13, 10, 26, 10>> <- head do
true
else
_ -> false
end
end
@spec is_png_by_filepath?(String.t()) :: boolean()
def is_png_by_filepath(file) do
with {:ok, file_content} <- :file.open(file, [:read, :binary]),
{:ok, <<137, 80, 78, 71, 13, 10, 26, 10>>} <- :file.read(file_content, 8) do
true
else
_error ->
false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment