Search code examples
c#imagebrightness

Changing image brightness for transparent images


I've been using this code that I found from here to change the brightness of images

public Bitmap SetBrightness(Bitmap bmap, int brightness)
    {
        if (brightness < -255) brightness = -255;
        if (brightness > 255) brightness = 255;
        Color c;
        for (int i = 0; i < bmap.Width; i++)
        {
            for (int j = 0; j < bmap.Height; j++)
            {
                c = bmap.GetPixel(i, j);
                int cR = c.R + brightness;
                int cG = c.G + brightness;
                int cB = c.B + brightness;

                if (cR < 0) cR = 1;
                if (cR > 255) cR = 255;

                if (cG < 0) cG = 1;
                if (cG > 255) cG = 255;

                if (cB < 0) cB = 1;
                if (cB > 255) cB = 255;

                bmap.SetPixel(i, j, Color.FromArgb((byte)cR, (byte)cG, (byte)cB));
            }
        }
        return bmap;
    }

It works just fine for non-transparent images, but when try to apply it to a transparent image, it will also fill up the transparent parts. For example, here is my original image with transparency before and here it is after. I only want to darken the non-transparent part of the image, not the transparent background.


Solution

  • When you call Color.FromArgb your not supplying the alpha channel try this and see if it works better:

    public Bitmap SetBrightness(Bitmap bmap, int brightness)
    {
        if (brightness < -255) brightness = -255;
        if (brightness > 255) brightness = 255;
        Color c;
        for (int i = 0; i < bmap.Width; i++)
        {
            for (int j = 0; j < bmap.Height; j++)
            {
                c = bmap.GetPixel(i, j);
                int cR = c.R + brightness;
                int cG = c.G + brightness;
                int cB = c.B + brightness;
    
                if (cR < 0) cR = 1;
                if (cR > 255) cR = 255;
    
                if (cG < 0) cG = 1;
                if (cG > 255) cG = 255;
    
                if (cB < 0) cB = 1;
                if (cB > 255) cB = 255;
    
                bmap.SetPixel(i, j, Color.FromArgb(c.A, (byte)cR, (byte)cG, (byte)cB));
            }
        }
        return bmap;
    }