Skip to content

Instantly share code, notes, and snippets.

@voluntas
Last active May 26, 2017 05:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save voluntas/be3929379c56d1bd9df527c625916c09 to your computer and use it in GitHub Desktop.
Save voluntas/be3929379c56d1bd9df527c625916c09 to your computer and use it in GitHub Desktop.
webp parser/builder (sample)
-module(webp).
-export([parse/0, parse/1]).
-export([build/1]).
-include_lib("eunit/include/eunit.hrl").
-define(MAX_SIZE, 4294967274).
%% http://www-2.cs.cmu.edu/~chuck/lennapg/lena_std.tif
%% $ cwebp -q 80 lena_std.tif -o lena_std.webp
%% https://developers.google.com/speed/webp/docs/riff_container
%% Erlang/OTP 19 [erts-8.0.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false] [dtrace] [sharing-preserving]
%%
%% Eshell V8.0.2 (abort with ^G)
%% 1> c(webp).
%% {ok,webp}
%% 2> webp:parse().
%% webp.erl:24:<0.57.0>: ChunkSize = 30214
%% webp.erl:25:<0.57.0>: Size = 30202
%% webp.erl:
parse() ->
parse("lena_std.webp").
parse(Filename) ->
{ok, Binary} = file:read_file(Filename),
parse_header(Binary).
parse_header(<<"RIFF",
ChunkSize:32/unsigned-little,
"WEBP",
"VP8 ",
Size:32/unsigned-little,
_Rest/binary>>) ->
?debugVal(ChunkSize),
?debugVal(Size),
?debugVal(byte_size(_Rest)),
ok.
%% @mururu
-spec build(binary()) -> {ok, binary()} | {error, too_large_image}.
build(Binary) ->
case byte_size(Binary) of
Size when Size =< ?MAX_SIZE ->
{ok, <<"RIFF",
(Size + 12):32/unsigned-little,
"WEBP",
"VP8 ",
Size:32/unsigned-little,
Binary/binary>>};
_ ->
{error, too_large_image}
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment