Created
June 18, 2024 15:29
-
-
Save AldeRoberge/46a2f2d512b3b7a23a7599c87e0b8155 to your computer and use it in GitHub Desktop.
Adds a (white) background to png images and export them to jpeg.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using SkiaSharp; | |
namespace AGXSpriteProcessor | |
{ | |
// Loads all images in a directory, adds a white background, and saves them to a new directory as .jpeg | |
public static class AddBackground | |
{ | |
private const string InputDirectory = @"C:\Users\Alde\Desktop\Wik"; | |
private const string OutputDirectory = @"C:\Users\Alde\Desktop\Wik\Output"; | |
public static void AddBackgroundToImages() | |
{ | |
var files = Directory.GetFiles(InputDirectory, "*.png"); | |
// Create output directory if it doesn't exist | |
if (!Directory.Exists(OutputDirectory)) | |
Directory.CreateDirectory(OutputDirectory); | |
// Use parallel for faster processing | |
Parallel.ForEach(files, file => | |
{ | |
using var inputStream = File.OpenRead(file); | |
using var bitmap = SKBitmap.Decode(inputStream); | |
// Create a new bitmap with a white background | |
var imageWithBackground = new SKBitmap(bitmap.Width, bitmap.Height); | |
using (var canvas = new SKCanvas(imageWithBackground)) | |
{ | |
canvas.Clear(SKColors.White); | |
canvas.DrawBitmap(bitmap, 0, 0); | |
} | |
// Save the new image as a .jpeg in the output directory | |
var outputFilePath = Path.Combine(OutputDirectory, $"{Path.GetFileNameWithoutExtension(file)}.jpeg"); | |
using (var outputStream = File.OpenWrite(outputFilePath)) | |
{ | |
Console.WriteLine($"Saving {outputFilePath}"); | |
imageWithBackground.Encode(outputStream, SKEncodedImageFormat.Jpeg, 100); | |
} | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment