use progressive jpegs for previews

This commit is contained in:
2020-10-17 08:18:57 +00:00
committed by Stepan Usatiuk
parent 47a90febd1
commit 0c560404a5
2 changed files with 21 additions and 8 deletions

View File

@@ -29,7 +29,7 @@ import {
validateOrReject,
} from "class-validator";
import { config } from "~config";
import { getShotDate, resizeTo } from "~util";
import { fileCheck, getShotDate, resizeToJpeg } from "~util";
export interface IPhotoJSON {
id: number;
@@ -101,7 +101,7 @@ export class Photo extends BaseEntity {
private getThumbFileName(size: number): string {
return `${this.user.id.toString()}-${this.hash}-${this.size}-${size}.${
mime.extension(this.format) as string
mime.extension("image/jpeg") as string
}`;
}
@@ -142,14 +142,13 @@ export class Photo extends BaseEntity {
// Checks if file exists and updates the DB
public async fileExists(): Promise<boolean> {
try {
await fs.access(this.getPath(), fsConstants.F_OK);
if (await fileCheck(this.getPath())) {
if (!this.uploaded) {
this.uploaded = true;
await this.save();
}
return true;
} catch (e) {
} else {
if (this.uploaded) {
this.uploaded = false;
this.generatedThumbs = [];
@@ -174,7 +173,7 @@ export class Photo extends BaseEntity {
if (!(await this.fileExists())) {
return;
}
await resizeTo(this.getPath(), this.getThumbPath(size), size);
await resizeToJpeg(this.getPath(), this.getThumbPath(size), size);
this.generatedThumbs.push(size.toString());
await this.save();
}
@@ -184,7 +183,10 @@ export class Photo extends BaseEntity {
throw new Error("Wrong thumbnail size");
}
const path = this.getThumbPath(size);
if (!this.generatedThumbs.includes(size.toString())) {
if (
!this.generatedThumbs.includes(size.toString()) ||
!(await fileCheck(path))
) {
await this.generateThumbnail(size);
}
return path;

View File

@@ -3,6 +3,7 @@ import { fromFile } from "hasha";
import * as ExifReader from "exifreader";
import * as sharp from "sharp";
import * as fs from "fs/promises";
import { constants as fsConstants } from "fs";
export async function getHash(file: string): Promise<string> {
return await fromFile(file, {
@@ -34,7 +35,7 @@ export async function getShotDate(file: string): Promise<Date | null> {
return date;
}
export async function resizeTo(
export async function resizeToJpeg(
inPath: string,
outPath: string,
size: number,
@@ -56,9 +57,19 @@ export async function resizeTo(
await sharp(inPath)
.resize(newWidth, newHeight)
.withMetadata()
.jpeg({ progressive: true })
.toFile(outPath);
}
export async function fileCheck(file: string) {
try {
await fs.access(file, fsConstants.F_OK);
return true;
} catch (e) {
return false;
}
}
// eslint-disable-next-line @typescript-eslint/no-misused-promises
export const getHashSync: (file: string) => string = deasync(getHash);
// eslint-disable-next-line @typescript-eslint/no-misused-promises