ImgCf (img_cf v0.3.0)
This module provides a Phoenix Component which provides CDN and on-the-fly image resizing through Cloudflares (CF) Image Resize (IR) service.
Modify your view_helpers function to always import it the img_cf Component:
lib/myapp_web/myapp_web.ex:
defp view_helpers do
...
import ImgCf, only: [img_cf: 1]
end
From the Cloudflare website (https://developers.cloudflare.com/images/image-resizing):
You can resize, adjust quality, and convert images to WebP or AVIF format on demand. Cloudflare will automatically cache every derived image at the edge, so you only need to store one original image at your origin
We need to proxy all our traffic through CF, and then rewrite the image URLs we want to resize. This package makes it very easy:
- Domain must be on Cloudflare.
- In CF Dashboard: proxy all trafic for your domain
- In CF Dashboard: enable the Image Resizing service
- In our Phoenix project: use
<.img_tag src={Routes.static_path(...)} width=400>
Usage of the img_cf
tag is almost similar to just using a regular img
tag, except:
src
is always rewritten to the magic IR url.- If
width
, orheight
is given, they are used for resizing. - A high definition version (
srcset 2x
), is always attempted, unless turned off.
#Example
<.img_cf src={Routes.static_path(...)} />
Cloudflare specific options can be passed into the component with cf
like so:
<.img_cf src={...}
width="400"
cf=[retina: false, use_img_dims: false, sharpen: "3"]
/>
Link to this section Summary
Functions
Doubles the :width, and/or :height if present. Otherwise returns opts
untouched.
HTML image tag that provides image resizing on the fly, with no infrastructure setup.
Rewrite img to on-the-fly CloudFlare Image Resizing via special magic paths: https://developers.cloudflare.com/images/image-resizing
Link to this section Functions
double_or_pop(val)
Specs
double_or_pop(nil | non_neg_integer()) :: :pop | {non_neg_integer(), non_neg_integer()}
get_opts_2x(opts)
Specs
Doubles the :width, and/or :height if present. Otherwise returns opts
untouched.
img_cf(assigns)
HTML image tag that provides image resizing on the fly, with no infrastructure setup.
Either width, height, or srcset is required in opts
.
Recommended ways of usage:
Examples
<.img_cf
src={Routes.static_path(@conn, "/images/foobar.png")}
width: 400
height: 400
cf: [retina: true, width: 400, height: 400]
/>
img_render(assigns)
maybe_merge_img_dim(opts, arg2, arg3)
modify_assigns(assigns)
Specs
Rewrite img to on-the-fly CloudFlare Image Resizing via special magic paths: https://developers.cloudflare.com/images/image-resizing