Skip to content

gungun974/bun-image-transform

Repository files navigation

Logo

Bun Image Transform

Powered by sharp and libvips.

What is Bun Image Transform ?

Bun Image Transform is a plugin for the Bun Bundler and Runtime capable of transforming an image upon import.

By default, Bun allows you to import and retrieve the file path, but sometimes you may want to import a high-resolution image directly from the source code, apply effects, and then compress it.

Bun Image Transform allows you to do exactly this.

How to installed it

You will first need to install the package with Bun.

bun install bun-image-transform

Next, in your tsconfig.json file, you will need to add the library's typings to avoid "module not found" errors.

  {
    "compilerOptions": {
      "types": [
        // other packages, e.g. "bun-types",
+       "bun-image-transform"
      ]
    }
  }

ESBuild

Since version v1.1.0. This Plugin has compatibility with ESBuild if you prefer ESBuild. If you used the default import you would automatically use the correct Plugin however you can use ESBuildImageTransformPlugin if you prefer named import.

Usages

Runtime usage

To use as a runtime plugin, create a file that registers the plugin:

// preload.ts
import BunImageTransformPlugin from "bun-image-transform";

Bun.plugin(BunImageTransformPlugin());

Then preload it in your bunfig.toml:

preload = ["./preload.ts"]

Bundler usage

To use this plugin, you will need to add it to your Bun build step.

import BunImageTransformPlugin from "bun-image-transform";

Bun.build({
  entrypoints: ["./index.ts"],
  // other config

  plugins: [BunImageTransformPlugin()],
});

Code usage

To use it in your code once the plugin is activated, you will simply need to load an image file as usual, with the exception that you will need to add modifiers like ?width=128&bunimg after the file extension.

This syntax is similar to what one might find in the parameters of an HTTP GET method, but there is two major differences.

  1. The order matters
  2. You can repeat the modifiers

Also, some modifiers like format can receive information from special modifiers called "flags" that are placed only behind them.

import bunLogo from "./bun-logo.png?format=jpeg&bunimg";

console.log(bunLogo);

You can also use if you want require and await import()

require("./bun-logo.png?format=webp&bunimg");

await import("./bun-logo.png?quality=75&format=jpg&bunimg");

Important : You can't use dot to write number like 0.5 you must use commas like 0,5 or the file will not be resolve correctly

Note : Even though it's possible to transform an image with an await import, don't forget that the API remains limited in complex modifications, and you can simply perform the dynamic image transformations yourself using sharp directly.

Modifiers

Bun Image Transform works by using the Node image processing library, sharp. Therefore, the available modifiers are directly taken from the sharp documentation.

Property Docs Example Comments
width Docs ./bun-logo.png?width=128&bunimg See enlarge modifier.
height Docs ./bun-logo.png?height=128&bunimg See enlarge modifier.
resize Docs ./bun-logo.png?resize=128x128_#ffffff&bunimg The background color of the resize is optional. See enlarge, kernel, fit and position modifiers.
trim Docs ./bun-logo.png?trim&bunimg
extend Docs ./bun-logo.png?extend={top}_{right}_{bottom}_{left}_[color]&bunimg Extend / pad / extrude one or more edges of the image with either the provided background color or pixels derived from the image. The background color is optional
extract Docs ./bun-logo.png?extract={left}_{top}_{width}_{height}&bunimg Extract/crop a region of the image.
format Docs ./bun-logo.png?format=png&bunimg Supported format: png, jpg, jpeg, webp, avif, gif, heif and tiff
rotate Docs ./bun-logo.png?rotate=45&bunimg
flip Docs ./bun-logo.png?flip&bunimg
flop Docs ./bun-logo.png?flop&bunimg
sharpen Docs ./bun-logo.png?sharpen=30&bunimg
median Docs ./bun-logo.png?median=10&bunimg
blur Docs ./bun-logo.png?blur=5&bunimg
gamma Docs ./bun-logo.png?gamma=3&bunimg
negate Docs ./bun-logo.png?negate&bunimg
normalize Docs ./bun-logo.png?normalize&bunimg
threshold Docs ./bun-logo.png?threshold=10&bunimg
tint Docs ./bun-logo.png?tint=#00ff00&bunimg
grayscale Docs ./bun-logo.png?grayscale&bunimg You can also use "greyscale" as a word.
modulate Docs ./bun-logo.png?brightness=2&modulate&bunimg See brightness, hue, lightness and saturation flags.
render _ ./bun-logo.png?trim&render&rotate=90&bunimg Apply all the previous modifiers and flatten them in this way. Use only when needed, as the transformed image will be stored in memory in a Buffer.

Flags

Property Docs Example Comments
kernel Docs ./bun-logo.png?kernel=nearest&resize=128x128_#ffffff&bunimg Supported kernel: nearest, cubic, mitchell, lanczos2 and lanczos3 (default), for resize modifier
fit Docs ./bun-logo.png?fit=fit_outside&resize=128x128_#ffffff&bunimg Sets fit option for resize modifier.
position Docs ./bun-logo.png?position=top&resize=128x128_#ffffff&bunimg Sets position option for resize modifier.
enlarge _ ./bun-logo.png?enlarge&resize=1024x1024&bunimg For width, height and resize modifier. Allow the image to be upscaled. By default the returned image will never be larger than the source in any dimension, while preserving the requested aspect ratio.
quality _ ./bun-logo.png?quality=80&format=webp&bunimg For format modifier and accepted values: 0 to 100 and need the format property to be apply
brightness Docs ./bun-logo.png?brightness=2&modulate&bunimg
hue Docs ./bun-logo.png?hue=180&modulate&bunimg
lightness Docs ./bun-logo.png?lightness=50&modulate&bunimg
saturation Docs ./bun-logo.png?saturation=0,5&modulate&bunimg

Settings

By default, image files will be generated in the .cache folder. You can modify this behavior with the parameter below.

BunImageTransformPlugin({
  outputDirectory: "customOutputFolder",
});

There are two more advanced options that allow you to disable the default behavior of the file loader and return a relative path to the output folder.

This behavior is perfectly suitable if you have a public folder on a web server where you want to directly place the generated images and work with the relative paths of that public folder.

BunImageTransformPlugin({
  outputDirectory: "./build/public/img/",
  useRelativePath: true,
  prefixRelativePath: "img/",
});

Credits

This project would not be possible without Bun inspiring me to create this plugin.

To the project also Sharp for making it easy to transform and convert images.

And to the high-performance, secure, and easy-to-use image optimizer server, IPX, which greatly inspired the syntax of the modifiers and usage.

Experimental

This project has a command line to transform bunimg:// urls like the plugin does directly but in a file. This Command Line is not yet documented because it remains experimental.

License

MIT

About

A bun plugin to import and transform image on the go

Resources

License

Stars

Watchers

Forks

Packages

No packages published