Skip to content

Instantly share code, notes, and snippets.

@javiercampos
Created January 5, 2025 22:18
Show Gist options
  • Select an option

  • Save javiercampos/a526d5c00bada29e20047a138ed63f27 to your computer and use it in GitHub Desktop.

Select an option

Save javiercampos/a526d5c00bada29e20047a138ed63f27 to your computer and use it in GitHub Desktop.
InstagramBatchResize Project
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="SixLabors.Imagesharp" Version="3.1.6" />
</ItemGroup>
</Project>
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
if(args.Length < 2) {
Console.WriteLine("Parameters: <input directory> <output directory>");
Console.WriteLine("Note: output directory will be created if not existing");
return 1;
}
var inputFolder = args[0];
var outputFolder = args[1];
if(!Directory.Exists(inputFolder)) {
Console.WriteLine("Input directory doesn't exist");
return 2;
}
Directory.CreateDirectory(outputFolder);
foreach (var inputFile in Directory.GetFiles(inputFolder, "*.jpg", SearchOption.AllDirectories))
{
var outputFile = Path.Combine(outputFolder, Path.GetRelativePath(inputFolder, inputFile));
var dirName = Path.GetDirectoryName(outputFile);
if (dirName is null)
{
Console.WriteLine($"Invalid folder for {outputFile}");
return 1;
}
Directory.CreateDirectory(dirName);
if (File.Exists(outputFile))
{
continue;
}
using var image = Image.Load<Rgba32>(inputFile);
int targetWidth, targetHeight;
if (image.Width > image.Height)
{
// Landscape
targetWidth = 1080;
targetHeight = 566;
}
else
{
// Portrait
targetWidth = 1080;
targetHeight = 1350;
}
Console.WriteLine($"{outputFile} {image.Width}x{image.Height} -> {targetWidth}x{targetHeight}");
image.Mutate(x => x.Resize(new ResizeOptions
{
Size = new Size(targetWidth, targetHeight),
PadColor = Color.Black,
Mode = ResizeMode.Pad,
Sampler = KnownResamplers.Lanczos3
}));
var encoder = new JpegEncoder { Quality = 90 };
image.Save(outputFile, encoder);
}
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment