0.1.6 • Published 7 months ago

railway-image-service v0.1.6

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

Railway Image Service

Integrating with your image service is easier than ever with these React components, hooks, and Node.js client.

Installation

npm install jotai railway-image-service

Examples

  • Astro site

  • Next.js site


Node SDK

ImageServiceClient

A constructor that creates a Node client for your image service.

Options

NameTypeRequired?Description
urlstringYesThe base URL of your image service.
secretKeystringYesThe SECRET_KEY of your image service.
signatureSecretKeystringNoThe SIGNATURE_SECRET_KEY of your image service. If provided URLs can be signed locally without making a network request.

ImageServiceClient.put()

Create or overwrite a file in blob storage.

Arguments

NameTypeRequired?Description
keystringYesThe key to use in blob storage.
contentReadableStream \| Buffer \| ArrayBufferYesThe contents of the file to put in blob storage.

Returns

A Response object.

ImageServiceClient.get()

Get a file from blob storage.

Arguments

NameTypeRequired?Description
keystringYesThe key to get from blob storage.

Returns

A Response object.

ImageServiceClient.delete()

Delete a file in blob storage.

Arguments

NameTypeRequired?Description
keystringYesThe key to delete from blob storage.

Returns

A Response object.

ImageServiceClient.list()

List keys in blob storage.

Options

NameTypeRequired?Description
prefixstringNoA prefix to filter keys by e.g. path/to/.
limitnumberNoThe maximum number of keys to return.
startingAtstringNoThe key to start listing from. Used for pagination.

Returns

A list result object

export type ListResult = {
	/** The keys of the files */
	keys: string[];
	/** A URL to the next page of results */
	nextPage?: string;
	/** Whether or not there are more results */
	hasMore: boolean;
};

ImageServiceClient.sign()

Get a signed URL for a path.

Arguments

NameTypeRequired?Description
pathstringYesThe path to get a signed URL for.

Returns

A signed URL for the given path.

imageUrlBuilder()

Creates a fluent builder for constructing image transformation URLs. Supports chaining of operations for resizing, cropping, filtering, and other image manipulations.

Arguments

NameTypeRequired?Description
clientImageServiceClientYesThe image service client instance used to sign URLs.

Returns

An ImageUrlBuilder instance that supports method chaining.

Examples

import {
	ImageServiceClient,
	imageUrlBuilder,
} from "railway-image-service/server";

const client = new ImageServiceClient({
	url: process.env.IMAGE_SERVICE_URL,
	secretKey: process.env.IMAGE_SERVICE_SECRET_KEY,
	signatureSecretKey: process.env.IMAGE_SERVICE_SIGNATURE_SECRET_KEY,
});

const builder = imageUrlBuilder(client);

// Basic image resize
const url = builder.url("https://github.com/railwayapp.png").size(48).build();

// Avatar generation
const url = builder.avatar(48, { quality: 90 }).build();

// Complex transformation
const url = builder
	.key("my-image-key.jpg")
	.size(1200, 800)
	.fit("cover")
	.trim()
	.filter({
		quality: 85,
		brightness: 10,
		format: "webp",
	})
	.build();

// Smart cropping with focal point
const url = builder
	.url("https://example.com/portrait.jpg")
	.size(400, 400)
	.smart()
	.filter({
		focal: "300,400",
		format: "jpeg",
		quality: 90,
	})
	.build();

// Sign the URL remotely
const url = await builder
	.key("my-image-key.jpg")
	.size(1200, 800)
	.fit("cover")
	.trim()
	.filter({
		quality: 85,
		brightness: 10,
		format: "webp",
	});

Image Source Methods

.key(blobKey)

Sets the image source using a blob storage key.

NameTypeRequired?Description
blobKeystringYesThe storage key identifying the image.

.url(httpUrl)

Sets the image source using a URL.

NameTypeRequired?Description
httpUrlstringYesThe URL of the source image.

Avatar generation

