PlugImageProcessing is published on Hex. Add it to your list of dependencies in mix.exs:
# mix.exs
def deps do
[
{:plug_image_processing, ">= 0.0.1"}
]
endThen run mix deps.get to install the package and its dependencies.
To expose a /imageproxy route, add the plug in your endpoint, before your router plug, but after Plug.Parsers:
# lib/my_app_web/endpoint.ex
plug(PlugImageProcessing.Web, path: "/imageproxy")
#...
plug(MyAppWeb.Router)A single source for image is supported for now: the url query parameter.
/imageproxy/resize?url=https://s3.ca-central-1.amazonaws.com/my_image.jpg&width=300It will download the image from the remote location, modify it using libvips and return it to the client.
A number of operations exposed by libvips are supported by PlugImageProcessing. See the PlugImageProcessing.Operations.* module for more details.
Validations can be added so your endpoint is more secure.
By adding a signature key in your config, a parameter sign needs to be included in the URL to validate the payload.
The signature prevent a client to forge a large number of unique requests that would go through the CDN and hitting our server.
plug(PlugImageProcessing.Web, url_signature_key: "1234")Then a request path like:
/imageproxy/resize?url=https://s3.ca-central-1.amazonaws.com/my_image.jpg&width=300&quality=60will fail because the sign parameter is not present.
The HMAC-SHA256 hash is created by taking the URL path (excluding the leading /), the request parameters (alphabetically-sorted and concatenated with & into a string). The hash is then base64url-encoded.
Base.url_encode64(:crypto.mac(:hmac, :sha256, "1234", "resize" <> "quality=60&url=https://s3.ca-central-1.amazonaws.com/my_image.jpg&width=300"))
# => "ku5SCH56vrsqEr-_VRDOFJHqa6AXslh3fpAelPAPoeI="Now this request will succeed!
/imageproxy/resize?url=https://s3.ca-central-1.amazonaws.com/my_image.jpg&width=300&quality=60&sign=ku5SCH56vrsqEr-_VRDOFJHqa6AXslh3fpAelPAPoeI=PlugImageProcessing is © 2022 Mirego and may be freely distributed under the New BSD license. See the LICENSE.md file.
Mirego is a team of passionate people who believe that work is a place where you can innovate and have fun. We’re a team of talented people who imagine and build beautiful Web and mobile applications. We come together to share ideas and change the world.
We also love open-source software and we try to give back to the community as much as we can.
