Issue with composited png

Dec 25, 2014 at 2:26 PM
The following snippet generates the desired image but yields a larger than expected png that cannot be optimized by pngout.exe - "unsupported format".
using (MagickImage background = new MagickImage(new MagickColor("yellow"), 500, 400))
{
    MagickImage foregroundImage = new MagickImage(@"C:\Temp\source.png");
    foregroundImage.Resize(400, 300);
    background.Composite(foregroundImage, 0, 0, CompositeOperator.Src);

    background.Write(@"C:\temp\test1.png");
}
A workaround I discovered was to save the resized image to disk before compositing. The result is an image ~30% the size of the image from the snippet above and it can be optimized by pngout.exe.
using (MagickImage background = new MagickImage(new MagickColor("yellow"), 500, 400))
{
    MagickImage foregroundImage = new MagickImage(@"C:\temp\source.png");
    foregroundImage.Resize(400, 300);
                
    //  save resized image to temp file
    var tempPath = Path.GetTempFileName();
    foregroundImage.Write(tempPath);

    background.Composite(new MagickImage(tempPath), 0, 0, CompositeOperator.Src);

    background.Write(@"C:\temp\test2.png");
}
Hoping someone can explain what I'm doing wrong. Thanks!
Coordinator
Dec 25, 2014 at 3:49 PM
The png writer might set some options when you write it earlier. Not sure why it does not set them after the composite operation. Can you provide me with a sample image so I can reproduce the problem? Feel free to contact through Codeplex if you don't want to share it publicly.
Dec 25, 2014 at 7:45 PM
I have shared the original image as well as the resulting image from the two snippets pasted above. Thanks for looking into this!

https://www.dropbox.com/sh/eiuqticy4bebymq/AADNfbAyEPwvOOp1BINiiqpqa?dl=0
Coordinator
Dec 25, 2014 at 8:38 PM
It seems that the Composite method changes the Depth of your image to 16 bit instead of the 8 bit of the original. Pngout.exe might not support 16-bit images. You can force a bit depth of 8 with the Depth property. You could also decide to force the writer to use the PNG24 format, this will get rid of the alpha channel but you might not notice the difference.
using (MagickImage background = new MagickImage(new MagickColor("yellow"), 500, 400))
{
  MagickImage foregroundImage = new MagickImage(@"C:\christmas.png");
  foregroundImage.Resize(400, 300);
  background.Composite(foregroundImage, 0, 0, CompositeOperator.Src);

  if (NoNeedAlpha)
    background.Write(@"PNG24:C:\christmas-45kb.png");
  else
  {
    background.Depth = 8;
    background.Write(@":C:\christmas-50kb.png");
  }
}
Dec 26, 2014 at 5:10 AM
Thanks a lot for the help dlemstra! Great library and super helpful.