CC#
Created by Kiel on 8/4/2024 in #help
✅ How to bulk compress a directory of images until each individual image is under a set size?
using System;
using System.Collections.Generic;
using System.IO;
using ImageMagick;

public class BatchImageCompressor
{
public static void CompressImages(string sourceDirectory, string targetDirectory, long maxSizeInBytes)
{
// Make sure the target directory exists
if (!Directory.Exists(targetDirectory))
Directory.CreateDirectory(targetDirectory);

// Get all image files in the source directory
string[] files = Directory.GetFiles(sourceDirectory, "*.*", SearchOption.AllDirectories);

// Compress Pictures
foreach (string file in files)
{
using (MagickImage image = new MagickImage(file))
{
// Try different compression levels until the file size meets your requirements.
while (image.GetBaseSize() > maxSizeInBytes && image.Quality > 1)
{
image.Quality--;
}

// Save the compressed image
string outputFile = Path.Combine(targetDirectory, Path.GetFileName(file));
image.Write(outputFile);
}
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using ImageMagick;

public class BatchImageCompressor
{
public static void CompressImages(string sourceDirectory, string targetDirectory, long maxSizeInBytes)
{
// Make sure the target directory exists
if (!Directory.Exists(targetDirectory))
Directory.CreateDirectory(targetDirectory);

// Get all image files in the source directory
string[] files = Directory.GetFiles(sourceDirectory, "*.*", SearchOption.AllDirectories);

// Compress Pictures
foreach (string file in files)
{
using (MagickImage image = new MagickImage(file))
{
// Try different compression levels until the file size meets your requirements.
while (image.GetBaseSize() > maxSizeInBytes && image.Quality > 1)
{
image.Quality--;
}

// Save the compressed image
string outputFile = Path.Combine(targetDirectory, Path.GetFileName(file));
image.Write(outputFile);
}
}
}
}
In this code, the CompressImages method accepts the source directory, the destination directory, and the maximum file size (in bytes) as parameters. It iterates through all the files in the source directory, and for each image file, loads the image using a MagickImage object, then enters a loop that continuously reduces the image quality until its size does not exceed the preset maximum. Finally, the compressed image is saved to the destination directory. I don't know if this can help you.
3 replies