.avatar(size, filters)

Applies optimized image filters and transformations for avatar images. Automatically enables smart cropping, cover fitting, and metadata stripping.

NameTypeRequired?Description
sizenumberYesTarget size for the avatar (width and height)
filtersImageFiltersYesAdditional filter settings to apply

Default Settings

  • fit: "cover"
  • smart: true
  • upscale: true
  • quality: 80
  • strip_exif: true
  • strip_metadata: true
  • strip_icc: true

Dimension Methods

.width(value)

Sets the target width of the output image.

NameTypeRequired?Description
valuenumberYesWidth in pixels.

.height(value)

Sets the target height of the output image.

NameTypeRequired?Description
valuenumberYesHeight in pixels.

.size(width, height?)

Sets both width and height of the output image.

NameTypeRequired?Description
widthnumberYesWidth in pixels.
heightnumberNoHeight in pixels. Defaults to width if omitted.

Transform Methods

.fit(value)

Sets the fit mode for image resizing.

NameTypeRequired?Description
valueImageFitYesThe fit mode to use.

ImageFit Options

  • "cover": Scales to fill the entire box, cropping if necessary
  • "contain": Scales to fit within the box while maintaining aspect ratio
  • "stretch": Stretches or compresses to exactly fill the box
  • "contain-stretch": Combines contain and stretch modes

.flip(direction)

Flips the image horizontally, vertically, or both.

NameTypeRequired?Description
direction"horizontal" \| "vertical" \| "both"YesThe direction to flip.

.crop(x, y, width, height)

Crops the image to a specified region.

NameTypeRequired?Description
xnumber \| stringYesLeft coordinate (pixels or percentage with '%')
ynumber \| stringYesTop coordinate (pixels or percentage with '%')
widthnumber \| stringYesWidth of crop (pixels or percentage with '%')
heightnumber \| stringYesHeight of crop (pixels or percentage with '%')

.padding(left, top, right, bottom)

Adds padding around the image.

NameTypeRequired?Description
leftnumberYesLeft padding in pixels
topnumberYesTop padding in pixels
rightnumberYesRight padding in pixels
bottomnumberYesBottom padding in pixels

.trim(enable?)

Enables trim mode to remove surrounding space.

NameTypeRequired?Description
enablebooleanNoWhether to enable trim. Default: true

.smart(enable?)

Enables smart detection of focal points for cropping.

NameTypeRequired?Description
enablebooleanNoWhether to enable smart detection. Default: true

.align(horizontal?, vertical?)

Sets the alignment for cropping and fitting operations.

NameTypeRequired?Description
horizontal"left" \| "center" \| "right"NoHorizontal alignment
vertical"top" \| "middle" \| "bottom"NoVertical alignment

Filter Methods

.filter(filters)

Applies image filters like blur, brightness, contrast, etc.

NameTypeRequired?Description
filtersImageFiltersYesObject containing filter settings

ImageFilters Options

NameTypeDescription
background_colorstringSets background color for transparent images
blurnumberApplies Gaussian blur (sigma value)
brightnessnumberAdjusts brightness (-100 to 100)
contrastnumberAdjusts contrast (-100 to 100)
fillstringFills transparent areas (color/blur/auto/none)
formatImageFormatSets output format
grayscalebooleanConverts to grayscale
huenumberRotates the hue (0-360 degrees)
orientAngleSets image orientation
proportionnumberScales image by percentage
qualitynumberSets JPEG quality (0-100)
rgb[number, number, number]Adjusts RGB channels (-100 to 100 each)
rotateAngleRotates image by fixed angles
saturationnumberAdjusts color saturation (-100 to 100)
sharpennumberApplies sharpening effect
focalstringSets focal point for cropping
round_cornerobjectAdds rounded corners
max_bytesnumberLimits output file size
max_framesnumberLimits animation frames
pagenumberSelects specific page/frame
dpinumberSets DPI for vector formats
strip_exifbooleanRemoves EXIF metadata
strip_iccbooleanRemoves ICC profile
strip_metadatabooleanRemoves all metadata
upscalebooleanAllows upscaling with fit-in
attachmentstringSets download filename
expirenumberSets content expiration
previewbooleanSkips result storage
rawbooleanReturns unprocessed image

