MagickNet PNG with Transparency to JPEG

2.2k Views Asked by At

I am using MagickNet for image manipulation in my ASP.NET C# project. My issue is that I am uploading a PNG image with transparency and when I convert it to JPEG, I get a black background with some white spots instead of a white background for the transparent part.

  Stream su = upload.FileContent;

MagickNet.Image testimage = new MagickNet.Image(su);

testimage.Filter = FilterType.LanczosFilter;
testimage.Compression = CompressionType.JPEGCompression;
testimage.QuantizeDither = false;  
testimage.BackgroundColor = new Color(System.Drawing.Color.White);

testimage.Resize( new System.Drawing.Size(Convert.ToInt32(testimage.Size.Width * 0.4), Convert.ToInt32(testimage.Size.Height * 0.4)));
testimage.Write(System.Web.HttpContext.Current.Server.MapPath(".") + "\\temp\\" + DateTime.Now.Hour +  "-"  +DateTime.Now.Minute + "-" + DateTime.Now.Second + ".jpg");
su.Close();
su.Dispose();

testimage.Dispose();
Magick.Term();

I played with it and always get the wrong result that I am after. Sometimes I get a transparent background but some parts of the image at the outer region have white dots. I also resize the image to be smaller than what it is. I think the re-sizing it causing the issue.

update: this is caused because of the resizing for some reason. Without resizing it works. Having said that, I need to resize, so I need it to work with it.

Thanks.

2

There are 2 best solutions below

1
On

Try to composite onto a white background image.

Image bg = new Image(testimage.Size, new ColorRGB(255, 255, 255));
testimage = bg.Composite(testimage, 0, 0);
0
On

First of all, it is better to create your MagickImage object with the desirable size the speed of reading the file/stream with the required size can in some situation 100 times faster. You may not have that error.

using(var testimage = new MagickImage(yourstream/yourFileAddress, width, height)
{
....
}

But if you convert the MagickImage to Bitmap and then save the bitmap as jpg you can see that the image has a white background

using (var testBitmap = testimage.ToBitmap())
{
     testBitmap.Save(@"d:\temp.jpg"); 
}

also using is much better that calling dispose member function. Because if your code throw exception before it reaches the dispose call your object will remain in the memory. But with using, if program jump out of the block the object will be disposed.