1 import { copy, readFile, remove, rename } from 'fs-extra'
2 import Jimp, { read as jimpRead } from 'jimp'
3 import { join } from 'path'
4 import { ColorActionName } from '@jimp/plugin-color'
5 import { getLowercaseExtension } from '@shared/core-utils'
6 import { buildUUID } from '@shared/extra-utils'
7 import { convertWebPToJPG, generateThumbnailFromVideo, processGIF } from './ffmpeg'
8 import { logger, loggerTagsFactory } from './logger'
10 const lTags = loggerTagsFactory('image-utils')
12 function generateImageFilename (extension = '.jpg') {
13 return buildUUID() + extension
16 async function processImage (options: {
19 newSize: { width: number, height: number }
20 keepOriginal?: boolean // default false
22 const { path, destination, newSize, keepOriginal = false } = options
24 const extension = getLowercaseExtension(path)
26 if (path === destination) {
27 throw new Error('Jimp/FFmpeg needs an input path different that the output path.')
30 logger.debug('Processing image %s to %s.', path, destination)
32 // Use FFmpeg to process GIF
33 if (extension === '.gif') {
34 await processGIF({ path, destination, newSize })
36 await jimpProcessor(path, destination, newSize, extension)
39 if (keepOriginal !== true) await remove(path)
42 async function generateImageFromVideoFile (options: {
46 size: { width: number, height: number }
48 const { fromPath, folder, imageName, size } = options
50 const pendingImageName = 'pending-' + imageName
51 const pendingImagePath = join(folder, pendingImageName)
54 await generateThumbnailFromVideo({ fromPath, folder, imageName })
56 const destination = join(folder, imageName)
57 await processImage({ path: pendingImagePath, destination, newSize: size })
59 logger.error('Cannot generate image from video %s.', fromPath, { err, ...lTags() })
62 await remove(pendingImagePath)
64 logger.debug('Cannot remove pending image path after generation error.', { err, ...lTags() })
69 async function getImageSize (path: string) {
70 const inputBuffer = await readFile(path)
72 const image = await jimpRead(inputBuffer)
75 width: image.getWidth(),
76 height: image.getHeight()
80 // ---------------------------------------------------------------------------
83 generateImageFilename,
84 generateImageFromVideoFile,
91 // ---------------------------------------------------------------------------
93 async function jimpProcessor (path: string, destination: string, newSize: { width: number, height: number }, inputExt: string) {
95 const inputBuffer = await readFile(path)
98 sourceImage = await jimpRead(inputBuffer)
100 logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err })
102 const newName = path + '.jpg'
103 await convertWebPToJPG({ path, destination: newName })
104 await rename(newName, path)
106 sourceImage = await jimpRead(path)
109 await remove(destination)
111 // Optimization if the source file has the appropriate size
112 const outputExt = getLowercaseExtension(destination)
113 if (skipProcessing({ sourceImage, newSize, imageBytes: inputBuffer.byteLength, inputExt, outputExt })) {
114 return copy(path, destination)
117 await autoResize({ sourceImage, newSize, destination })
120 async function autoResize (options: {
122 newSize: { width: number, height: number }
125 const { sourceImage, newSize, destination } = options
127 // Portrait mode targeting a landscape, apply some effect on the image
128 const sourceIsPortrait = sourceImage.getWidth() < sourceImage.getHeight()
129 const destIsPortraitOrSquare = newSize.width <= newSize.height
131 removeExif(sourceImage)
133 if (sourceIsPortrait && !destIsPortraitOrSquare) {
134 const baseImage = sourceImage.cloneQuiet().cover(newSize.width, newSize.height)
135 .color([ { apply: ColorActionName.SHADE, params: [ 50 ] } ])
137 const topImage = sourceImage.cloneQuiet().contain(newSize.width, newSize.height)
139 return write(baseImage.blit(topImage, 0, 0), destination)
142 return write(sourceImage.cover(newSize.width, newSize.height), destination)
145 function write (image: Jimp, destination: string) {
146 return image.quality(80).writeAsync(destination)
149 function skipProcessing (options: {
151 newSize: { width: number, height: number }
156 const { sourceImage, newSize, imageBytes, inputExt, outputExt } = options
157 const { width, height } = newSize
159 if (hasExif(sourceImage)) return false
160 if (sourceImage.getWidth() > width || sourceImage.getHeight() > height) return false
161 if (inputExt !== outputExt) return false
165 if (height >= 1000) return imageBytes <= 200 * kB
166 if (height >= 500) return imageBytes <= 100 * kB
168 return imageBytes <= 15 * kB
171 function hasExif (image: Jimp) {
172 return !!(image.bitmap as any).exifBuffer
175 function removeExif (image: Jimp) {
176 (image.bitmap as any).exifBuffer = null