Build Methods

.buildRemote()

Builds and signs the final URL for the image transformation using the image service client API.

Returns

A promise that resolves to the signed URL string.

.build()

Builds and signs the final URL for the image transformation locally.

Returns

A signed URL string.


React API

Components

<Provider>

Provides configuration to its child hooks and components.

Props

NameTypeRequired?Description
urlstring \| {get: string; put: string}YesThe base URL where blob storage (PUT) and serve (GET) requests will be sent. Your file blob key will be joined to this URL.
maxUploadSizenumberNoThe maximum size of an image that can be uploaded in bytes.

Hooks

useDropzone()

A hook that creates a clickable dropzone for files. This is a convenience wrapper around useSelectFiles and useDropFiles.

Options

NameTypeRequired?Description
acceptstringNoA comma-separated list of content types your users are allowed to select in the browser dialog, e.g. IMAGE_MIMES
multiplebooleanNoSet to true if you want to allow multiple files to be selected at once.
keyKeyNoSet the key that will be stored in blob storage for the file. Defaults to the file name.
onSelectOnSelectNoCalled each time a file is selected.

Returns

type ReturnType = {
	/**
	 * Props that can directly added to a dropzone container.
	 */
	props: React.HTMLAttributes<HTMLElement>;
	/**
	 * Whether or not the dropzone is actively being dragged voer.
	 */
	isActive: dropFiles.isActive;
};

useSelectFiles()

A hook that returns a callback which opens a browser dialog for selecting files when called.

Options

NameTypeRequired?Description
acceptstringNoA comma-separated list of content types your users are allowed to select in the browser dialog, e.g. IMAGE_MIMES
multiplebooleanNoSet to true if you want to allow multiple files to be selected at once.
onSelectOnSelectNoCalled each time a file is selected.

Returns

export type SelectFilesCallback = (options?: {
	/**
	 * The key that will be stored in blob storage for the file.
	 */
	key?: Key;
}) => void;

useDropFiles()

A hook that handles drag-n-drop file uploads.

Options

NameTypeRequired?Description
acceptstringNoA comma-separated list of content types your users are allowed to select in the browser dialog, e.g. IMAGE_MIMES
multiplebooleanNoSet to true if you want to allow multiple files to be selected at once.
keyKeyNoSet the key that will be stored in blob storage for the file. Defaults to the file name.
onSelectOnSelectNoCalled each time a file is selected.

Returns

type ReturnType = {
	/**
	 * Props that can directly added to a dropzone container.
	 */
	props: React.HTMLAttributes<HTMLElement>;
	/**
	 * Whether or not the dropzone is actively being dragged voer.
	 */
	isActive: dropFiles.isActive;
};

useSelectDirectory()

A hook that returns a callback that opens a browser dialog for selecting files from an entire directory when called.

Options

NameTypeRequired?Description
onSelectOnSelectNoCalled each time a file is selected.

Returns

export type SelectFilesCallback = (options?: {
	/**
	 * The key that will be stored in blob storage for the file.
	 */
	key?: Key;
}) => void;

useSelectedFile()

A hook that returns the raw file File object from a selected file and the key.

Arguments

NameTypeRequired?Description
selectedFileSelectedFileNoA file that was selected with any of the useDropzone, useSelectFiles, useDropFiles, or useSelectDirectory hooks.

Returns

type ReturnType = {
	/**
	 * The key that will be added via the blob storage API
	 */
	key: file.key;
	/**
	 * The raw `File` object created by the browser
	 */
	file: file.file;
};

useUploadFile()

A hook that returns a callback for uploading a file to the server.

Returns

