I am trying to change the background color of a png image.
I've downloaded the first one I've found on the internet with a white background.
I am using some simple code (Console Application) just to transform the background color to transparent (or any other color, really):
string originalFile = @"C:\Users\myname\Desktop\fedex.png";
using (var currentImage = new ImageProcessor.ImageFactory())
{
currentImage
.Load(originalFile)
.BackgroundColor(Color.Transparent)
.Save($@"C:\Users\myname\Desktop\{Guid.NewGuid().ToString()}_1.png");
}
and nothing really happens here. I've tried to apply some other transformation like resize and everything works fine, except for the background.
If, instead, I use System.Drawing directly everything works as exptected:
string originalFile = @"C:\Users\myname\Desktop\fedex.png";
using (var originalImage = System.Drawing.Image.FromFile(originalFile))
{
var bmp = new Bitmap(originalImage);
bmp.MakeTransparent(Color.White);
bmp.Save($@"C:\Users\myname\Desktop\{Guid.NewGuid().ToString()}_2.png");
}
Now I can see the new generated image with a transparent background.
Hi @Leftyx
You're actually asking ImageProcessor to do the wrong thing.
BackgroundColor simply sets the background colour of the canvas the equivalent of
``` c#
graphics.Clear(Color.Transparent);
While in your second example you are telling System.Drawing to replace one colour with a transparent colour (It's not specific to the background).
What you are looking for is the `ReplaceColor` method.
So in your example, you would want
```c#
string originalFile = @"C:\Users\myname\Desktop\fedex.png";
using (var currentImage = new ImageProcessor.ImageFactory())
{
currentImage
.Load(originalFile)
.ReplaceColor(Color.White, Color.Transparent)
.Save($@"C:\Users\myname\Desktop\{Guid.NewGuid().ToString()}_1.png");
}
Hope that all makes sense
Cheers
James
Thanks. Great. It works like a charm.
Good to hear. :smile:
Took me hours until I found this issue...
I tried exactly your code with version 2.7.0.100, but it always produced an image with black background.
I added
.BackgroundColor(Color.Transparent);
but with no luck... downgraded to 2.5.6 again and everything worked.
Then it鈥檚 not the same issue