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

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.

License

NotificationsYou must be signed in to change notification settings

blueimp/JavaScript-Load-Image

Repository files navigation

A JavaScript library to load and transform image files.

Contents

Description

JavaScript Load Image is a library to load images provided asFile orBlobobjects or viaURL. It returns an optionallyscaled,cropped orrotated HTMLimg orcanvas element.

It also provides methods to parse image metadata to extractIPTC andExif tags as well as embedded thumbnailimages, to overwrite the Exif Orientation value and to restore the completeimage header after resizing.

Setup

Install viaNPM:

npm install blueimp-load-image

This will install the JavaScript files inside./node_modules/blueimp-load-image/js/ relative to your current directory, fromwhere 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 HTMLmarkup:

<scriptsrc="js/load-image.all.min.js"></script>

Or alternatively, choose which components you want to include:

<!-- required for all operations --><scriptsrc="js/load-image.js"></script><!-- required for scaling, cropping and as dependency for rotation --><scriptsrc="js/load-image-scale.js"></script><!-- required to parse meta data and to restore the complete image head --><scriptsrc="js/load-image-meta.js"></script><!-- required to parse meta data from images loaded via URL --><scriptsrc="js/load-image-fetch.js"></script><!-- required for rotation and cross-browser image orientation --><scriptsrc="js/load-image-orientation.js"></script><!-- required to parse Exif tags and cross-browser image orientation --><scriptsrc="js/load-image-exif.js"></script><!-- required to display text mappings for Exif tags --><scriptsrc="js/load-image-exif-map.js"></script><!-- required to parse IPTC tags --><scriptsrc="js/load-image-iptc.js"></script><!-- required to display text mappings for IPTC tags --><scriptsrc="js/load-image-iptc-map.js"></script>

Usage

Image loading

In your application code, use theloadImage() function withcallback style:

