Skip to content

Archive

Tag: C#

To increase the brightness of an image, all you need to do is add a value to each component for each pixel in the image.

Increasing the brightness is not always reversible, because as the colour value tops out at 255, if the increased value goes above this value, it will be limited to that value. This makes any reversal of the process impossible. The opposite is true for negative values. Then if the value falls below 0, then the values are limited.

Increasing the brightness by 100

Increasing the brightness by 100

You can download the full code for the sample application which contains code for all the image effects covered in the series here.


        public void ApplyBrightness(int brightness)
        {
            int A, R, G, B;
            Color pixelColor;

            for (int y = 0; y < bitmapImage.Height; y++)
            {
                for (int x = 0; x < bitmapImage.Width; x++)
                {
                    pixelColor = bitmapImage.GetPixel(x, y);
                    A = pixelColor.A;
                    R =  pixelColor.R + brightness;
                    if (R > 255)
                    {
                        R = 255;
                    }
                    else if (R < 0)
                    {
                        R = 0;
                    }

                    G = pixelColor.G + brightness;
                    if (G > 255)
                    {
                        G = 255;
                    }
                    else if (G < 0)
                    {
                        G = 0;
                    }

                    B = pixelColor.B + brightness;
                    if (B > 255)
                    {
                        B = 255;
                    }
                    else if (B < 0)
                    {
                        B = 0;
                    }

                    bitmapImage.SetPixel(x, y, Color.FromArgb(A, R, G, B));
                }
            }

        }
Share

Contrast in a picture is a measure of how close the range of colours in a picture are. The closer the colours are together, the lower the contrast.

The value for the contrast ranges from -100 to 100, with positive numbers increasing the contrast, and negative numbers decreasing the contrast.

Now, we calculate the contrast value which we will use in the calculation with
((100 + contrast) / 100)2

Then, for each pixel in the image, we take each component of the pixel, and divide the value by 255 to get a value between 0 and 1. We then subtract 0.5, and
any values which are negative will have their contrast decreased, while any positive values will have their contrast increased.

Then we add back the 0.5, and convert the value back to a range of 0-255. After that we set the pixel colour again.

Increasing the contrast by 50

Increasing the contrast by 50


You can download the full code for the sample application which contains code for all the image effects covered in the series here.

public void ApplyContrast(double contrast)
{
    double A, R, G, B;

    Color pixelColor;

    contrast = (100.0 + contrast) / 100.0;
    contrast *= contrast;

    for (int y = 0; y < bitmapImage.Height; y++)
    {
        for (int x = 0; x < bitmapImage.Width; x++)
        {
            pixelColor = bitmapImage.GetPixel(x, y);
            A = pixelColor.A;

            R = pixelColor.R / 255.0;
            R -= 0.5;
            R *= contrast;
            R += 0.5;
            R *= 255;

            if (R > 255)
            {
                R = 255;
            }
            else if (R < 0)
            {
                R = 0;
            }

            G = pixelColor.G / 255.0;
            G -= 0.5;
            G *= contrast;
            G += 0.5;
            G *= 255;
            if (G > 255)
            {
                G = 255;
            }
            else if (G < 0)
            {
                G = 0;
            }

            B = pixelColor.B / 255.0;
            B -= 0.5;
            B *= contrast;
            B += 0.5;
            B *= 255;
            if (B > 255)
            {
                B = 255;
            }
            else if (B < 0)
            {
                B = 0;
            }

            bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
        }
    }

}
Share

Converting an image to greyscale is a relatively easy effect to apply to an image.

For each pixel in the image, we take the three colour components (red, green and blue), and then combine the values.

Most people would think that you just take the average of the three colours, but the problem with that is the human eye has different sensitivities to different frequencies, so what we need to do is add in the colours at different ratios.

So, to make the colour ratios correct, we multiply the red, green and blue components by 0.299, 0.587 and 0.114 respectively.

We then assign the value to all the components of the pixel.

You can download the full code for the sample application which contains code for all the image effects covered in the series here.

public void ApplyGreyscale()
{
    byte A, R, G, B;
    Color pixelColor;

    for (int y = 0; y < bitmapImage.Height; y++)
    {
        for (int x = 0; x < bitmapImage.Width; x++)
        {
            pixelColor = bitmapImage.GetPixel(x, y);
            A = pixelColor.A;
            R =  (byte)((0.299 * pixelColor.R) + (0.587 * pixelColor.G) + (0.114 * pixelColor.B));
            G = B = R;

            bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
        }
    }

}
Share

This is the first part of my series on image processing, and to start off with, I will cover a relatively easy topic – how to invert the colours of an image.

You can download the full code for the sample application which contains code for all the image effects covered in the series here.

Actually inverting the colours of an image – in essence, creating a negative of the image, is remarkably easy. All it entails is getting the colour of each pixel, which is broken down into red, green and blue and then subtracting each component from 255.

The Bitmap object we are using in C# uses colour components in the range of 0-255, hence why we subtract the value from 255.

There is also an Alpha component to a colour, but we ignore that and just reuse the original value.

Once we have adjusted the colour components, we set the pixel to the new colour.

Inverting an image

Inverting an image


The code below does not include the instantiation of the bitmapData variable, since the function below forms part of a larger class (available in the full download). It is a standard Bitmap object.

