Replacing Colour Of An Image

前端 未结 3 1356
猫巷女王i
猫巷女王i 2020-12-20 10:37

I am trying to replace the black colours of a picture with white, and vice versa. This is actually so my OCR code can read it on white backgrounds better. It\'s currently ge

3条回答
  •  别那么骄傲
    2020-12-20 11:11

    You can use the ColorMap and ImageAttributes classes from the System.Drawimg.Imaging namespace to directly replace the pixels in your image:

    Image img = Clipboard.GetImage();
    if (img != null) {
      ColorMap[] cm = new ColorMap[1];
      cm[0] = new ColorMap();
      cm[0].OldColor = Color.Black;
      cm[0].NewColor = Color.White;
      ImageAttributes ia = new ImageAttributes();
      ia.SetRemapTable(cm);
      using (Graphics g = Graphics.FromImage(img)) {
        g.DrawImage(img, new Rectangle(Point.Empty, img.Size), 0, 0, img.Width, img.Height,
                    GraphicsUnit.Pixel, ia);
      }
      pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
      pictureBox1.Image = img;
    }
    

提交回复
热议问题