Imageprocessor: Issue changing BackgroundColor of a png

Created on 17 Oct 2017  路  5Comments  路  Source: JimBobSquarePants/ImageProcessor

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.

  • ImageProcessor version: 2.5.6
  • ImageProcessor.Web version: -
  • Other ImageProcessor packages and versions: -
  • Environment (Operating system, version and so on): Windows 10 Pro ver. 1703
  • .NET Framework version: 4.6.1
  • Additional information: Console Application
question

All 5 comments

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

Was this page helpful?
0 / 5 - 0 ratings