PhoenixImage

An on-demand image optimization library for Phoenix applications. phx_image provides a Plug that fetches source images, resizes/transcodes them, and serves them with caching headers. It also provides a Next.js-like <.image /> function component for Phoenix templates.

Features

Installation

The package can be installed by adding phx_image to your list of dependencies in mix.exs:

def deps do
  [
    {:phx_image, "~> 0.1.0"}
  ]
end

PhoenixImage.Component depends on :phoenix_live_view. Add it explicitly if you use the component:

def deps do
  [
    {:phx_image, "~> 0.1.0"},
    {:phoenix_live_view, "~> 1.0"}
  ]
end

Usage

Demo App

This repo includes a Phoenix demo app in demo/ for manual testing.

cd demo
mix deps.get
mix phx.server

Open http://localhost:4000 and use the form to test /images/optimize.

As a Plug

You can mount the PhoenixImage.Plug in your Phoenix router or as part of a standalone Plug pipeline:

# In your router.ex
scope "/images" do
  pipe_through :browser
  get "/optimize", PhoenixImage.Plug, []
end

As a Component (<.image />)

Add to your Phoenix components module:

defmodule MyAppWeb.CoreComponents do
  use Phoenix.Component
  import PhoenixImage.Component, only: [image: 1]
end

Use in HEEx:

<.image
  src="https://example.com/photo.jpg"
  alt="Scenic view"
  width={1200}
  height={800}
  sizes="100vw"
/>

Required sizing rule:

Configure component defaults:

config :phx_image, :image_component,
  optimize_path: "/images/optimize",
  device_sizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
  image_sizes: [16, 32, 48, 64, 96, 128, 256, 384],
  allowed_hosts: ["example.com", "cdn.example.com"]

Plug Options

PhoenixImage.Plug supports:

Query Parameters

Resize Behavior

Example

Requesting a 400px wide WebP version of an external image:

GET /images/optimize?src=https://example.com/large-photo.jpg&w=400&f=webp

The response will include:

Relative src Example

GET /images/optimize?src=/images/logo.png&w=320

Error Semantics

Requirements

Compatibility

Security Notes

License

Apache-2.0. See LICENSE.

Documentation can be generated locally with:

mix docs

Docs are published automatically to GitLab Pages from the default branch.

Releasing

Use the custom task to run preflight checks, tag, push, and publish:

mix release.publish --yes

Useful flags: