Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

🏞 Real-time image processing for your express application.

License

NotificationsYou must be signed in to change notification settings

pmb0/express-sharp

Repository files navigation

Real-time image processing for your express application.

npm versionTest CoverageBuild Status

Description

express-sharp adds real-time image processing routes to your express application. Images are processed withsharp, a fast Node.js module for resizing images.

                      express-sharp    Express app         endpoint          image path    transformation                ┌─────────────────┐┌────────────────┐┌──────────────────┐ ┌────────┐https://example.com/path/to/my-scaler/images/my-image.jpg?w=100&h=50

Original images are loaded via an image adapter. Currently this includes HTTP and file system adapters.

Highlights

Table of contents

Install

$ yarn add express-sharp

Seesharp installation for additional installation instructions.

Express server integration

Exampleapp.js (See alsoexample/app.ts in this project):

importexpressfrom'express'import{expressSharp,FsAdapter,HttpAdapter}from'express-sharp'constapp=express()// Fetch original images via HTTPapp.use('/some-http-endpoint',expressSharp({imageAdapter:newHttpAdapter({prefixUrl:'http://example.com/images',}),}))// Alternative: Load original images from diskapp.use('/fs-endpoint',expressSharp({imageAdapter:newFsAdapter(path.join(__dirname,'images')),}))app.listen(3000)

Render/images/image.jpg with 400x400 pixels:

curl http://my-server/express-sharp-endpoint/images/image.jpg?w=400&h=400

Same as above, but with 80% quality,webp image type and with progressive enabled:

curl http://my-server/express-sharp-endpoint/images/image.jpg?w=400&h=400&f=webp&q=80&p

Server configuration

import{expressSharp}from'express-sharp'app.use('/some-http-endpoint',expressSharp(options))

Supportedoptions:

NameDescriptionDefault
autoUseWebpSpecifies whether images should automatically be rendered in webp format when supported by the browser.true
cacheIf specified, the keyv cache configured here is used to cache the retrieval of the original images and the transformations.-
corsAny validCORS configuration option-
imageAdapterConfigures the image adapter to be used (see below). Must be specified.-
secretIf specified, express-sharp will validate the incoming request to verify that a valid signature has been provided. The secret is used to compute this signature.-

Image Adapters

express-sharp contains the following standard image adapters.

File System

With this adapter original images are loaded from the hard disk.

import{FsAdapter}from'express-sharp'constadapter=newFsAdapter('/path/to/images')

HTTP

Loads original images via HTTP. To use this adapter, the peer dependencygot must be installed:

$ yarn add got
import{HttpAdapter}from'express-sharp'constadapter=newHttpAdapter({prefixUrl:'http://localhost:3000/images',})

The constructor can be passed anygot options.

Amazon S3

Loads images from Amazon S3. To use this adapter, the peer dependencyaws-sdk must be installed:

$ yarn add aws-sdk
import{S3Adapter}from'express-sharp'constbucketName='my-bucketname'constadapter=newS3Adapter(bucketname)

The AWS SDK expects the environment variablesAWS_ACCESS_KEY_ID andAWS_SECRET_ACCESS_KEY to be set.

Custom

If you needed your own adapters can be used. An "image adapter" is a class that implements theImageAdapter interface:

import{ImageAdapter}from'express-sharp'classMyAdapterimplementsImageAdapter{asyncfetch(id:string):Promise<Buffer|undefined>{if(imageDoesNotExist(id)){returnundefined}returnBuffer.from('my image blob')}}

Caching

The fetching of the original images and the transformations can be cached. To enable this feature, thecache option must be passed to theexpressSharp middleware. Anykeyv cache stores can be passed.

In-memory cache example:

constcache=newKeyv({namespace:'express-sharp'})app.use('/my-endpoint',expressSharp({    cache,imageAdapter: ...}))

Redis example:

constcache=newKeyv('redis://',{namespace:'express-sharp'}app.use('/my-endpoint',expressSharp({    cache,imageAdapter: ...}))

URL signing

By setting the environment variableEXPRESS_SHARP_SIGNED_URL_SECRET or by specifying thesecret option when calling theexpress-sharp middleware, signed URLs are activated. This reduces the attack surface on the server, since the caller cannot produce an unlimited number of URLs that cause load on the server.

In order to compute the signature, the supplied client should be used:

import{createClient}from'express-sharp'constendpoint='https://example.com/my-express-sharp-endpoint'constsecret='test'constclient=createClient(endpoint,secret)constimageUrl=client.url('/foo.png',{width:500})// https://example.com/my-express-sharp-endpoint/foo.png?w=500&s=Of3ty8QY-NDhCsIrgIHvPvbokkDcxV8KtaYUB4NFRd8

Debug logging

This project usesdebug. To display debug messages fromexpress-sharp, theDEBUG environment variable must be exported so that it contains the valueexpress-sharp*. Example:

$export DEBUG='my-app:*,express-sharp*'

Client integration

express-sharp comes with a client that can be used to generate URLs for images.

import{createClient}from'express-sharp'constclient=createClient('http://my-base-host','optional secret')constoriginalImageUrl='/foo.png'constoptions={width:500}constfooUrl=client.url(originalImageUrl,options)

Currently the following transformations can be applied to images:

Client option nameQuery param nameDescription
qualityqQuality is a number between 1 and 100 (seesharp docs).
widthw
heighth
formatfOutput image format. Valid values: every validsharp output format string, i.e.jpeg,gif,webp orraw.
progressivepOnly available for jpeg and png formats. Enable progressive scan by passingtrue.
cropcSetting crop totrue enables thesharp cropping feature. Note: Bothwidth andheight params are neccessary for crop to work. Default isfalse.
trimtSetting trim totrue enables thesharp trim feature.
gravitygWhen the crop option is activated you can specify the gravity of the cropping. Possible attributes of the optionalgravity arenorth,northeast,east,southeast,south,southwest,west,northwest,center andcentre. Default iscenter.

License

express-sharp is distributed under the MIT license.See LICENSE for details.

About

🏞 Real-time image processing for your express application.

Topics

Resources

License

Stars

Watchers

Forks

Contributors8


[8]ページ先頭

©2009-2025 Movatter.jp