📜 ⬆️ ⬇️

Quick System.Drawing.Bitmap

This topic prompted me to write an article about working with System.Drawing.Bitmap http://habrahabr.ru/blogs/net/60085/ . I often had to deal with pixel-by-pixel processing of images for typical operations, while in .NET there are classes ColorMatrix, ColorMap, ImageAttributes for some types of image transformations.

For example, for the 1024 x 768 image, the following code that performs the conversion to a gray image was executed in 0.1 second on my machine (Virtual Machine (under Hyper-V) 4 cores and 1GB of RAM), and for a 360 image size x 480 time was 0.03 seconds. (I strictly ask you not to judge the code that you quickly jotted down for this topic - on the form there are two PictureBox and one Button).
DateTime startTime = DateTime .Now;

ImageAttributes ia = new ImageAttributes();
ColorMatrix cm = new ColorMatrix();
cm.Matrix00 = cm.Matrix01 = cm.Matrix02 =
cm.Matrix10 = cm.Matrix11 = cm.Matrix12 =
cm.Matrix20 = cm.Matrix21 = cm.Matrix22 = 0.34f;

ia.SetColorMatrix(cm);

Bitmap bmp = new Bitmap (pictureBox1.Image);
Graphics g = Graphics .FromImage(bmp);

g.DrawImage(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, ia);

pictureBox2.Image = (Image)bmp;

button1.Text = ( DateTime .Now - startTime).TotalSeconds + " c." ;


* This source code was highlighted with Source Code Highlighter .


"Fading" can be obtained using the values:

cm.Matrix00 = cm.Matrix11 = cm.Matrix22 = 0;
cm.Matrix33 = 0.25f;


* This source code was highlighted with Source Code Highlighter .

')
If desired / necessary, you can specify all values ​​simultaneously using the class constructor:
ColorMatrix cm = new ColorMatrix( new float [][]
{
new float [] { 0, 0, 0, 0, 0},
new float [] { 0, 0, 0, 0, 0},
new float [] { 0, 0, 0, 0, 0},
new float [] { 0, 0, 0, 0.25f, 0},
new float [] { 0, 0, 0, 0, 0},
});


* This source code was highlighted with Source Code Highlighter .


They can also be used to create negative images, replace one color with another, and so on. operations.

Source: https://habr.com/ru/post/60175/


All Articles