blueimp-load-image中文文档|blueimp-load-image js中文教程|解析
JavaScript 加载图片
用于加载和转换图像文件的 JavaScript 库。
内容
描述
JavaScript Load Image 是一个库,用于加载作为File
或Blob
对象或通过URL
. 它返回一个可选的缩放、裁剪或
旋转的HTMLimg
或canvas
元素。
它还提供了解析图像元数据以提取
IPTC和
Exif标签以及嵌入的缩略图图像、覆盖 Exif 方向值并在调整大小后恢复完整图像标题的方法。
设置
通过NPM安装:
npm install blueimp-load-image
这会将 JavaScript 文件安装在./node_modules/blueimp-load-image/js/
相对于您当前目录的内部
,您可以从那里将它们复制到您的 Web 服务器提供的文件夹中。
接下来在 HTML 标记中包含合并和缩小的 JavaScript 加载图像脚本:
<script src="js/load-image.all.min.js"></script>
或者,选择要包含的组件:
<!-- required for all operations -->
<script src="js/load-image.js"></script>
<!-- required for scaling, cropping and as dependency for rotation -->
<script src="js/load-image-scale.js"></script>
<!-- required to parse meta data and to restore the complete image head -->
<script src="js/load-image-meta.js"></script>
<!-- required to parse meta data from images loaded via URL -->
<script src="js/load-image-fetch.js"></script>
<!-- required for rotation and cross-browser image orientation -->
<script src="js/load-image-orientation.js"></script>
<!-- required to parse Exif tags and cross-browser image orientation -->
<script src="js/load-image-exif.js"></script>
<!-- required to display text mappings for Exif tags -->
<script src="js/load-image-exif-map.js"></script>
<!-- required to parse IPTC tags -->
<script src="js/load-image-iptc.js"></script>
<!-- required to display text mappings for IPTC tags -->
<script src="js/load-image-iptc-map.js"></script>
用法
图片加载
在您的应用程序代码中,使用回调样式的loadImage()
函数
:
document.getElementById('file-input').onchange = function () {
loadImage(
this.files[0],
function (img) {
document.body.appendChild(img)
},
{ maxWidth: 600 } // Options
)
}
或者像这样使用基于Promise的 API(旧浏览器需要一个 polyfill):
document.getElementById('file-input').onchange = function () {
loadImage(this.files[0], { maxWidth: 600 }).then(function (data) {
document.body.appendChild(data.image)
})
}
使用
async/await
(需要现代浏览器或Babel或TypeScript等代码转译器
):
document.getElementById('file-input').onchange = async function () {
let data = await loadImage(this.files[0], { maxWidth: 600 })
document.body.appendChild(data.image)
}
图像缩放
也可以直接对现有图像使用图像缩放功能:
var scaledImage = loadImage.scale(
img, // img or canvas element
{ maxWidth: 600 }
)
要求
JavaScript 加载图像库具有零依赖项,但受益于以下两个
polyfill:
-
blueimp-canvas-to-blob
用于没有原生HTMLCanvasElement.toBlob
支持的浏览器
,用于Blob
从canvas
元素创建对象。 -
promise-polyfill能够在没有本机支持的浏览器中使用
基于Promise的loadImage
APIPromise
。
浏览器支持
实现以下 API 的浏览器支持所有选项:
- 从 File 和 Blob 对象加载图像:
- 解析元数据:
- FileReader.readAsArrayBuffer
- 切片
-
DataView
(不需要BigInt
支持)
- 从通过 URL 加载的图像中解析元数据:
- 基于 Promise 的 API:
这包括(但不限于)以下浏览器:
- 铬 32+
- 火狐 29+
- 野生动物园 8+
- 移动版 Chrome 42+ (Android)
- 移动版 Firefox 50+ (Android)
- 移动版 Safari 8+ (iOS)
- 边缘 74+
- 边缘遗产 12+
- Internet Explorer 10+
*
*
Internet Explorer需要Promise
基于 API的 polyfill 。
orientation:true
所有实现HTMLCanvasElement
接口的浏览器都支持从 URL 加载图像并应用转换(缩放、裁剪和旋转 – 除了需要读取元数据)
。
所有实现img元素的浏览器都支持从 URL 加载图像并缩放它的大小,
并且已经在与 Internet Explorer 5(通过IE11 的仿真模式)一样古老的浏览器引擎上成功测试
。
该loadImage()
函数使用渐进增强应用选项
并回退到浏览器支持的配置,例如,如果
canvas
不支持该img
元素,则返回等效元素。
应用程序接口
打回来
函数签名
该loadImage()
函数接受一个
File或
Blob对象或一个图像 URL 作为第一个参数。
如果File或
Blob作为参数传递,img
如果浏览器支持URL API ,它将返回一个 HTML元素,或者如果支持
API
,则返回FileReader对象FileReader
,或者false
.
传递图像 URL 时,它始终返回 HTML
img元素:
var loadingImage = loadImage(
'https://example.org/image.png',
function (img) {
document.body.appendChild(img)
},
{ maxWidth: 600 }
)
取消图片加载
如果元素的src
属性img
发生更改,某些浏览器(例如 Chrome)将取消图像加载过程。
为了避免不必要的请求,我们可以使用
1×1像素透明GIF图片的
数据URL作为src
目标,取消原始图片下载。
要禁用回调处理,我们还可以取消设置图像事件处理程序,并为了最大的浏览器兼容性,如果返回的对象是FileReader
实例,则取消文件读取过程
:
var loadingImage = 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'
}
}
请注意:加载图像
的img
元素(或FileReader
实例)仅在使用回调样式 API 时返回,并且不适用于
基于Promise的 API。
回调参数
对于回调风格的API,to的第二个参数loadImage()
必须是一个
callback
函数,当图片加载完毕或者加载图片出错时调用。
回调函数传递两个参数:
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 }
)
请注意:
原始图像尺寸反映了应用任何转换之前加载图像的自然宽度和高度。
为了跨浏览器保持一致的值,必须通过 启用元数据解析meta:true
,这样loadImage
才能检测自动图像方向并规范化尺寸。
错误处理
实现错误处理的示例代码:
loadImage(
fileOrBlobOrUrl,
function (img, data) {
if (img.type === 'error') {
console.error('Error loading image file')
} else {
document.body.appendChild(img)
}
},
{ maxWidth: 600 }
)
承诺
如果在loadImage()
没有callback
函数作为第二个参数的情况下调用该函数并且
Promise
API 可用,它将返回一个Promise
对象:
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 errors
console.log(err)
})
在Promise
与具有以下属性的对象决定:
另请阅读回调参数部分中有关原始图像尺寸标准化的说明
。
如果元数据已被解析,则对象上可能会出现其他属性。
如果图像加载失败,则Promise
拒绝类型为
Event对象
error
。
选项
可选的 options 参数loadImage()
允许配置图像加载。
它可以通过以下方式与回调样式一起使用:
loadImage(
fileOrBlobOrUrl,
function (img) {
document.body.appendChild(img)
},
{
maxWidth: 600,
maxHeight: 300,
minWidth: 100,
minHeight: 50,
canvas: true
}
)
或者使用Promise
基于 API的以下方式:
loadImage(fileOrBlobOrUrl, {
maxWidth: 600,
maxHeight: 300,
minWidth: 100,
minHeight: 50,
canvas: true
}).then(function (data) {
document.body.appendChild(data.image)
})
所有设置都是可选的。默认情况下,图像作为 HTMLimg
元素返回,没有任何图像大小限制。
最大宽度
定义img
/canvas
元素的最大宽度。
最大高度
定义img
/canvas
元素的最大高度。
最小宽度
定义img
/canvas
元素的最小宽度。
最小高度
定义img
/canvas
元素的最小高度。
源宽度
要绘制到目标画布中的源图像子矩形的宽度。
默认为源图像宽度,需要canvas: true
.
源高度
要绘制到目标画布中的源图像子矩形的高度。
默认为源图像高度,需要canvas: true
.
最佳
源图像子矩形的上边距。
默认为0
并需要canvas: true
.
对
源图像子矩形的右边距。
默认为0
并需要canvas: true
.
底部
源图像子矩形的底部边距。
默认为0
并需要canvas: true
.
剩下
源图像子矩形的左边距。
默认为0
并需要canvas: true
.
包含
如果设置为 ,则向上/向下缩放图像以将其包含在最大尺寸中true
。
这模拟了 CSS 功能
background-image: contains。
覆盖
如果设置为 ,则向上/向下缩放图像以覆盖图像尺寸的最大尺寸true
。
这模拟了 CSS 功能
background-image: cover。
纵横比
将图像裁剪为给定的纵横比(例如16/9
)。
设置aspectRatio
也会启用该crop
选项。
像素比
定义画布像素与屏幕上物理图像像素的比率。
应设置为
window.devicePixelRatio
除非缩放后的图像未在屏幕上呈现。
默认为1
并需要canvas: true
.
下采样率
定义图像下采样的比率(逐步缩小)。
默认情况下,图像是一步下采样的。
比率为 时0.5
,每一步将图像缩放到一半大小,然后达到目标尺寸。
需要canvas: true
.
图像平滑已启用
如果设置为false
,则
禁用图像平滑。
默认为true
并需要canvas: true
.
图像平滑质量
设置图像平滑的
质量。
可能的值:'low'
, 'medium'
,'high'
默认为'low'
和 requires canvas: true
。
庄稼
如果设置为 ,则将图像裁剪到maxWidth
/maxHeight
约束true
。
启用该crop
选项也会启用该canvas
选项。
方向
根据指定的 Exif 方向转换画布,可以是to或布尔值integer
范围内的一个。1
8
true
设置为 时true
,将根据图片的 Exif 数据设置方向值,如果 Exif 扩展名可用,将自动解析该值。
Exif 方向值以正确显示字母 F:
1 2
██████ ██████
██ ██
████ ████
██ ██
██ ██
3 4
██ ██
██ ██
████ ████
██ ██
██████ ██████
5 6
██████████ ██
██ ██ ██ ██
██ ██████████
7 8
██ ██████████
██ ██ ██ ██
██████████ ██
设置orientation
为true
启用canvas
和meta
选项,除非浏览器支持自动图像方向(请参阅
浏览器对图像方向的支持)。
如果浏览器确实支持自动图像方向(以允许重置方向),则设置orientation
为1
启用canvas
和meta
选项。
设置orientation
在的范围内的整数2
,以8
始终使canvas
选项,并且还能够使meta
选择浏览器是否支持自动图像方向(再一次,以允许复位)。
元
如果设置为 ,则自动解析图像元数据true
。
如果找到元数据,则作为第二个参数传递给回调函数的数据对象具有附加属性(请参阅
元数据解析)。
如果文件以 URL 形式给出并且浏览器支持
fetch API或 XHR
responseType
blob
,则提取文件Blob
以便能够解析元数据。
帆布
如果设置为 ,则将图像作为画布元素返回
true
。
跨原点
设置用于加载启用 CORS 的图像crossOrigin
的img
元素
的属性。
不撤销
默认情况下,在
加载图像后撤销创建的对象 URL,除非此选项设置为
true
。
元数据解析
如果包含加载图像元扩展,则可以使用以下meta
选项自动解析图像元数据:
loadImage(
fileOrBlobOrUrl,
function (img, data) {
console.log('Original image head: ', data.imageHead)
console.log('Exif data: ', data.exif) // requires exif extension
console.log('IPTC data: ', data.iptc) // requires iptc extension
},
{ meta: true }
)
或者通过loadImage.parseMetaData
,它可以与可用File
或Blob
对象一起用作第一个参数:
loadImage.parseMetaData(
fileOrBlob,
function (data) {
console.log('Original image head: ', data.imageHead)
console.log('Exif data: ', data.exif) // requires exif extension
console.log('IPTC data: ', data.iptc) // requires iptc extension
},
{
maxMetaDataSize: 262144
}
)
或者使用
基于Promise的 API:
loadImage
.parseMetaData(fileOrBlob, {
maxMetaDataSize: 262144
})
.then(function (data) {
console.log('Original image head: ', data.imageHead)
console.log('Exif data: ', data.exif) // requires exif extension
console.log('IPTC data: ', data.iptc) // requires iptc extension
})
元数据扩展添加了用于该parseMetaData
方法的其他选项:
-
maxMetaDataSize
:要解析的元数据的最大字节数。 -
disableImageHead
: 禁用解析原始图像头。 -
disableMetaDataParsers
:禁用解析元数据(仅限图像头)
图像头
调整大小的 JPEG 图像可以通过 与它们的原始图像头部组合
loadImage.replaceHead
,这需要调整大小的图像作为Blob
对象作为第一个参数,ArrayBuffer
图像头部作为第二个参数。
使用回调风格,第三个参数必须是一个callback
函数,它被新Blob
对象调用:
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 }
)
或者
像这样使用
基于Promise的 API:
loadImage(fileOrBlobOrUrl, { meta: true, canvas: true, maxWidth: 800 })
.then(function (data) {
if (!data.imageHead) throw new Error('Could not parse image metadata')
return new Promise(function (resolve) {
data.image.toBlob(function (blob) {
data.blob = blob
resolve(data)
}, 'image/jpeg')
})
})
.then(function (data) {
return loadImage.replaceHead(data.blob, data.imageHead)
})
.then(function (blob) {
// do something with the new Blob object
})
.catch(function (err) {
console.error(err)
})
请注意:
Blob
可以通过HTMLCanvasElement.toBlob创建调整大小图像的对象
。
blueimp-canvas-to-blob
为没有原生canvas.toBlob()
支持的浏览器提供了一个polyfill。
Exif 解析器
如果包含 Load Image Exif Parser 扩展,则传递给回调的参数parseMetaData
将包含以下附加属性,如果可以在给定图像中找到 Exif 数据:
-
exif
: 解析的 Exif 标签 -
exifOffsets
: 解析的 Exif 标签偏移量 -
exifTiffOffset
: TIFF 头偏移(用于偏移指针) -
exifLittleEndian
: 如果为真则为小端顺序,如果为假则为大端
该exif
对象存储解析的 Exif 标签:
var orientation = data.exif[0x0112] // Orientation
在exif
与exifOffsets
对象也提供了一个get()
检索标签值的方法/通过标签的映射名称偏移量:
var orientation = data.exif.get('Orientation')
var orientationOffset = data.exifOffsets.get('Orientation')
默认情况下,仅映射以下名称:
Orientation
-
Thumbnail
(见Exif 缩略图) -
Exif
(见Exif IFD) -
GPSInfo
(见GPSInfo IFD) -
Interoperability
(请参阅互操作性 IFD)
如果您还包括 Load Image Exif Map 库,则可以使用其他标签映射以及三种其他方法:
exif.getText()
exif.getName()
exif.getAll()
var orientationText = data.exif.getText('Orientation') // e.g. "Rotate 90° CW"
var name = data.exif.getName(0x0112) // "Orientation"
// A map of all parsed tags with their mapped names/text as keys/values:
var allTags = data.exif.getAll()
Exif 缩略图
显示嵌入 Exif 元数据的缩略图的示例代码:
loadImage(
fileOrBlobOrUrl,
function (img, data) {
var exif = data.exif
var thumbnail = exif && exif.get('Thumbnail')
var blob = thumbnail && thumbnail.get('Blob')
if (blob) {
loadImage(
blob,
function (thumbImage) {
document.body.appendChild(thumbImage)
},
{ orientation: exif.get('Orientation') }
)
}
},
{ meta: true }
)
Exif IFD
示例代码显示来自 Exif IFD(图像文件目录)的数据,其中包含 Exif 指定的 TIFF 标签:
loadImage(
fileOrBlobOrUrl,
function (img, data) {
var exifIFD = 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
显示来自包含GPS信息的 Exif IFD(图像文件目录)的数据的示例代码:
loadImage(
fileOrBlobOrUrl,
function (img, data) {
var gpsInfo = 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 }
)
互操作性IFD
显示来自包含互操作性数据的 Exif IFD(图像文件目录)的数据的示例代码:
loadImage(
fileOrBlobOrUrl,
function (img, data) {
var interoperabilityData = data.exif && data.exif.get('Interoperability')
if (interoperabilityData) {
// The InteroperabilityIndex tag value:
console.log(interoperabilityData.get('InteroperabilityIndex'))
}
},
{ meta: true }
)
Exif 解析器选项
Exif 解析器添加了额外的选项:
-
disableExif
: 禁用 Exif 解析true
。 -
disableExifOffsets
:禁用存储 Exif 标记偏移量时true
。 -
includeExifTags
:要包含用于解析的 Exif 标记的映射(默认情况下包括除排除的标记之外的所有标记)。 -
excludeExifTags
:要从解析中排除的 Exif 标签的映射(默认为 excludeExif
MakerNote
)。
仅解析 Orientation、Thumbnail 和 ExifVersion 标签的示例:
loadImage.parseMetaData(
fileOrBlob,
function (data) {
console.log('Exif data: ', data.exif)
},
{
includeExifTags: {
0x0112: true, // Orientation
ifd1: {
0x0201: true, // JPEGInterchangeFormat (Thumbnail data offset)
0x0202: true // JPEGInterchangeFormatLength (Thumbnail data length)
},
0x8769: {
// ExifIFDPointer
0x9000: true // ExifVersion
}
}
}
)
排除Exif
MakerNote
和的示例GPSInfo
:
loadImage.parseMetaData(
fileOrBlob,
function (data) {
console.log('Exif data: ', data.exif)
},
{
excludeExifTags: {
0x8769: {
// ExifIFDPointer
0x927c: true // MakerNote
},
0x8825: true // GPSInfoIFDPointer
}
}
)
Exif 编写器
Exif 解析器扩展还包括一个最小的编写器,允许覆盖Orientation
解析的 Exif值imageHead
ArrayBuffer
:
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 }
)
请注意:
Exif 编写器依赖于 Exif 标记偏移量作为data.exifOffsets
属性可用
,这要求已从图像中解析 Exif 数据。
Exif 编写器只能更改现有值,不能添加新标签,例如,它不能为没有 ExifOrientation
标签的图像添加 Exif标签。
IPTC解析器
如果包含加载图像 IPTC 解析器扩展,则传递给回调的参数parseMetaData
将包含以下附加属性,如果可以在给定图像中找到 IPTC 数据:
-
iptc
: 解析的 IPTC 标签 -
iptcOffsets
: 解析的 IPTC 标签偏移量
该iptc
对象存储解析的 IPTC 标签:
var objectname = data.iptc[5]
在iptc
与iptcOffsets
对象也提供了一个get()
检索标签值的方法/通过标签的映射名称偏移量:
var objectname = data.iptc.get('ObjectName')
默认情况下,仅映射以下名称:
ObjectName
如果您还包括 Load Image IPTC Map 库,则可以使用其他标签映射以及三种其他方法:
iptc.getText()
iptc.getName()
iptc.getAll()
var keywords = data.iptc.getText('Keywords') // e.g.: ['Weather','Sky']
var name = data.iptc.getName(5) // ObjectName
// A map of all parsed tags with their mapped names/text as keys/values:
var allTags = data.iptc.getAll()
IPTC 解析器选项
IPTC 解析器添加了其他选项:
-
disableIptc
:当为真时禁用 IPTC 解析。 -
disableIptcOffsets
:禁用存储 IPTC 标记偏移量时true
。 -
includeIptcTags
:要包含用于解析的 IPTC 标记的映射(默认情况下包括除排除标记之外的所有标记)。 -
excludeIptcTags
:要从解析中排除的 IPTC 标签的映射(默认为 excludeObjectPreviewData
)。
仅解析ObjectName
标签的示例:
loadImage.parseMetaData(
fileOrBlob,
function (data) {
console.log('IPTC data: ', data.iptc)
},
{
includeIptcTags: {
5: true // ObjectName
}
}
)
排除ApplicationRecordVersion
和的示例ObjectPreviewData
:
loadImage.parseMetaData(
fileOrBlob,
function (data) {
console.log('IPTC data: ', data.iptc)
},
{
excludeIptcTags: {
0: true, // ApplicationRecordVersion
202: true // ObjectPreviewData
}
}
)
执照
JavaScript 加载图像库是在MIT 许可下发布的
。
学分
- 在 Achim Stöhr 的帮助和贡献下实现的原始图像元数据处理。
- 基于 Jacob Seidelin 的exif-js库的原始 Exif 标签映射
。 - Dave Bevan 的原始 IPTC 解析器实现
。