Rainer
Elegant way to check filetypes?
Hi
Recently I wanted to check if a File is a Picture, and I don’t like checking just the extension.
So with the help of this:
I came to the following solution:
def is_picture(file) do
{_, content} = :file.open(file, [:read, :binary])
fileHeader = :file.read(content, 8)
:file.close(content)
case fileHeader do
{:ok, <<0xFF, 0xD8, _, _, _, _, _, _>>} -> true #jpg
{:ok, <<0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A>>} -> true #png
{:ok, <<0x47, 0x49, 0x46, 0x38, 0x37, 0x61, _, _>>} -> true #gif standard
{:ok, <<0x47, 0x49, 0x46, 0x38, 0x39, 0x61, _, _>>} -> true #gif animated
_ -> false
end
end
As I’m still not experienced with Elixir, I wonder how would you write such a function in an elegant way?
Most Liked
ityonemo
Assuming you don’t care about false positives and strictly don’t care about corrupted files, looks good. I would advocate using elixir File module (so you don’t have to open, you can go straight to read) instead of erlang :file module and maybe consider putting it in a with statement. Closing the file I’d put either in an after block, or possibly even not bother (when the calling process dies, the file descriptor will be reclaimed)
kokolegorille
Maybe this package can help, if You are on Linux.
Rainer
Thanks for the replies ![]()
I didn’t know about the with statement until now ![]()
Haven’t thought about such a simple solution, also a good idea ![]()
I’ll try to improve my function with your suggestions ![]()







