7

I am trying to resize image using Magick.Net. But the image I compressed has greater size and bitdepth of 32 where as original image has bitdepth of 2.I want to retain or reduce the bitdepth too. Here is my code.

           var imageMacig = new MagickImage(filePath);
            //Percentage p = new Percentage(60);
            //imageMacig.Threshold(p); // 60 is OK 
            imageMacig.VirtualPixelMethod = VirtualPixelMethod.Transparent;
            imageMacig.Depth = 1;
            imageMacig.FilterType = FilterType.Quadratic;
            imageMacig.Transparent(MagickColor.FromRgb(0,0,0));
            imageMacig.Format = MagickFormat.Png00;
            imageMacig.Resize(newWidth, newHeight);
            imageMacig.Write(targetPath);
            imageMacig.Dispose();
            originalBMP.Dispose();
Manij Rai
  • 189
  • 1
  • 2
  • 8
  • Why you first create some "image", then from it you create "originalBMP" and from that in turn you create MagickImage? Why not create MagickImage from file directly? – Evk Nov 26 '16 at 15:23
  • I had tried for other method before using MagickImage. I used System.Drawing.Imaging first to resize then used MagickImage. – Manij Rai Nov 26 '16 at 15:30
  • So first try to remove your "image" and "originalBMP" (and everything related to them) completely and construct MagickImage from file. – Evk Nov 26 '16 at 15:32
  • I did as you told but some imagees are 1 bit and some are 32. Also could you tell me how to keep the image transparent. I seems images are not transparent too. – Manij Rai Nov 26 '16 at 15:52
  • 1
    Would be good if you update your question with code after removal of unnecessary thing. Even better if you attach\add a link to some sample image you have problem with. – Evk Nov 26 '16 at 16:18
  • i have updated code – Manij Rai Nov 26 '16 at 16:37

1 Answers1

6

You are getting more than two colors because you are resizing the image. This will add an alpha channel and that will result in a lot of semi-transparent pixels. If you want to go back to 2 colors you should change the ColorType of the image to BiLevel. And setting the format to MagickFormat.Png8 will make sure that your image will be written as a 2-bit png. Below is an example of how you could do that:

using (var imageMagick = new MagickImage(filePath))
{
  imageMagick.Transparent(MagickColor.FromRgb(0,0,0));
  imageMagick.FilterType = FilterType.Quadratic;
  imageMagick.Resize(newWidth, newHeight);
  imageMagick.ColorType = ColorType.Bilevel;
  imageMagick.Format = MagickFormat.Png8;
  imageMagick.Write(targetPath);
}
dlemstra
  • 7,813
  • 2
  • 27
  • 43
  • Thanks for the reply but the output I got was black and white image while my original image had a color. – Manij Rai Dec 10 '16 at 06:25