document.getElementById('file-input').onchange=function(){loadImage(this.files[0],function(img){document.body.appendChild(img)},{maxWidth:600}// Options)}

Or use thePromise based API like this (requires apolyfill for older browsers):

document.getElementById('file-input').onchange=function(){loadImage(this.files[0],{maxWidth:600}).then(function(data){document.body.appendChild(data.image)})}

Withasync/await(requires a modern browser or a code transpiler likeBabel orTypeScript):

document.getElementById('file-input').onchange=asyncfunction(){letdata=awaitloadImage(this.files[0],{maxWidth:600})document.body.appendChild(data.image)}

Image scaling

It is also possible to use the image scaling functionality directly with anexisting image:

varscaledImage=loadImage.scale(img,// img or canvas element{maxWidth:600})

Requirements

The JavaScript Load Image library has zero dependencies, but benefits from thefollowing twopolyfills:

Browser support

Browsers which implement the following APIs support all options:

This includes (but is not limited to) the following browsers:

  • Chrome 32+
  • Firefox 29+
  • Safari 8+
  • Mobile Chrome 42+ (Android)
  • Mobile Firefox 50+ (Android)
  • Mobile Safari 8+ (iOS)
  • Edge 74+
  • Edge Legacy 12+
  • Internet Explorer 10+*

* Internet Explorerrequires a polyfill for thePromisebased API.

Loading an image from a URL and applying transformations (scaling, cropping androtating - exceptorientation:true, which requires reading meta data) issupported by all browsers which implement theHTMLCanvasElementinterface.

Loading an image from a URL and scaling it in size is supported by all browserswhich implement theimg element andhas been tested successfully with browser engines as old as Internet Explorer 5(viaIE11's emulation mode).

TheloadImage() function applies options usingprogressive enhancementand falls back to a configuration that is supported by the browser, e.g. if thecanvas element is not supported, an equivalentimg element is returned.

API

Callback

Function signature

TheloadImage() function accepts aFile orBlob object or an imageURL as first argument.

If aFile orBlob is passed asparameter, it returns an HTMLimg element if the browser supports theURL API, alternatively aFileReader objectif theFileReader API is supported, orfalse.

It always returns an HTMLimg elementwhen passing an image URL:

varloadingImage=loadImage('https://example.org/image.png',function(img){document.body.appendChild(img)},{maxWidth:600})

Cancel image loading

Some browsers (e.g. Chrome) will cancel the image loading process if thesrcproperty of animg element is changed.
To avoid unnecessary requests, we can use thedata URLof a 1x1 pixel transparent GIF image assrc target to cancel the originalimage download.

To disable callback handling, we can also unset the image event handlers and formaximum browser compatibility, cancel the file reading process if the returnedobject is aFileReaderinstance:

varloadingImage=loadImage('https://example.org/image.png',function(img){document.body.appendChild(img)},{maxWidth:600})if(loadingImage){// Unset event handling for the loading image:loadingImage.onload=loadingImage.onerror=null// Cancel image loading process:if(loadingImage.abort){// FileReader instance, stop the file reading process:loadingImage.abort()}else{// HTMLImageElement element, cancel the original image request by changing// the target source to the data URL of a 1x1 pixel transparent image GIF:loadingImage.src='data:image/gif;base64,'+'R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'}}

Please note:
Theimg element (orFileReader instance) for the loading image is onlyreturned when using the callback style API and not available with thePromise based API.

Callback arguments

For the callback style API, the second argument toloadImage() must be acallback function, which is called when the image has been loaded or an erroroccurred while loading the image.

The callback function is passed two arguments:

  1. An HTMLimgelement orcanvaselement, or anEvent object oftypeerror.
  2. An object with the original image dimensions as properties and potentiallyadditionalmetadata.
loadImage(fileOrBlobOrUrl,function(img,data){document.body.appendChild(img)console.log('Original image width: ',data.originalWidth)console.log('Original image height: ',data.originalHeight)},{maxWidth:600,meta:true})

Please note:
The original image dimensions reflect the natural width and height of the loadedimage before applying any transformation.
For consistent values across browsers,metadata parsing hasto be enabled viameta:true, soloadImage can detect automatic imageorientation and normalize the dimensions.

Error handling

Example code implementing error handling:

loadImage(fileOrBlobOrUrl,function(img,data){if(img.type==='error'){console.error('Error loading image file')}else{document.body.appendChild(img)}},{maxWidth:600})

Promise

If theloadImage() function is called without acallback function as secondargument and thePromiseAPI is available, it returns aPromise object:

loadImage(fileOrBlobOrUrl,{maxWidth:600,meta:true}).then(function(data){document.body.appendChild(data.image)console.log('Original image width: ',data.originalWidth)console.log('Original image height: ',data.originalHeight)}).catch(function(err){// Handling image loading errorsconsole.log(err)})

ThePromise resolves with an object with the following properties:

  • image: An HTMLimg orcanvas 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 thecallback arguments section.

Ifmetadata has been parsed, additional properties might bepresent on the object.

If image loading fails, thePromise rejects with anEvent object of typeerror.

Options

The optional options argument toloadImage() allows to configure the imageloading.

It can be used the following way with the callback style:

loadImage(fileOrBlobOrUrl,function(img){document.body.appendChild(img)},{maxWidth:600,maxHeight:300,minWidth:100,minHeight:50,canvas:true})

Or the following way with thePromise based API:

loadImage(fileOrBlobOrUrl,{maxWidth:600,maxHeight:300,minWidth:100,minHeight:50,canvas:true}).then(function(data){document.body.appendChild(data.image)})

All settings are optional. By default, the image is returned as HTMLimgelement without any image size restrictions.

maxWidth

Defines the maximum width of theimg/canvas element.

maxHeight

Defines the maximum height of theimg/canvas element.

minWidth

Defines the minimum width of theimg/canvas element.

minHeight

Defines the minimum height of theimg/canvas element.

sourceWidth

The width of the sub-rectangle of the source image to draw into the destinationcanvas.
Defaults to the source image width and requirescanvas: true.

sourceHeight

The height of the sub-rectangle of the source image to draw into the destinationcanvas.
Defaults to the source image height and requirescanvas: true.

top

The top margin of the sub-rectangle of the source image.
Defaults to0 and requirescanvas: true.

right

The right margin of the sub-rectangle of the source image.
Defaults to0 and requirescanvas: true.

bottom

The bottom margin of the sub-rectangle of the source image.
Defaults to0 and requirescanvas: true.

left

The left margin of the sub-rectangle of the source image.
Defaults to0 and requirescanvas: true.

contain

Scales the image up/down to contain it in the max dimensions if set totrue.
This emulates the CSS featurebackground-image: contain.

cover

Scales the image up/down to cover the max dimensions with the image dimensionsif set totrue.
This emulates the CSS featurebackground-image: cover.

aspectRatio

Crops the image to the given aspect ratio (e.g.16/9).
Setting theaspectRatio also enables thecrop option.

pixelRatio

Defines the ratio of the canvas pixels to the physical image pixels on thescreen.
Should be set towindow.devicePixelRatiounless the scaled image is not rendered on screen.
Defaults to1 and requirescanvas: true.

downsamplingRatio

Defines the ratio in which the image is downsampled (scaled down in steps).
By default, images are downsampled in one step.
With a ratio of0.5, each step scales the image to half the size, beforereaching the target dimensions.
Requirescanvas: true.

imageSmoothingEnabled

If set tofalse,disables image smoothing.
Defaults totrue and requirescanvas: true.

imageSmoothingQuality

Sets thequality of image smoothing.
Possible values:'low','medium','high'
Defaults to'low' and requirescanvas: true.

crop

Crops the image to themaxWidth/maxHeight constraints if set totrue.
Enabling thecrop option also enables thecanvas option.

orientation

Transform the canvas according to the specified Exif orientation, which can beaninteger in the range of1 to8 or the boolean valuetrue.

When set totrue, it will set the orientation value based on the Exif data ofthe image, which will be parsed automatically if the Exif extension isavailable.

Exif orientation values to correctly display the letter F:

    1             2  ██████        ██████  ██                ██  ████            ████  ██                ██  ██                ██    3             4      ██        ██      ██        ██    ████        ████      ██        ██  ██████        ██████    5             6██████████    ████  ██        ██  ████            ██████████    7             8        ██    ██████████    ██  ██        ██  ████████████            ██

Settingorientation totrue enables thecanvas andmeta options, unlessthe browser supports automatic image orientation (seebrowser support for image-orientation).

Settingorientation to1 enables thecanvas andmeta options if thebrowser does support automatic image orientation (to allow reset of theorientation).

Settingorientation to an integer in the range of2 to8 always enablesthecanvas option and also enables themeta option if the browser supportsautomatic image orientation (again to allow reset).

meta

Automatically parses the image metadata if set totrue.

If metadata has been found, the data object passed as second argument to thecallback function has additional properties (seemetadata parsing).

If the file is given as URL and the browser supports thefetch API or theXHRresponseTypeblob, fetches the file asBlob to be able to parse the metadata.

canvas

Returns the image ascanvas element ifset totrue.

crossOrigin

Sets thecrossOrigin property on theimg element for loadingCORS enabled images.

noRevoke

By default, thecreated object URLis revoked after the image has been loaded, except when this option is set totrue.

Metadata parsing

If the Load Image Meta extension is included, it is possible to parse image metadata automatically with themeta option:

loadImage(fileOrBlobOrUrl,function(img,data){console.log('Original image head: ',data.imageHead)console.log('Exif data: ',data.exif)// requires exif extensionconsole.log('IPTC data: ',data.iptc)// requires iptc extension},{meta:true})

Or alternatively vialoadImage.parseMetaData, which can be used with anavailableFile orBlob object as first argument:

loadImage.parseMetaData(fileOrBlob,function(data){console.log('Original image head: ',data.imageHead)console.log('Exif data: ',data.exif)// requires exif extensionconsole.log('IPTC data: ',data.iptc)// requires iptc extension},{maxMetaDataSize:262144})

Or using thePromisebased API:

loadImage.parseMetaData(fileOrBlob,{maxMetaDataSize:262144}).then(function(data){console.log('Original image head: ',data.imageHead)console.log('Exif data: ',data.exif)// requires exif extensionconsole.log('IPTC data: ',data.iptc)// requires iptc extension})

The Metadata extension adds additional options used for theparseMetaDatamethod:

  • maxMetaDataSize: Maximum number of bytes of metadata to parse.
  • disableImageHead: Disable parsing the original image head.
  • disableMetaDataParsers: Disable parsing metadata (image head only)

Image head

Resized JPEG images can be combined with their original image head vialoadImage.replaceHead, which requires the resized image asBlob object asfirst argument and anArrayBuffer image head as second argument.

With callback style, the third argument must be acallback function, which iscalled with the newBlob object:

loadImage(fileOrBlobOrUrl,function(img,data){if(data.imageHead){img.toBlob(function(blob){loadImage.replaceHead(blob,data.imageHead,function(newBlob){// do something with the new Blob object})},'image/jpeg')}},{meta:true,canvas:true,maxWidth:800})

Or using thePromisebased API like this:

loadImage(fileOrBlobOrUrl,{meta:true,canvas:true,maxWidth:800}).then(function(data){if(!data.imageHead)thrownewError('Could not parse image metadata')returnnewPromise(function(resolve){data.image.toBlob(function(blob){data.blob=blobresolve(data)},'image/jpeg')})}).then(function(data){returnloadImage.replaceHead(data.blob,data.imageHead)}).then(function(blob){// do something with the new Blob object}).catch(function(err){console.error(err)})

Please note:
Blob objects of resized images can be created viaHTMLCanvasElement.toBlob.
blueimp-canvas-to-blobprovides a polyfill for browsers without nativecanvas.toBlob() support.

Exif parser

If you include the Load Image Exif Parser extension, the argument passed to thecallback forparseMetaData will contain the following additional properties ifExif data could be found in the given image:

  • exif: The parsed Exif tags
  • exifOffsets: The parsed Exif tag offsets
  • exifTiffOffset: TIFF header offset (used for offset pointers)
  • exifLittleEndian: little endian order if true, big endian if false

Theexif object stores the parsed Exif tags:

varorientation=data.exif[0x0112]// Orientation

Theexif andexifOffsets objects also provide aget() method to retrievethe tag value/offset via the tag's mapped name:

varorientation=data.exif.get('Orientation')varorientationOffset=data.exifOffsets.get('Orientation')

By default, only the following names are mapped:

If you also include the Load Image Exif Map library, additional tag mappingsbecome available, as well as three additional methods:

  • exif.getText()
  • exif.getName()
  • exif.getAll()
varorientationText=data.exif.getText('Orientation')// e.g. "Rotate 90° CW"varname=data.exif.getName(0x0112)// "Orientation"// A map of all parsed tags with their mapped names/text as keys/values:varallTags=data.exif.getAll()

Exif Thumbnail

Example code displaying a thumbnail image embedded into the Exif metadata:

loadImage(fileOrBlobOrUrl,function(img,data){varexif=data.exifvarthumbnail=exif&&exif.get('Thumbnail')varblob=thumbnail&&thumbnail.get('Blob')if(blob){loadImage(blob,function(thumbImage){document.body.appendChild(thumbImage)},{orientation:exif.get('Orientation')})}},{meta:true})

Exif IFD

Example code displaying data from the Exif IFD (Image File Directory) thatcontains Exif specified TIFF tags:

loadImage(fileOrBlobOrUrl,function(img,data){varexifIFD=data.exif&&data.exif.get('Exif')if(exifIFD){// Map of all Exif IFD tags with their mapped names/text as keys/values:console.log(exifIFD.getAll())// A specific Exif IFD tag value:console.log(exifIFD.get('UserComment'))}},{meta:true})

GPSInfo IFD

Example code displaying data from the Exif IFD (Image File Directory) thatcontainsGPS info:

loadImage(fileOrBlobOrUrl,function(img,data){vargpsInfo=data.exif&&data.exif.get('GPSInfo')if(gpsInfo){// Map of all GPSInfo tags with their mapped names/text as keys/values:console.log(gpsInfo.getAll())// A specific GPSInfo tag value:console.log(gpsInfo.get('GPSLatitude'))}},{meta:true})

Interoperability IFD

Example code displaying data from the Exif IFD (Image File Directory) thatcontains Interoperability data:

loadImage(fileOrBlobOrUrl,function(img,data){varinteroperabilityData=data.exif&&data.exif.get('Interoperability')if(interoperabilityData){// The InteroperabilityIndex tag value:console.log(interoperabilityData.get('InteroperabilityIndex'))}},{meta:true})

Exif parser options

The Exif parser adds additional options:

  • disableExif: Disables Exif parsing whentrue.
  • disableExifOffsets: Disables storing Exif tag offsets whentrue.
  • includeExifTags: A map of Exif tags to include for parsing (includes all butthe excluded tags by default).
  • excludeExifTags: A map of Exif tags to exclude from parsing (defaults toexcludeExifMakerNote).

An example parsing only Orientation, Thumbnail and ExifVersion tags:

loadImage.parseMetaData(fileOrBlob,function(data){console.log('Exif data: ',data.exif)},{includeExifTags:{0x0112:true,// Orientationifd1:{0x0201:true,// JPEGInterchangeFormat (Thumbnail data offset)0x0202:true// JPEGInterchangeFormatLength (Thumbnail data length)},0x8769:{// ExifIFDPointer0x9000:true// ExifVersion}}})

An example excludingExifMakerNote andGPSInfo:

loadImage.parseMetaData(fileOrBlob,function(data){console.log('Exif data: ',data.exif)},{excludeExifTags:{0x8769:{// ExifIFDPointer0x927c:true// MakerNote},0x8825:true// GPSInfoIFDPointer}})

Exif writer

The Exif parser extension also includes a minimal writer that allows to overridethe ExifOrientation value in the parsedimageHeadArrayBuffer:

loadImage(fileOrBlobOrUrl,function(img,data){if(data.imageHead&&data.exif){// Reset Exif Orientation data:loadImage.writeExifData(data.imageHead,data,'Orientation',1)img.toBlob(function(blob){loadImage.replaceHead(blob,data.imageHead,function(newBlob){// do something with newBlob})},'image/jpeg')}},{meta:true,orientation:true,canvas:true,maxWidth:800})

Please note:
The Exif writer relies on the Exif tag offsets being available asdata.exifOffsets property, which requires that Exif data has been parsed fromthe image.
The Exif writer can only change existing values, not add new tags, e.g. itcannot add an ExifOrientation tag for an image that does not have one.

IPTC parser

If you include the Load Image IPTC Parser extension, the argument passed to thecallback forparseMetaData will contain the following additional properties ifIPTC data could be found in the given image:

  • iptc: The parsed IPTC tags
  • iptcOffsets: The parsed IPTC tag offsets

Theiptc object stores the parsed IPTC tags:

varobjectname=data.iptc[5]

Theiptc andiptcOffsets objects also provide aget() method to retrievethe tag value/offset via the tag's mapped name:

varobjectname=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 mappingsbecome available, as well as three additional methods:

  • iptc.getText()
  • iptc.getName()
  • iptc.getAll()
varkeywords=data.iptc.getText('Keywords')// e.g.: ['Weather','Sky']varname=data.iptc.getName(5)// ObjectName// A map of all parsed tags with their mapped names/text as keys/values:varallTags=data.iptc.getAll()

IPTC parser options

The IPTC parser adds additional options:

  • disableIptc: Disables IPTC parsing when true.
  • disableIptcOffsets: Disables storing IPTC tag offsets whentrue.
  • includeIptcTags: A map of IPTC tags to include for parsing (includes all butthe excluded tags by default).
  • excludeIptcTags: A map of IPTC tags to exclude from parsing (defaults toexcludeObjectPreviewData).

An example parsing only theObjectName tag:

loadImage.parseMetaData(fileOrBlob,function(data){console.log('IPTC data: ',data.iptc)},{includeIptcTags:{5:true// ObjectName}})

An example excludingApplicationRecordVersion andObjectPreviewData:

loadImage.parseMetaData(fileOrBlob,function(data){console.log('IPTC data: ',data.iptc)},{excludeIptcTags:{0:true,// ApplicationRecordVersion202:true// ObjectPreviewData}})

License

The JavaScript Load Image library is released under theMIT license.

Credits

  • Original image metadata handling implemented with the help and contribution ofAchim Stöhr.
  • Original Exif tags mapping based on Jacob Seidelin'sexif-js library.
  • Original IPTC parser implementation byDave Bevan.

About

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.

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp