If you ever ask yourself how to convert images to characters or to binary. This tutorial will show you how to make this on the easiest way posible by arrays.
Creating the Form
- Open the visual studio, create a new form, windows application.
- Drag the follow items to the form: Two Buttons, One pictureBox, One TextBox and one OpenDialog.
- Make the TextBox Multiline on the properties page.
- Be sure that the PictureBox is an square because we're going to work with square arrays.
Your form should look like the one in the picture 1.
Inserting an Image to the Picture Box
To insert the image double click on one of the two buttons, this will lead you to the click event, and then try the next code:
- openFileDialog1.FileName = "";
- openFileDialog1.Title = "Images";
- openFileDialog1.Filter = "All Images|*.jpg; *.bmp; *.png";
-
- openFileDialog1.ShowDialog();
- if (openFileDialog1.FileName.ToString() != "")
- {
- Imagen.ImageLocation = openFileDialog1.FileName.ToString();
- direction.
- }
Voila the Picture Box will display the image you select.
Converting the image to binary
Ok this is how I normally works with arrays and images. First we should create a global variable:
This one let us work with the image withou modify the original. Then you should add some code after the,
- "Imagen.ImageLocation = openFileDialog1.FileName.ToString();"
- img = new Bitmap(openFileDialog1.FileName.ToString());
Then go back to the design form and double click on the second button, this will lead you to the event, and then place the next code:
-
- string texto = "";
-
- for (int i = 0; i < img.Height; i++) {
- for (int j = 0; j < img.Width; j++) {
-
- order because the images are reading from top to bottom
-
- if (img.GetPixel(j, i).A.ToString() == "255" && img.GetPixel(j, i).B.ToString() == "255" && img.GetPixel(j, i).G.ToString() == "255" && img.GetPixel(j, i).R.ToString() == "255") {
- texto = texto + "0";
- } else {
- texto = texto + "1";
- }
- }
- texto = texto + "\r\n";
- }
-
- txtArreglo.Text = texto;
As you can see in picture 2 the image will display only zeros and ones, if the pixel color is diferent than white.
If your image is big the delay of execution will be long because this code search pixel by pixel.