1 import { copy, readFile, remove, rename } from 'fs-extra'
2 import Jimp, { read as jimpRead } from 'jimp'
3 import { join } from 'path'
4 import { getLowercaseExtension } from '@shared/core-utils'
5 import { buildUUID } from '@shared/extra-utils'
6 import { convertWebPToJPG, generateThumbnailFromVideo, processGIF } from './ffmpeg/ffmpeg-images'
7 import { logger, loggerTagsFactory } from './logger'
9 const lTags = loggerTagsFactory('image-utils')
11 function generateImageFilename (extension = '.jpg') {
12 return buildUUID() + extension
15 async function processImage (
18 newSize: { width: number, height: number },
21 const extension = getLowercaseExtension(path)
23 if (path === destination) {
24 throw new Error('Jimp/FFmpeg needs an input path different that the output path.')
27 logger.debug('Processing image %s to %s.', path, destination)
29 // Use FFmpeg to process GIF
30 if (extension === '.gif') {
31 await processGIF(path, destination, newSize)
33 await jimpProcessor(path, destination, newSize, extension)
36 if (keepOriginal !== true) await remove(path)
39 async function generateImageFromVideoFile (fromPath: string, folder: string, imageName: string, size: { width: number, height: number }) {
40 const pendingImageName = 'pending-' + imageName
41 const pendingImagePath = join(folder, pendingImageName)
44 await generateThumbnailFromVideo(fromPath, folder, imageName)
46 const destination = join(folder, imageName)
47 await processImage(pendingImagePath, destination, size)
49 logger.error('Cannot generate image from video %s.', fromPath, { err, ...lTags() })
52 await remove(pendingImagePath)
54 logger.debug('Cannot remove pending image path after generation error.', { err, ...lTags() })
59 async function getImageSize (path: string) {
60 const inputBuffer = await readFile(path)
62 const image = await jimpRead(inputBuffer)
65 width: image.getWidth(),
66 height: image.getHeight()
70 // ---------------------------------------------------------------------------
73 generateImageFilename,
74 generateImageFromVideoFile,
81 // ---------------------------------------------------------------------------
83 async function jimpProcessor (path: string, destination: string, newSize: { width: number, height: number }, inputExt: string) {
85 const inputBuffer = await readFile(path)
88 sourceImage = await jimpRead(inputBuffer)
90 logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err })
92 const newName = path + '.jpg'
93 await convertWebPToJPG(path, newName)
94 await rename(newName, path)
96 sourceImage = await jimpRead(path)
99 await remove(destination)
101 // Optimization if the source file has the appropriate size
102 const outputExt = getLowercaseExtension(destination)
103 if (skipProcessing({ sourceImage, newSize, imageBytes: inputBuffer.byteLength, inputExt, outputExt })) {
104 return copy(path, destination)
107 await autoResize({ sourceImage, newSize, destination })
110 async function autoResize (options: {
112 newSize: { width: number, height: number }
115 const { sourceImage, newSize, destination } = options
117 // Portrait mode targeting a landscape, apply some effect on the image
118 const sourceIsPortrait = sourceImage.getWidth() < sourceImage.getHeight()
119 const destIsPortraitOrSquare = newSize.width <= newSize.height
121 removeExif(sourceImage)
123 if (sourceIsPortrait && !destIsPortraitOrSquare) {
124 const baseImage = sourceImage.cloneQuiet().cover(newSize.width, newSize.height)
125 .color([ { apply: 'shade', params: [ 50 ] } ])
127 const topImage = sourceImage.cloneQuiet().contain(newSize.width, newSize.height)
129 return write(baseImage.blit(topImage, 0, 0), destination)
132 return write(sourceImage.cover(newSize.width, newSize.height), destination)
135 function write (image: Jimp, destination: string) {
136 return image.quality(80).writeAsync(destination)
139 function skipProcessing (options: {
141 newSize: { width: number, height: number }
146 const { sourceImage, newSize, imageBytes, inputExt, outputExt } = options
147 const { width, height } = newSize
149 if (hasExif(sourceImage)) return false
150 if (sourceImage.getWidth() > width || sourceImage.getHeight() > height) return false
151 if (inputExt !== outputExt) return false
155 if (height >= 1000) return imageBytes <= 200 * kB
156 if (height >= 500) return imageBytes <= 100 * kB
158 return imageBytes <= 15 * kB
161 function hasExif (image: Jimp) {
162 return !!(image.bitmap as any).exifBuffer
165 function removeExif (image: Jimp) {
166 (image.bitmap as any).exifBuffer = null