Gathering detailed insights and metrics for blueimp-load-image
Gathering detailed insights and metrics for blueimp-load-image
Gathering detailed insights and metrics for blueimp-load-image
Gathering detailed insights and metrics for blueimp-load-image
Load images provided as File or Blob objects or via URL. Retrieve an optionally scaled, cropped or rotated HTML img or canvas element. Use methods to parse image metadata to extract IPTC and Exif tags as well as embedded thumbnail images, to overwrite the Exif Orientation value and to restore the complete image header after resizing.
npm install blueimp-load-image
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
4,452 Stars
430 Commits
922 Forks
161 Watching
2 Branches
19 Contributors
Updated on 26 Nov 2024
JavaScript (93.75%)
HTML (3.82%)
CSS (2.24%)
Shell (0.19%)
Cumulative downloads
Total Downloads
Last day
-2.8%
36,211
Compared to previous day
Last week
3.6%
184,285
Compared to previous week
Last month
2.8%
794,287
Compared to previous month
Last year
-6.5%
10,738,659
Compared to previous year
A JavaScript library to load and transform image files.
JavaScript Load Image is a library to load images provided as File
or Blob
objects or via URL
. It returns an optionally scaled, cropped or
rotated HTML img
or canvas
element.
It also provides methods to parse image metadata to extract IPTC and Exif tags as well as embedded thumbnail images, to overwrite the Exif Orientation value and to restore the complete image header after resizing.
Install via NPM:
1npm install blueimp-load-image
This will install the JavaScript files inside
./node_modules/blueimp-load-image/js/
relative to your current directory, from
where you can copy them into a folder that is served by your web server.
Next include the combined and minified JavaScript Load Image script in your HTML markup:
1<script src="js/load-image.all.min.js"></script>
Or alternatively, choose which components you want to include:
1<!-- required for all operations --> 2<script src="js/load-image.js"></script> 3 4<!-- required for scaling, cropping and as dependency for rotation --> 5<script src="js/load-image-scale.js"></script> 6 7<!-- required to parse meta data and to restore the complete image head --> 8<script src="js/load-image-meta.js"></script> 9 10<!-- required to parse meta data from images loaded via URL --> 11<script src="js/load-image-fetch.js"></script> 12 13<!-- required for rotation and cross-browser image orientation --> 14<script src="js/load-image-orientation.js"></script> 15 16<!-- required to parse Exif tags and cross-browser image orientation --> 17<script src="js/load-image-exif.js"></script> 18 19<!-- required to display text mappings for Exif tags --> 20<script src="js/load-image-exif-map.js"></script> 21 22<!-- required to parse IPTC tags --> 23<script src="js/load-image-iptc.js"></script> 24 25<!-- required to display text mappings for IPTC tags --> 26<script src="js/load-image-iptc-map.js"></script>
In your application code, use the loadImage()
function with
callback style:
1document.getElementById('file-input').onchange = function () {
2 loadImage(
3 this.files[0],
4 function (img) {
5 document.body.appendChild(img)
6 },
7 { maxWidth: 600 } // Options
8 )
9}
Or use the Promise based API like this (requires a polyfill for older browsers):
1document.getElementById('file-input').onchange = function () {
2 loadImage(this.files[0], { maxWidth: 600 }).then(function (data) {
3 document.body.appendChild(data.image)
4 })
5}
With async/await (requires a modern browser or a code transpiler like Babel or TypeScript):
1document.getElementById('file-input').onchange = async function () {
2 let data = await loadImage(this.files[0], { maxWidth: 600 })
3 document.body.appendChild(data.image)
4}
It is also possible to use the image scaling functionality directly with an existing image:
1var scaledImage = loadImage.scale( 2 img, // img or canvas element 3 { maxWidth: 600 } 4)
The JavaScript Load Image library has zero dependencies, but benefits from the following two polyfills:
Blob
objects out of canvas
elements.loadImage
API in Browsers without native Promise
support.Browsers which implement the following APIs support all options:
This includes (but is not limited to) the following browsers:
*
*
Internet Explorer requires a polyfill for the Promise
based API.
Loading an image from a URL and applying transformations (scaling, cropping and
rotating - except orientation:true
, which requires reading meta data) is
supported by all browsers which implement the
HTMLCanvasElement
interface.
Loading an image from a URL and scaling it in size is supported by all browsers which implement the img element and has been tested successfully with browser engines as old as Internet Explorer 5 (via IE11's emulation mode).
The loadImage()
function applies options using
progressive enhancement
and falls back to a configuration that is supported by the browser, e.g. if the
canvas
element is not supported, an equivalent img
element is returned.
The loadImage()
function accepts a
File or
Blob object or an image
URL as first argument.
If a File or
Blob is passed as
parameter, it returns an HTML img
element if the browser supports the
URL API, alternatively a
FileReader object
if the FileReader
API is supported, or false
.
It always returns an HTML img element when passing an image URL:
1var loadingImage = loadImage(
2 'https://example.org/image.png',
3 function (img) {
4 document.body.appendChild(img)
5 },
6 { maxWidth: 600 }
7)
Some browsers (e.g. Chrome) will cancel the image loading process if the src
property of an img
element is changed.
To avoid unnecessary requests, we can use the
data URL
of a 1x1 pixel transparent GIF image as src
target to cancel the original
image download.
To disable callback handling, we can also unset the image event handlers and for maximum browser compatibility, cancel the file reading process if the returned object is a FileReader instance:
1var loadingImage = loadImage(
2 'https://example.org/image.png',
3 function (img) {
4 document.body.appendChild(img)
5 },
6 { maxWidth: 600 }
7)
8
9if (loadingImage) {
10 // Unset event handling for the loading image:
11 loadingImage.onload = loadingImage.onerror = null
12
13 // Cancel image loading process:
14 if (loadingImage.abort) {
15 // FileReader instance, stop the file reading process:
16 loadingImage.abort()
17 } else {
18 // HTMLImageElement element, cancel the original image request by changing
19 // the target source to the data URL of a 1x1 pixel transparent image GIF:
20 loadingImage.src =
21 'data:image/gif;base64,' +
22 'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
23 }
24}
Please note:
The img
element (or FileReader
instance) for the loading image is only
returned when using the callback style API and not available with the
Promise based API.
For the callback style API, the second argument to loadImage()
must be a
callback
function, which is called when the image has been loaded or an error
occurred while loading the image.
The callback function is passed two arguments:
error
.1loadImage( 2 fileOrBlobOrUrl, 3 function (img, data) { 4 document.body.appendChild(img) 5 console.log('Original image width: ', data.originalWidth) 6 console.log('Original image height: ', data.originalHeight) 7 }, 8 { maxWidth: 600, meta: true } 9)
Please note:
The original image dimensions reflect the natural width and height of the loaded
image before applying any transformation.
For consistent values across browsers, metadata parsing has
to be enabled via meta:true
, so loadImage
can detect automatic image
orientation and normalize the dimensions.
Example code implementing error handling:
1loadImage( 2 fileOrBlobOrUrl, 3 function (img, data) { 4 if (img.type === 'error') { 5 console.error('Error loading image file') 6 } else { 7 document.body.appendChild(img) 8 } 9 }, 10 { maxWidth: 600 } 11)
If the loadImage()
function is called without a callback
function as second
argument and the
Promise
API is available, it returns a Promise
object:
1loadImage(fileOrBlobOrUrl, { maxWidth: 600, meta: true }) 2 .then(function (data) { 3 document.body.appendChild(data.image) 4 console.log('Original image width: ', data.originalWidth) 5 console.log('Original image height: ', data.originalHeight) 6 }) 7 .catch(function (err) { 8 // Handling image loading errors 9 console.log(err) 10 })
The Promise
resolves with an object with the following properties:
image
: An HTML
img or
canvas element.originalWidth
: The original width of the image.originalHeight
: The original height of the image.Please also read the note about original image dimensions normalization in the callback arguments section.
If metadata has been parsed, additional properties might be present on the object.
If image loading fails, the Promise
rejects with an
Event object of type
error
.
The optional options argument to loadImage()
allows to configure the image
loading.
It can be used the following way with the callback style:
1loadImage( 2 fileOrBlobOrUrl, 3 function (img) { 4 document.body.appendChild(img) 5 }, 6 { 7 maxWidth: 600, 8 maxHeight: 300, 9 minWidth: 100, 10 minHeight: 50, 11 canvas: true 12 } 13)
Or the following way with the Promise
based API:
1loadImage(fileOrBlobOrUrl, {
2 maxWidth: 600,
3 maxHeight: 300,
4 minWidth: 100,
5 minHeight: 50,
6 canvas: true
7}).then(function (data) {
8 document.body.appendChild(data.image)
9})
All settings are optional. By default, the image is returned as HTML img
element without any image size restrictions.
Defines the maximum width of the img
/canvas
element.
Defines the maximum height of the img
/canvas
element.
Defines the minimum width of the img
/canvas
element.
Defines the minimum height of the img
/canvas
element.
The width of the sub-rectangle of the source image to draw into the destination
canvas.
Defaults to the source image width and requires canvas: true
.
The height of the sub-rectangle of the source image to draw into the destination
canvas.
Defaults to the source image height and requires canvas: true
.
The top margin of the sub-rectangle of the source image.
Defaults to 0
and requires canvas: true
.
The right margin of the sub-rectangle of the source image.
Defaults to 0
and requires canvas: true
.
The bottom margin of the sub-rectangle of the source image.
Defaults to 0
and requires canvas: true
.
The left margin of the sub-rectangle of the source image.
Defaults to 0
and requires canvas: true
.
Scales the image up/down to contain it in the max dimensions if set to true
.
This emulates the CSS feature
background-image: contain.
Scales the image up/down to cover the max dimensions with the image dimensions
if set to true
.
This emulates the CSS feature
background-image: cover.
Crops the image to the given aspect ratio (e.g. 16/9
).
Setting the aspectRatio
also enables the crop
option.
Defines the ratio of the canvas pixels to the physical image pixels on the
screen.
Should be set to
window.devicePixelRatio
unless the scaled image is not rendered on screen.
Defaults to 1
and requires canvas: true
.
Defines the ratio in which the image is downsampled (scaled down in steps).
By default, images are downsampled in one step.
With a ratio of 0.5
, each step scales the image to half the size, before
reaching the target dimensions.
Requires canvas: true
.
If set to false
,
disables image smoothing.
Defaults to true
and requires canvas: true
.
Sets the
quality of image smoothing.
Possible values: 'low'
, 'medium'
, 'high'
Defaults to 'low'
and requires canvas: true
.
Crops the image to the maxWidth
/maxHeight
constraints if set to true
.
Enabling the crop
option also enables the canvas
option.
Transform the canvas according to the specified Exif orientation, which can be
an integer
in the range of 1
to 8
or the boolean value true
.
When set to true
, it will set the orientation value based on the Exif data of
the image, which will be parsed automatically if the Exif extension is
available.
Exif orientation values to correctly display the letter F:
1 2
██████ ██████
██ ██
████ ████
██ ██
██ ██
3 4
██ ██
██ ██
████ ████
██ ██
██████ ██████
5 6
██████████ ██
██ ██ ██ ██
██ ██████████
7 8
██ ██████████
██ ██ ██ ██
██████████ ██
Setting orientation
to true
enables the canvas
and meta
options, unless
the browser supports automatic image orientation (see
browser support for image-orientation).
Setting orientation
to 1
enables the canvas
and meta
options if the
browser does support automatic image orientation (to allow reset of the
orientation).
Setting orientation
to an integer in the range of 2
to 8
always enables
the canvas
option and also enables the meta
option if the browser supports
automatic image orientation (again to allow reset).
Automatically parses the image metadata if set to true
.
If metadata has been found, the data object passed as second argument to the callback function has additional properties (see metadata parsing).
If the file is given as URL and the browser supports the
fetch API or the
XHR
responseType
blob
, fetches the file as Blob
to be able to parse the metadata.
Returns the image as
canvas element if
set to true
.
Sets the crossOrigin
property on the img
element for loading
CORS enabled images.
By default, the
created object URL
is revoked after the image has been loaded, except when this option is set to
true
.
If the Load Image Meta extension is included, it is possible to parse image meta
data automatically with the meta
option:
1loadImage( 2 fileOrBlobOrUrl, 3 function (img, data) { 4 console.log('Original image head: ', data.imageHead) 5 console.log('Exif data: ', data.exif) // requires exif extension 6 console.log('IPTC data: ', data.iptc) // requires iptc extension 7 }, 8 { meta: true } 9)
Or alternatively via loadImage.parseMetaData
, which can be used with an
available File
or Blob
object as first argument:
1loadImage.parseMetaData( 2 fileOrBlob, 3 function (data) { 4 console.log('Original image head: ', data.imageHead) 5 console.log('Exif data: ', data.exif) // requires exif extension 6 console.log('IPTC data: ', data.iptc) // requires iptc extension 7 }, 8 { 9 maxMetaDataSize: 262144 10 } 11)
Or using the Promise based API:
1loadImage 2 .parseMetaData(fileOrBlob, { 3 maxMetaDataSize: 262144 4 }) 5 .then(function (data) { 6 console.log('Original image head: ', data.imageHead) 7 console.log('Exif data: ', data.exif) // requires exif extension 8 console.log('IPTC data: ', data.iptc) // requires iptc extension 9 })
The Metadata extension adds additional options used for the parseMetaData
method:
maxMetaDataSize
: Maximum number of bytes of metadata to parse.disableImageHead
: Disable parsing the original image head.disableMetaDataParsers
: Disable parsing metadata (image head only)Resized JPEG images can be combined with their original image head via
loadImage.replaceHead
, which requires the resized image as Blob
object as
first argument and an ArrayBuffer
image head as second argument.
With callback style, the third argument must be a callback
function, which is
called with the new Blob
object:
1loadImage(
2 fileOrBlobOrUrl,
3 function (img, data) {
4 if (data.imageHead) {
5 img.toBlob(function (blob) {
6 loadImage.replaceHead(blob, data.imageHead, function (newBlob) {
7 // do something with the new Blob object
8 })
9 }, 'image/jpeg')
10 }
11 },
12 { meta: true, canvas: true, maxWidth: 800 }
13)
Or using the Promise based API like this:
1loadImage(fileOrBlobOrUrl, { meta: true, canvas: true, maxWidth: 800 })
2 .then(function (data) {
3 if (!data.imageHead) throw new Error('Could not parse image metadata')
4 return new Promise(function (resolve) {
5 data.image.toBlob(function (blob) {
6 data.blob = blob
7 resolve(data)
8 }, 'image/jpeg')
9 })
10 })
11 .then(function (data) {
12 return loadImage.replaceHead(data.blob, data.imageHead)
13 })
14 .then(function (blob) {
15 // do something with the new Blob object
16 })
17 .catch(function (err) {
18 console.error(err)
19 })
Please note:
Blob
objects of resized images can be created via
HTMLCanvasElement.toBlob.
blueimp-canvas-to-blob
provides a polyfill for browsers without native canvas.toBlob()
support.
If you include the Load Image Exif Parser extension, the argument passed to the
callback for parseMetaData
will contain the following additional properties if
Exif data could be found in the given image:
exif
: The parsed Exif tagsexifOffsets
: The parsed Exif tag offsetsexifTiffOffset
: TIFF header offset (used for offset pointers)exifLittleEndian
: little endian order if true, big endian if falseThe exif
object stores the parsed Exif tags:
1var orientation = data.exif[0x0112] // Orientation
The exif
and exifOffsets
objects also provide a get()
method to retrieve
the tag value/offset via the tag's mapped name:
1var orientation = data.exif.get('Orientation') 2var orientationOffset = data.exifOffsets.get('Orientation')
By default, only the following names are mapped:
Orientation
Thumbnail
(see Exif Thumbnail)Exif
(see Exif IFD)GPSInfo
(see GPSInfo IFD)Interoperability
(see Interoperability IFD)If you also include the Load Image Exif Map library, additional tag mappings become available, as well as three additional methods:
exif.getText()
exif.getName()
exif.getAll()
1var orientationText = data.exif.getText('Orientation') // e.g. "Rotate 90° CW" 2 3var name = data.exif.getName(0x0112) // "Orientation" 4 5// A map of all parsed tags with their mapped names/text as keys/values: 6var allTags = data.exif.getAll()
Example code displaying a thumbnail image embedded into the Exif metadata:
1loadImage( 2 fileOrBlobOrUrl, 3 function (img, data) { 4 var exif = data.exif 5 var thumbnail = exif && exif.get('Thumbnail') 6 var blob = thumbnail && thumbnail.get('Blob') 7 if (blob) { 8 loadImage( 9 blob, 10 function (thumbImage) { 11 document.body.appendChild(thumbImage) 12 }, 13 { orientation: exif.get('Orientation') } 14 ) 15 } 16 }, 17 { meta: true } 18)
Example code displaying data from the Exif IFD (Image File Directory) that contains Exif specified TIFF tags:
1loadImage( 2 fileOrBlobOrUrl, 3 function (img, data) { 4 var exifIFD = data.exif && data.exif.get('Exif') 5 if (exifIFD) { 6 // Map of all Exif IFD tags with their mapped names/text as keys/values: 7 console.log(exifIFD.getAll()) 8 // A specific Exif IFD tag value: 9 console.log(exifIFD.get('UserComment')) 10 } 11 }, 12 { meta: true } 13)
Example code displaying data from the Exif IFD (Image File Directory) that contains GPS info:
1loadImage( 2 fileOrBlobOrUrl, 3 function (img, data) { 4 var gpsInfo = data.exif && data.exif.get('GPSInfo') 5 if (gpsInfo) { 6 // Map of all GPSInfo tags with their mapped names/text as keys/values: 7 console.log(gpsInfo.getAll()) 8 // A specific GPSInfo tag value: 9 console.log(gpsInfo.get('GPSLatitude')) 10 } 11 }, 12 { meta: true } 13)
Example code displaying data from the Exif IFD (Image File Directory) that contains Interoperability data:
1loadImage( 2 fileOrBlobOrUrl, 3 function (img, data) { 4 var interoperabilityData = data.exif && data.exif.get('Interoperability') 5 if (interoperabilityData) { 6 // The InteroperabilityIndex tag value: 7 console.log(interoperabilityData.get('InteroperabilityIndex')) 8 } 9 }, 10 { meta: true } 11)
The Exif parser adds additional options:
disableExif
: Disables Exif parsing when true
.disableExifOffsets
: Disables storing Exif tag offsets when true
.includeExifTags
: A map of Exif tags to include for parsing (includes all but
the excluded tags by default).excludeExifTags
: A map of Exif tags to exclude from parsing (defaults to
exclude Exif
MakerNote
).An example parsing only Orientation, Thumbnail and ExifVersion tags:
1loadImage.parseMetaData( 2 fileOrBlob, 3 function (data) { 4 console.log('Exif data: ', data.exif) 5 }, 6 { 7 includeExifTags: { 8 0x0112: true, // Orientation 9 ifd1: { 10 0x0201: true, // JPEGInterchangeFormat (Thumbnail data offset) 11 0x0202: true // JPEGInterchangeFormatLength (Thumbnail data length) 12 }, 13 0x8769: { 14 // ExifIFDPointer 15 0x9000: true // ExifVersion 16 } 17 } 18 } 19)
An example excluding Exif
MakerNote
and GPSInfo
:
1loadImage.parseMetaData( 2 fileOrBlob, 3 function (data) { 4 console.log('Exif data: ', data.exif) 5 }, 6 { 7 excludeExifTags: { 8 0x8769: { 9 // ExifIFDPointer 10 0x927c: true // MakerNote 11 }, 12 0x8825: true // GPSInfoIFDPointer 13 } 14 } 15)
The Exif parser extension also includes a minimal writer that allows to override
the Exif Orientation
value in the parsed imageHead
ArrayBuffer
:
1loadImage(
2 fileOrBlobOrUrl,
3 function (img, data) {
4 if (data.imageHead && data.exif) {
5 // Reset Exif Orientation data:
6 loadImage.writeExifData(data.imageHead, data, 'Orientation', 1)
7 img.toBlob(function (blob) {
8 loadImage.replaceHead(blob, data.imageHead, function (newBlob) {
9 // do something with newBlob
10 })
11 }, 'image/jpeg')
12 }
13 },
14 { meta: true, orientation: true, canvas: true, maxWidth: 800 }
15)
Please note:
The Exif writer relies on the Exif tag offsets being available as
data.exifOffsets
property, which requires that Exif data has been parsed from
the image.
The Exif writer can only change existing values, not add new tags, e.g. it
cannot add an Exif Orientation
tag for an image that does not have one.
If you include the Load Image IPTC Parser extension, the argument passed to the
callback for parseMetaData
will contain the following additional properties if
IPTC data could be found in the given image:
iptc
: The parsed IPTC tagsiptcOffsets
: The parsed IPTC tag offsetsThe iptc
object stores the parsed IPTC tags:
1var objectname = data.iptc[5]
The iptc
and iptcOffsets
objects also provide a get()
method to retrieve
the tag value/offset via the tag's mapped name:
1var objectname = data.iptc.get('ObjectName')
By default, only the following names are mapped:
ObjectName
If you also include the Load Image IPTC Map library, additional tag mappings become available, as well as three additional methods:
iptc.getText()
iptc.getName()
iptc.getAll()
1var keywords = data.iptc.getText('Keywords') // e.g.: ['Weather','Sky'] 2 3var name = data.iptc.getName(5) // ObjectName 4 5// A map of all parsed tags with their mapped names/text as keys/values: 6var allTags = data.iptc.getAll()
The IPTC parser adds additional options:
disableIptc
: Disables IPTC parsing when true.disableIptcOffsets
: Disables storing IPTC tag offsets when true
.includeIptcTags
: A map of IPTC tags to include for parsing (includes all but
the excluded tags by default).excludeIptcTags
: A map of IPTC tags to exclude from parsing (defaults to
exclude ObjectPreviewData
).An example parsing only the ObjectName
tag:
1loadImage.parseMetaData( 2 fileOrBlob, 3 function (data) { 4 console.log('IPTC data: ', data.iptc) 5 }, 6 { 7 includeIptcTags: { 8 5: true // ObjectName 9 } 10 } 11)
An example excluding ApplicationRecordVersion
and ObjectPreviewData
:
1loadImage.parseMetaData( 2 fileOrBlob, 3 function (data) { 4 console.log('IPTC data: ', data.iptc) 5 }, 6 { 7 excludeIptcTags: { 8 0: true, // ApplicationRecordVersion 9 202: true // ObjectPreviewData 10 } 11 } 12)
The JavaScript Load Image library is released under the MIT license.
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
no SAST tool detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
11 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More