A callback used to upload a single file to blob storage.

async function uploadFile(
	file: SelectedFile,
	options: UploadFileOptions = {},
): Promise<void>;

type UploadFileOptions = {
	/**
	 * The key that will be stored in the key/value store for the file.
	 */
	key?: Key;
	/**
	 * Additional headers to send with the upload request
	 */
	headers?: Record<string, string>;
	/**
	 * Whether or not to send cookies with the upload request
	 */
	withCredentials?: boolean;
	/**
	 * A function that is called when the upload is aborted
	 */
	onAbort?: (selectedFileData: Pick<SelectedFileData, "key" | "file">) => void;
	/**
	 * Called when all of the files have successfully uploaded
	 */
	onSuccess?: (
		selectedFileData: Pick<SelectedFileData, "key" | "file">,
		response: Response,
	) => Promise<void> | void;
	/**
	 * Called when there is a progress event
	 */
	onProgress?: (
		selectedFileData: Pick<SelectedFileData, "key" | "file">,
		progress: ProgressData,
	) => Promise<void> | void;
	/**
	 * Called when there was an error uploading
	 */
	onError?: (
		selectedFileData: Pick<SelectedFileData, "key" | "file">,
		err: unknown,
	) => Promise<void> | void;
};

useUploadFiles()

A hook that returns a function for uploading multiple files concurrently with a configurable concurrency limit.

Returns

A callback used to upload multiple files to blob storage.

async function uploadFiles(
	selectedFiles: Array<SelectedFile>,
	options: {
		/**
		 * Maximum number of concurrent uploads
		 * @default 3
		 */
		concurrency?: number;
	} & UploadFileOptions = {},
): Promise<void>;

useProgress()

A hook that returns detailed progress information for a file upload. This includes the upload rate, estimated time remaining, and other upload statistics.

Arguments

NameTypeRequired?Description
selectedFileSelectedFileNoA file that was selected with any of the useDropzone, useSelectFiles, useDropFiles, or useSelectDirectory hooks.

Returns

Progress information including:

  • total - Total file size in bytes
  • loaded - Number of bytes uploaded
  • progress - Upload progress as a fraction between 0-1
  • rate - Upload speed in bytes per second
  • estimatedTimeRemaining - Estimated milliseconds until completion, or null if not started
  • timeElapsed - Milliseconds since upload started

useStatus()

A hook that returns the status from a selected file.

usePreview()

Arguments

NameTypeRequired?Description
selectedFileSelectedFileNoA file that was selected with any of the useDropzone, useSelectFiles, useDropFiles, or useSelectDirectory hooks.

Returns

The file status

export type SelectedFileStatus =
	| "idle"
	| "queued"
	| "uploading"
	| "aborted"
	| "success"
	| "error";

useAbort()

A hook that returns a callback for cancelling a file upload if possible.

Arguments

NameTypeRequired?Description
selectedFileSelectedFileNoA file that was selected with any of the useDropzone, useSelectFiles, useDropFiles, or useSelectDirectory hooks.

Returns

A callback that signals the abort controller for the file and sets its status to cancelled when the file isn't in a eterminal state (success/error).

Utility functions

hashFile()

Get the SHA-256 hash of a file's contents

Arguments

NameTypeRequired?Description
fileFileYesThe file to hash

Returns

A promise that resolves with the SHA-256 hash of the file's contents

async function hashFile(file: File): Promise<string>;

extname()

Get the file extension of a file

Arguments

NameTypeRequired?Description
fileFileYesThe file to hash

Returns

The file extension

function extname(file: File): string;

Constants

IMAGE_MIMES

MIME types for images. Can be used with the accept option in useSelectFiles to restrict which files can be selected in the browser dialog.

0.1.6

7 months ago

0.1.5

7 months ago

0.1.4

7 months ago

0.1.3

7 months ago

0.1.2

7 months ago

0.1.1

7 months ago

0.1.0

7 months ago