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 (options: {
18 newSize: { width: number, height: number }
19 keepOriginal?: boolean // default false
21 const { path, destination, newSize, keepOriginal = false } = options
23 const extension = getLowercaseExtension(path)
25 if (path === destination) {
26 throw new Error('Jimp/FFmpeg needs an input path different that the output path.')
29 logger.debug('Processing image %s to %s.', path, destination)
31 // Use FFmpeg to process GIF
32 if (extension === '.gif') {
33 await processGIF(path, destination, newSize)
35 await jimpProcessor(path, destination, newSize, extension)
38 if (keepOriginal !== true) await remove(path)
41 async function generateImageFromVideoFile (options: {
45 size: { width: number, height: number }
47 const { fromPath, folder, imageName, size } = options
49 const pendingImageName = 'pending-' + imageName
50 const pendingImagePath = join(folder, pendingImageName)
53 await generateThumbnailFromVideo(fromPath, folder, imageName)
55 const destination = join(folder, imageName)
56 await processImage({ path: pendingImagePath, destination, newSize: size })
58 logger.error('Cannot generate image from video %s.', fromPath, { err, ...lTags() })
61 await remove(pendingImagePath)
63 logger.debug('Cannot remove pending image path after generation error.', { err, ...lTags() })
68 async function getImageSize (path: string) {
69 const inputBuffer = await readFile(path)
71 const image = await jimpRead(inputBuffer)
74 width: image.getWidth(),
75 height: image.getHeight()
79 // ---------------------------------------------------------------------------
82 generateImageFilename,
83 generateImageFromVideoFile,
90 // ---------------------------------------------------------------------------
92 async function jimpProcessor (path: string, destination: string, newSize: { width: number, height: number }, inputExt: string) {
94 const inputBuffer = await readFile(path)
97 sourceImage = await jimpRead(inputBuffer)
99 logger.debug('Cannot read %s with jimp. Try to convert the image using ffmpeg first.', path, { err })
101 const newName = path + '.jpg'
102 await convertWebPToJPG(path, newName)
103 await rename(newName, path)
105 sourceImage = await jimpRead(path)
108 await remove(destination)
110 // Optimization if the source file has the appropriate size
111 const outputExt = getLowercaseExtension(destination)
112 if (skipProcessing({ sourceImage, newSize, imageBytes: inputBuffer.byteLength, inputExt, outputExt })) {
113 return copy(path, destination)
116 await autoResize({ sourceImage, newSize, destination })
119 async function autoResize (options: {
121 newSize: { width: number, height: number }
124 const { sourceImage, newSize, destination } = options
126 // Portrait mode targeting a landscape, apply some effect on the image
127 const sourceIsPortrait = sourceImage.getWidth() < sourceImage.getHeight()
128 const destIsPortraitOrSquare = newSize.width <= newSize.height
130 removeExif(sourceImage)
132 if (sourceIsPortrait && !destIsPortraitOrSquare) {
133 const baseImage = sourceImage.cloneQuiet().cover(newSize.width, newSize.height)
134 .color([ { apply: 'shade', params: [ 50 ] } ])
136 const topImage = sourceImage.cloneQuiet().contain(newSize.width, newSize.height)
138 return write(baseImage.blit(topImage, 0, 0), destination)
141 return write(sourceImage.cover(newSize.width, newSize.height), destination)
144 function write (image: Jimp, destination: string) {
145 return image.quality(80).writeAsync(destination)
148 function skipProcessing (options: {
150 newSize: { width: number, height: number }
155 const { sourceImage, newSize, imageBytes, inputExt, outputExt } = options
156 const { width, height } = newSize
158 if (hasExif(sourceImage)) return false
159 if (sourceImage.getWidth() > width || sourceImage.getHeight() > height) return false
160 if (inputExt !== outputExt) return false
164 if (height >= 1000) return imageBytes <= 200 * kB
165 if (height >= 500) return imageBytes <= 100 * kB
167 return imageBytes <= 15 * kB
170 function hasExif (image: Jimp) {
171 return !!(image.bitmap as any).exifBuffer
174 function removeExif (image: Jimp) {
175 (image.bitmap as any).exifBuffer = null