public void ApplyInvert()
{
    byte A, R, G, B;
    Color pixelColor;

    for (int y = 0; y < bitmapImage.Height; y++)
    {
        for (int x = 0; x < bitmapImage.Width; x++)
        {
            pixelColor = bitmapImage.GetPixel(x, y);
            A = pixelColor.A;
            R = (byte)(255 - pixelColor.R);
            G = (byte)(255 - pixelColor.G);
            B = (byte)(255 - pixelColor.B);
            bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B));
        }
    }

}
Share

Another type of sharpening effect is mean removal. It works similarly to the standard sharpening, except it subtracts values from all the surrounding pixels evenly.

The grid which we used for this effect is as follows

-1 -1 -1
-1 11 -1
-1 -1 -1

This gives a much more noticeable sharpening effect on the image.

Mean removal

Mean removal


You can download the full code for the sample application which contains code for all the image effects covered in the series here.

public void ApplyMeanRemoval(double weight)
{
    ConvolutionMatrix matrix = new ConvolutionMatrix(3);
    matrix.SetAll(1);
    matrix.Matrix[0, 0] = -1;
    matrix.Matrix[1, 0] = -1;
    matrix.Matrix[2, 0] = -1;
    matrix.Matrix[0, 1] = -1;
    matrix.Matrix[1, 1] = weight;
    matrix.Matrix[2, 1] = -1;
    matrix.Matrix[0, 2] = -1;
    matrix.Matrix[1, 2] = -1;
    matrix.Matrix[2, 2] = -1;
    matrix.Factor = weight - 8;
    bitmapImage = Convolution3x3(bitmapImage, matrix);

}
Share

You would have thought that .NET, with its vast libraries would have a decent way to handle Zip compression, but this is sadly not so.

Now C# does allow compression usig GZipStream, which can be used as follows to compress a file

        public void zipFile(FileInfo file)
        {
            FileStream sourceFile = File.OpenRead(file.FullName);
            FileStream destFile = File.Create(file.FullName + ".zip");

            GZipStream stream = new GZipStream(destFile, CompressionMode.Compress);

            try
            {
                int data = sourceFile.ReadByte();
                while (data != -1)
                {
                    stream.WriteByte((byte)data);
                    data = sourceFile.ReadByte();
                }
            }
            finally
            {
                stream.Dispose();
                sourceFile.Close();
                sourceFile.Dispose();
            }
        }

This produces a compressed file, but it is not exactly compatible with Zip archives, and Windows has quite a bit of a problem opening up this king of archive, so it is not always very useful.

The same thing can be done, using a conventional Zip archive, using the SharpZipLib library, which provides a much richer compression library than what Visual Studio natively provides.

        using System.IO;
        using ICSharpCode.SharpZipLib.Zip;

        public void zipFile(FileInfo file)
        {
            FileStream stream;
            byte[] buffer;
            ZipOutputStream zipStream = new ZipOutputStream(File.Create(file.FullName + ".zip"));
            zipStream.SetLevel(9);
            ZipEntry zipEntry = new ZipEntry(file.Name);
            zipStream.PutNextEntry(zipEntry);

            stream = File.OpenRead(file.FullName);
            buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            zipStream.Write(buffer, 0, buffer.Length);

            zipStream.Finish();
            zipStream.Close();
            stream.Close();
        }

How this works is that we create a zip stream which we are going to write the data to. Each file we want to write to the zip file is added to the zip stream by means of a zip entry.

We add the zip entry to the zip stream, and then read the data from the original file, and then write it into the zip stream. Everything else is taken care of behind the scenes when we call the Finish() method of the zip stream.
Unzipping a file is a little more work. but quite straightforward.

        public static void UnZipFiles(string zipFile, string folder)
        {
            ZipInputStream zipStream = new ZipInputStream(File.OpenRead(zipPathAndFile));
            ZipEntry zipEntry;

            while ((zipEntry = zipStream.GetNextEntry()) != null)
            {
                string directory = outputFolder;
                string filename = Path.GetFileName(zipEntry.Name);
                Directory.CreateDirectory(folder);
                if (filename != String.Empty)
                {
                    string fullPath = folder + "/" + zipEntry.Name;
                    string fullDir = Path.GetDirectoryName(fullPath);
                    if (!Directory.Exists(fullDir))
                    {
                        Directory.CreateDirectory(fullDir);
                    }
                    FileStream streamWriter = File.Create(fullPath);
                    int size = 2048;
                    byte[] data = new byte[2048];
                    while (true)
                    {
                        size = zipStream.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            streamWriter.Write(data, 0, size);
                        }
                        else
                        {
                            break;
                        }
                    }
                    streamWriter.Close();
                }
            }
            zipStream.Close();
        }

Unzipping a zip file is simply the reverse of the zipping operation.

Share

C# does not have native capabilities to use SFTP, but fortunately there are libraries available to do this. Most of these libraries are commercial libraries, but there are two that are open-source and free to use.

These are SharpSSh by a guy called Tamir Gal, and Granados.

SharpSSH is a relatively easy library to use, and allows either a straight SSH connection, or provides a wrapper to transfer files.

The code to send a file to a remote server is rather easy using this library.

Sftp scp = new Sftp(HostName, SSHUsername);
scp.Password = SSHPassword;

scp.Connect(SSHPort);
scp.Put(fullFileName, remoteName);
scp.Close();

Don’t forget to include the reference to the library

using Tamir.SharpSsh;

The library does provide a lot more functionality that you can play around with, for example, you can check if the connection is connected or not, and check what cipher you are using. You can also use this object to create folders on the remote server, and download files from the server too.

Share