Bun.Image
Recorded: May 23, 2026, 11:59 p.m.
| Original | Summarized |
Image - BunSkip to main contentBun home pageSearch...⌘KInstall BunSearch...NavigationUtilitiesImageRuntimePackage ManagerBundlerTest RunnerGuidesReferenceBlogFeedbackGet StartedWelcome to BunInstallationQuickstartTypeScriptTypeScript 6 and 7bun initbun createCore RuntimeBun RuntimeWatch ModeDebuggingREPLbunfig.tomlFile & Module SystemFile TypesModule ResolutionJSXAuto-installPluginsFile System RouterHTTP serverServerRoutingCookiesTLSError HandlingMetricsNetworkingFetchWebSocketsTCPUDPDNSData & StorageCookiesFile I/OStreamsBinary DataArchiveSQLSQLiteS3RedisConcurrencyWorkersProcess & SystemEnvironment VariablesShellSpawnWebViewCronInterop & ToolingNode-APIFFIC CompilerTranspilerUtilitiesCSRF ProtectionSecretsConsoleTOMLYAMLMarkdownJSON5JSONLHTMLRewriterImageHashingGlobSemverColorUtilsStandards & CompatibilityGlobalsBun APIsWeb APIsNode.js CompatibilityContributingRoadmapBenchmarkingContributingBuilding WindowsBindgenLicenseOn this pageInputMetadataResizeRotate · flipModulateOutput formatsTerminalsPlaceholdersBun.serve integrationClipboardPlatform backendsUtilitiesImageCopy pageDecode, transform, and encode images with a fast native pipelineCopy pageDocumentation IndexFetch the complete documentation index at: https://bun.com/docs/llms.txtUse this file to discover all available pages before exploring further.Bun.Image is a chainable image pipeline for decoding, resizing, rotating, and re-encoding JPEG, PNG, WebP, HEIC, and AVIF — built on libjpeg-turbo, spng, libwebp, and SIMD geometry kernels, with zero npm dependencies and no native addon build step. The API is shaped after Sharp: construct from an input, chain transforms, pick an output format, then await a terminal method. Nothing runs until the terminal is awaited, and the work executes off the JavaScript thread. The format is sniffed from the bytes — extensions and Content-Type are ignored. Metadata Resize fitBehavior"fill" (default)Stretch to exactly width × height"inside"Preserve aspect ratio; result fits within the box Modulate Output formats palette: true quantizes to a ≤256-color palette and emits an indexed (color-type 3) PNG, optionally with Floyd–Steinberg dither. This is typically 3–5× smaller than truecolor for screenshots and UI assets. .write() accepts the same destinations as Bun.write — a path string, Bun.file(), Bun.s3(), or an fd. If you didn’t chain a format method and the destination is a path string, the extension picks one (.jpg/.png/.webp/.heic/.avif). For coarse-to-fine rendering of the image itself, encode a progressive JPEG: After the first terminal resolves, img.width and img.height reflect the output dimensions (they’re -1 before). Passing the pipeline directly (new Response(img)) also works, but currently runs the encode synchronously during body init. fromClipboard() reads PNG, TIFF, HEIC, JPEG, WebP, GIF, or BMP from the system pasteboard on macOS and Windows; the regular decode pipeline takes it from there. Returns null if there’s no image, and always null on Linux — call wl-paste/xclip yourself and pass the bytes to the constructor. Formats handled by the system backend (TIFF, HEIC, AVIF, clipboard) inherit the OS’s patch level — keep macOS / Windows updated. JPEG, PNG, and WebP go through the same statically-linked codecs on every platform, so encoded output is byte-identical across Linux, macOS, and Windows. To force the portable Highway path for geometry too — e.g. for golden-image tests — set the process-global backend: |
The Bun.Image API provides a chainable pipeline for image processing, enabling fast native operations for decoding, resizing, rotating, and re-encoding various formats including JPEG, PNG, WebP, HEIC, and AVIF. This system is engineered upon high-performance components such as libjpeg-turbo, spng, libwebp, and SIMD geometry kernels, crucially operating without any npm dependencies or native addon build steps. The API structure mirrors the approach of systems like Sharp: an input is provided, a sequence of transformations is chained, an output format is selected, and finally, a terminal method is awaited to execute the work asynchronously off the JavaScript thread. Input handling accepts file paths, raw bytes, or Blobs, utilizing methods like Bun.file() or Bun.s3() for lazy reading. Developers must exercise caution when using path strings, as this presents an arbitrary-file-read primitive, requiring validation of untrusted input. When dealing with byte arrays or TypedArrays, the API ensures that decoding runs off-thread, borrowing the data without mutation while the terminal operation is pending; shared or resizable buffers are explicitly disallowed in favor of fixed views. Options allow configuration, such as setting maximum pixel dimensions to mitigate decompression bombs or controlling EXIF orientation handling. The API also allows for reading basic metadata, such as width, height, and format, without fully decoding the pixel data. Transformations are executed through methods that manipulate the image state. Resizing permits various behaviors, including fitting within a specified box while preserving aspect ratio, exactly stretching to target dimensions, or setting specific filtering algorithms like lanczos3 for sharpness or mitchell for smooth gradients. Rotation and flipping are supported for geometric manipulation, and modulation allows adjustments to brightness and saturation. The system defines specific resampling kernels, such as lanczos3, mitchell, cubic, and nearest, to control the quality of geometric operations. Output formats are handled via specific methods, allowing encoding to JPEG with adjustable quality, PNG with options for palette inclusion and dithering, and support for modern formats like WebP and HEIC, as well as AVIF. The process of generating output is asynchronous, dictated by waiting for a terminal method to resolve, which can yield raw bytes, memory buffers, descriptive blobs, Base64 strings, or paths for writing to the filesystem or S3. Furthermore, placeholder generation allows for the creation of low-quality, minimally decoded data URLs for rapid rendering in contexts like HTML before the full image loads. The API integrates into server environments through Bun.serve, where the image pipeline can be used to generate network responses, automatically setting the Content-Type. For handling image data from the clipboard, Bun.Image.fromClipboard() reads various image types from the system pasteboard, acknowledging platform differences across Linux, macOS, and Windows. The system employs platform-specific backends, such as ImageIO on macOS and Win32 on Windows, for decoding, and includes logic to handle unsupported system formats by automatically falling back to a more portable format, such as WebP, ensuring resilience against hardware or OS limitations. The configuration allows setting a global backend identifier, which can be used to force portable geometry testing, and the system mandates keeping operating systems updated to support advanced formats like AVIF. |