Files
X-Financial/remove_bg_fast.ps1

46 lines
1.8 KiB
PowerShell
Raw Normal View History

$code = @"
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public class ImageProcessor {
public static void RemoveWhiteBg(string inputFile, string outputFile, int threshold) {
Bitmap bmp = new Bitmap(inputFile);
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
int bytes = Math.Abs(bmpData.Stride) * bmp.Height;
byte[] rgbValues = new byte[bytes];
Marshal.Copy(bmpData.Scan0, rgbValues, 0, bytes);
for (int i = 0; i < rgbValues.Length; i += 4) {
byte b = rgbValues[i];
byte g = rgbValues[i + 1];
byte r = rgbValues[i + 2];
byte a = rgbValues[i + 3];
float avg = (r + g + b) / 3f;
if (avg > threshold && r > threshold - 10 && g > threshold - 10 && b > threshold - 10) {
float factor = (avg - threshold) / (255f - threshold);
int alpha = (int)(255 * (1 - factor));
if (alpha < 0) alpha = 0;
if (alpha > 255) alpha = 255;
rgbValues[i] = 255;
rgbValues[i + 1] = 255;
rgbValues[i + 2] = 255;
rgbValues[i + 3] = (byte)alpha;
}
}
Marshal.Copy(rgbValues, 0, bmpData.Scan0, bytes);
bmp.UnlockBits(bmpData);
bmp.Save(outputFile, ImageFormat.Png);
bmp.Dispose();
}
}
"@
Add-Type -TypeDefinition $code -ReferencedAssemblies System.Drawing
[ImageProcessor]::RemoveWhiteBg("d:\Code\Project\X-Financial\web\src\assets\images\raw_documents.png", "d:\Code\Project\X-Financial\web\src\assets\images\hero-financial-decor.png", 235)
Write-Host "Done"