1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-12-23 01:30:01 +01:00
blog/gatsby/createExifFields.js

94 lines
2.0 KiB
JavaScript
Raw Normal View History

2018-10-14 02:25:24 +02:00
const fastExif = require('fast-exif')
const Fraction = require('fraction.js')
const dms2dec = require('dms2dec')
exports.createExifFields = async (node, createNodeField) => {
let exifData
try {
exifData = await fastExif.read(node.absolutePath, true)
if (!exifData) return
constructExifFields(exifData, createNodeField, node)
} catch (error) {
// console.error(`${node.name}: ${error.message}`)
return null // just silently fail when exif can't be extracted
}
2018-10-14 02:25:24 +02:00
}
const getGps = gpsData => {
if (!gpsData) return
2018-10-14 02:25:24 +02:00
const { GPSLatitudeRef, GPSLatitude, GPSLongitudeRef, GPSLongitude } = gpsData
2018-10-14 02:25:24 +02:00
const GPSdec = dms2dec(
GPSLatitude,
GPSLatitudeRef,
GPSLongitude,
GPSLongitudeRef
)
const latitude = GPSdec[0]
const longitude = GPSdec[1]
return { latitude, longitude }
}
const getExposure = exposureMode => {
const exposureShortened = parseFloat(exposureMode.toFixed(2))
2018-10-14 02:25:24 +02:00
let exposure
if (exposureMode === 0) {
2018-10-14 02:25:24 +02:00
exposure = `+/- ${exposureShortened} ev`
} else if (exposureMode > 0) {
2018-10-14 02:25:24 +02:00
exposure = `+ ${exposureShortened} ev`
} else {
exposure = `${exposureShortened} ev`
}
return exposure
}
const constructExifFields = (exifData, createNodeField, node) => {
const { Model } = exifData.image
const {
ISO,
FNumber,
ExposureTime,
FocalLength,
ExposureBiasValue,
ExposureMode,
LensModel
} = exifData.exif
const iso = `ISO ${ISO}`
const fstop = `ƒ ${FNumber}`
const focalLength = `${FocalLength}mm`
// Shutter speed
const { n, d } = new Fraction(ExposureTime)
const shutterspeed = `${n}/${d}s`
// GPS
let latitude
let longitude
if (exifData.gps) ({ latitude, longitude } = getGps(exifData.gps))
// Exposure
const exposure = getExposure(ExposureBiasValue || ExposureMode)
2018-10-14 02:25:24 +02:00
// add exif fields to type File
createNodeField({
node,
name: 'exif',
value: {
iso,
model: Model,
2018-10-14 02:25:24 +02:00
fstop,
shutterspeed,
focalLength,
lensModel: LensModel,
2018-10-14 02:25:24 +02:00
exposure,
gps: { latitude, longitude }
2018-10-14 02:25:24 +02:00
}
})
}