1
0
mirror of https://github.com/upscayl/upscayl.git synced 2025-02-17 19:19:23 +01:00
upscayl/electron/utils/convert-and-scale.ts

82 lines
2.1 KiB
TypeScript
Raw Normal View History

2023-10-14 13:48:43 +05:30
import fs from "fs";
2023-09-17 05:44:41 +05:30
import sharp, { FormatEnum } from "sharp";
2023-09-10 14:44:04 +05:30
import logit from "./logit";
2023-09-10 23:12:18 +05:30
import { getMainWindow } from "../main-window";
2023-09-13 19:37:45 +05:30
import { compression } from "./config-variables";
2023-09-10 14:44:04 +05:30
const convertAndScale = async (
originalImagePath: string,
upscaledImagePath: string,
processedImagePath: string,
scale: string,
saveImageAs: string,
onError: (error: any) => void
) => {
2023-09-10 23:12:18 +05:30
const mainWindow = getMainWindow();
2023-09-10 14:44:04 +05:30
const originalImage = await sharp(originalImagePath).metadata();
2023-09-17 05:29:18 +05:30
2023-10-14 13:48:43 +05:30
fs.access(originalImagePath, fs.constants.F_OK, (err) => {
if (err) {
throw new Error("Could not grab the original image!");
}
});
2023-09-10 14:44:04 +05:30
if (!mainWindow || !originalImage) {
throw new Error("Could not grab the original image!");
}
2023-09-19 00:00:43 +05:30
2023-09-10 14:44:04 +05:30
// Resize the image to the scale
const newImage = sharp(upscaledImagePath, {
limitInputPixels: false,
2023-09-17 05:29:18 +05:30
}).resize(
originalImage.width && originalImage.width * parseInt(scale),
2023-09-19 00:00:43 +05:30
originalImage.height && originalImage.height * parseInt(scale),
{
fit: "outside",
}
2023-09-17 05:29:18 +05:30
);
2023-09-16 16:13:14 +05:30
// Convert compression percentage (0-100) to compressionLevel (0-9)
const compressionLevel = Math.round((compression / 100) * 9);
2023-09-19 00:00:43 +05:30
logit("📐 Processing Image: ", {
originalWidth: originalImage.width,
originalHeight: originalImage.height,
scale,
saveImageAs,
compressionPercentage: compression,
compressionLevel,
});
2023-09-17 05:29:18 +05:30
2023-09-10 14:44:04 +05:30
const buffer = await newImage.toBuffer();
2023-09-13 21:45:42 +05:30
try {
2023-09-19 00:00:43 +05:30
logit("");
await sharp(buffer, {
limitInputPixels: false,
2023-09-17 05:29:18 +05:30
})
2023-09-17 05:44:41 +05:30
.toFormat(saveImageAs as keyof FormatEnum, {
2023-09-17 17:07:57 +05:30
...(saveImageAs === "jpg" && {
quality: 100 - (compression === 100 ? 99 : compression),
chromaSubsampling: "4:4:4",
}),
...(saveImageAs === "png" && {
compressionLevel,
}),
force: true,
2023-09-17 05:44:41 +05:30
})
2023-09-17 05:29:18 +05:30
.withMetadata({
orientation: originalImage.orientation,
density: originalImage.density,
})
.toFile(processedImagePath);
2023-09-13 21:45:42 +05:30
} catch (error) {
logit("❌ Error converting to: ", saveImageAs, error);
onError(error);
}
logit("✅ Done converting to: ", upscaledImagePath);
2023-09-10 14:44:04 +05:30
};
export default convertAndScale;