0

Iam using this piece of code to convert image to black and white using hscrollbar :

private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)
    {
        Bitmap BAndW = new Bitmap(image.Width, image.Height);
        for (int i = 0; i < image.Width; i++)
        {
            for (int j = 0; j < image.Height; j++)
            {
                Color C = image.GetPixel(i, j);
                int newVal = ((C.R + C.G + C.B) / 3);

               // newVal = HorizontalScroll.Value;
                newVal = newVal > e.NewValue ? 255 : 0;
                
                Color newC = Color.FromArgb(newVal, newVal, newVal);
                BAndW.SetPixel(i, j, newC);
            }
        }
        pictureBox1.Image = BAndW;
    }

the problem is the scrollbar took like 2s to change the color every time I scroll what should I do to decrease this time period ?

  • See: [Bitmap.LockBits()](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.bitmap.lockbits) – Jimi Mar 12 '21 at 21:14
  • Use `ColorMatrix` which is pretty fast: https://stackoverflow.com/a/2265990/1204153 – Andy Mar 12 '21 at 21:18
  • Locking the image bytes in memory, a B&W conversion + disposing of the old Bitmap and showing in a UI, should take [10-20]ms tops, with an Image size of 1000x1000. Also note that the Scrollbar raises the Scroll event twice. -- @Andy That's a Grayscale conversion with a (not so good) matrix ([this one](https://stackoverflow.com/a/59102380/7444103) is better), it doesn't use a threshold, so the Scrollbar is useless. The OP is not converting to Grayscale, they use a base form of B&W conversion, where all the Pixels beyond a threshold are set to Color.White, the others to Color.Black. – Jimi Mar 12 '21 at 21:58
  • Thanks it works now..... – MHD Firass Barakat Mar 19 '21 at 15:15

0 Answers0