2023-09-10 11:14:04 +02:00
|
|
|
import sharp from "sharp";
|
|
|
|
import logit from "./logit";
|
2023-09-10 19:42:18 +02:00
|
|
|
import { getMainWindow } from "../main-window";
|
2023-09-13 16:07:45 +02:00
|
|
|
import { compression } from "./config-variables";
|
2023-09-10 11:14:04 +02:00
|
|
|
|
|
|
|
const convertAndScale = async (
|
|
|
|
originalImagePath: string,
|
|
|
|
upscaledImagePath: string,
|
|
|
|
processedImagePath: string,
|
|
|
|
scale: string,
|
|
|
|
saveImageAs: string,
|
|
|
|
onError: (error: any) => void
|
|
|
|
) => {
|
2023-09-10 19:42:18 +02:00
|
|
|
const mainWindow = getMainWindow();
|
|
|
|
|
2023-09-10 11:14:04 +02:00
|
|
|
const originalImage = await sharp(originalImagePath).metadata();
|
|
|
|
if (!mainWindow || !originalImage) {
|
|
|
|
throw new Error("Could not grab the original image!");
|
|
|
|
}
|
|
|
|
// Resize the image to the scale
|
2023-09-16 12:34:35 +02:00
|
|
|
const newImage = sharp(upscaledImagePath, {
|
|
|
|
limitInputPixels: false,
|
|
|
|
})
|
2023-09-10 11:14:04 +02:00
|
|
|
.resize(
|
|
|
|
originalImage.width && originalImage.width * parseInt(scale),
|
|
|
|
originalImage.height && originalImage.height * parseInt(scale)
|
|
|
|
)
|
|
|
|
.withMetadata(); // Keep metadata
|
2023-09-16 12:34:35 +02:00
|
|
|
// Convert compression percentage (0-100) to compressionLevel (0-9)
|
|
|
|
const compressionLevel = Math.round((compression / 100) * 9);
|
2023-09-10 11:14:04 +02:00
|
|
|
// Change the output according to the saveImageAs
|
|
|
|
if (saveImageAs === "png") {
|
2023-09-16 12:34:35 +02:00
|
|
|
newImage.png({ compressionLevel });
|
2023-09-10 11:14:04 +02:00
|
|
|
} else if (saveImageAs === "jpg") {
|
2023-09-16 12:34:35 +02:00
|
|
|
console.log("compression: ", compression);
|
|
|
|
newImage.jpeg({ quality: compression });
|
2023-09-10 11:14:04 +02:00
|
|
|
}
|
|
|
|
// Save the image
|
|
|
|
const buffer = await newImage.toBuffer();
|
2023-09-13 18:15:42 +02:00
|
|
|
try {
|
2023-09-16 12:34:35 +02:00
|
|
|
await sharp(buffer, {
|
|
|
|
limitInputPixels: false,
|
|
|
|
}).toFile(processedImagePath);
|
2023-09-13 18:15:42 +02:00
|
|
|
} catch (error) {
|
|
|
|
logit("❌ Error converting to: ", saveImageAs, error);
|
|
|
|
onError(error);
|
|
|
|
}
|
|
|
|
|
|
|
|
logit("✅ Done converting to: ", upscaledImagePath);
|
2023-09-10 11:14:04 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
export default convertAndScale;
|