LockBitmap revision, lockbitmap Revision

Source: Internet
Author: User
Tags html comment

LockBitmap revision, lockbitmap Revision

Currently, the LockBitmap class is found to be related to the color extraction of the image topic. However, it is found that there are some problems with the color extracted, it appears in the topic color. After being ruled out from many aspects, it is determined that it is a LockBitmap problem. articles related to this category have been forwarded many times, basically everywhere, but only a few people raised the problem (such as the https://www.cnblogs.com/xiashengwang/p/4225848.html comment inside), also did not give the relevant solution, so can only change their own

The revised version is as follows: (modified rows 50/95/137)

1 public class LockBitmap: IDisposable 2 {3 Bitmap source = null; 4 IntPtr Iptr = IntPtr. zero; 5 BitmapData bitmapData = null; 6 7 public byte [] Pixels {get; set;} 8 public int Depth {get; private set;} 9 public int Width {get; private set;} 10 public int Height {get; private set;} 11 12 public LockBitmap (Bitmap source) 13 {14 this. source = source; 15 LockBits (); 16} 17 18 // <summary> 19 // Lock bitmap data 20 /// </summary> 21 public void LockBits () 22 {23 try 24 {25 // Get width and height of bitmap 26 Width = source. width; 27 Height = source. height; 28 29 // get total locked pixels count 30 // int PixelCount = Width * Height; 31 32 // Create rectangle to lock 33 System. drawing. rectangle rect = new System. drawing. rectangle (0, 0, Width, Height); 34 35 // get source bitmap p Ixel format size 36 Depth = System. drawing. bitmap. getPixelFormatSize (source. pixelFormat); 37 38 // Check if bpp (Bits Per Pixel) is 8, 24, or 32 39 if (Depth! = 8 & Depth! = 24 & Depth! = 32) 40 {41 throw new ArgumentException ("Only 8, 24 and 32 bpp images are supported. "); 42} 43 44 // Lock bitmap and return bitmap data 45 bitmapData = source. lockBits (rect, ImageLockMode. readWrite, 46 source. pixelFormat); 47 48 // create byte array to copy pixel values 49 int step = Depth/8; 50 Pixels = new byte [bitmapData. stride * Height]; 51 Iptr = bitmapData. scan0; 52 53 // Copy data from Pointer to array 54 Marshal. copy (Iptr, Pixels, 0, Pixels. length); 55} 56 catch (Exception ex) 57 {58 throw ex; 59} 60} 61 62 // <summary> 63 // Unlock bitmap data 64 // </summary> 65 public void UnlockBits () 66 {67 try 68 {69 // Copy data from byte array to pointer 70 Marshal. copy (Pixels, 0, Iptr, Pixels. length); 71 72 // Unlock bitmap data 73 source. unlockBits (bitmapData); 74} 75 catch (Exception ex) 76 {77 throw ex; 78} 79} 80 81 // <summary> 82 // Get the color of the specified pixel 83 // </summary> 84 // <param name =" x "> </param> 85 // <param name =" y "> </param> 86 // <returns> </returns> 87 public Color GetPixel (int x, int y) 88 {89 Color clr = Color. empty; 90 91 // Get color components count 92 int cCount = Depth/8; 93 94 // Get start index of the specified pixel 9 5 // int I = (y * Width) + x) * cCount; 96 int I = y * bitmapData. stride + x * cCount; 97 98 if (I> Pixels. length-cCount) 99 throw new IndexOutOfRangeException (); 100 101 if (Depth = 32) // For 32 bpp get Red, Green, blue and Alpha102 {103 byte B = Pixels [I]; 104 byte g = Pixels [I + 1]; 105 byte r = Pixels [I + 2]; 106 byte a = Pixels [I + 3]; // a107 clr = Color. fromArgb (a, r, g, B); 108} 109 if (De Pth = 24) // For 24 bpp get Red, Green and Blue110 {111 byte B = Pixels [I]; 112 byte g = Pixels [I + 1]; 113 byte r = Pixels [I + 2]; 114 clr = Color. fromArgb (r, g, B); 115} 116 if (Depth = 8) 117 // For 8 bpp get color value (Red, Green and Blue values are the same) 118 {119 byte c = Pixels [I]; 120 clr = Color. fromArgb (c, c, c); 121} 122 return clr; 123} 124 125 // <summary> 126 // Set the color of the s Pecified pixel127 // </summary> 128 // <param name = "x"> </param> 129 // <param name = "y"> </param> 130 // <param name = "color"> </param> 131 public void SetPixel (int x, int y, Color color) 132 {133 // Get color components count134 int cCount = Depth/8; 135 136 // Get start index of the specified pixelied // int I = (y * Width) + x) * cCount; 138 int I = y * bitmapData. stride + x * cCount; 139 140 if (Dep Th = 32) // For 32 bpp set Red, Green, Blue and Alpha141 {142 Pixels [I] = color. b; 143 Pixels [I + 1] = color. g; 144 Pixels [I + 2] = color. r; 145 Pixels [I + 3] = color. a; 146} 147 if (Depth = 24) // For 24 bpp set Red, Green and Blue148 {149 Pixels [I] = color. b; 150 Pixels [I + 1] = color. g; 151 Pixels [I + 2] = color. r; 152} 153 if (Depth = 8) 154 // For 8 bpp set color value (Red, Green and Blue values Are the same) 155 {156 Pixels [I] = color. b; 157} 158} 159 160 public bool IsValidCoordinate (int x, int y) 161 {162 return x> = 0 & x <this. width & y> 0 & y <this. height; 163} 164 165 # region IDisposable Support166 private bool disposedValue = false; // to detect redundancy call 167 168 169 protected virtual void Dispose (bool disposing) 170 {if (! DisposedValue) 171 {172 if (disposing) 173 {174 // TODO: Release the managed object ). 175} 176 177 // TODO: Release unhosted resources (unmanaged objects) and replace the terminator in the following content. 178 // TODO: Set large fields to null. 179 UnlockBits (); 180 disposedValue = true; 181} 182} 183 184 // TODO: only when the above Dispose (bool disposing) the Terminator is replaced only when you have code to release unmanaged resources. 185 //~ LockBitmap () {186 // do not change this code. Put the cleanup code in the above Dispose (bool disposing. 187 // Dispose (false); 188 //} 189 190 // Add this code to implement the disposal mode correctly. 191 void IDisposable. Dispose () 192 {193 // do not change this code. Put the cleanup code in the above Dispose (bool disposing. 194 Dispose (true); 195 // TODO: If the Terminator is replaced by the above content, uncomment the following line. 196 // GC. SuppressFinalize (this); 197} 198 # endregion199}

Usage:

    using (var bitmap = new LockBitmap(img))    {        for (int i = 0; i < img.Width; i++)        {            for (int j = 0; j < img.Height; j++)            {                tempColor = bitmap.GetPixel(i, j);            }        }    }

The difference between Stride and Width references: http://blog.csdn.net/ustcxiangchun/article/details/25893883

Here's a problem: I used the one in the https://www.cnblogs.com/bomo/archive/2013/02/26/2934055.html.Pointer MethodThen, the MVC attribute "allow Insecure code" is also checked. However, Release of the Release version is unsuccessful. Only the Debug version can be released, if you know how to Release the Release version, I 'd like to comment on it. Thank you. Compiling environment: VS2015, ASP. net mvc 5, and. NET Framework 4.5.2. Method tried: web. config configuration "/unsafe +" = true is useless

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.