public static int LoadTexture(string filename) { var bitmap = new Bitmap (filename); int id = GL.GenTexture (); BitmapData bmpData = bitmap.LockBits ( new Rectangle (0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.BindTexture (TextureTarget.Texture2D, id); GL.TexImage2D (TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bitmap.Width, bitmap.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0); bitmap.UnlockBits (bmpData); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); return id; }
public void AddFrame(Bitmap bmp) { bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); BitmapData bmpDat = bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); if (countFrames == 0) { this.stride = (UInt32)bmpDat.Stride; this.width = bmp.Width; this.height = bmp.Height; CreateStream(); } int result = AviReadingMethods.AVIStreamWrite(aviStream, countFrames, 1, bmpDat.Scan0, (Int32)(stride * height), 0, 0, 0); if (result != 0) { throw new Exception("Problem podczas otwierania pliku AVI" + result.ToString()); } bmp.UnlockBits(bmpDat); countFrames++; }
public static void CalcDifference(Bitmap bmp1, Bitmap bmp2) { PixelFormat pxf = PixelFormat.Format32bppArgb; Rectangle rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height); BitmapData bmpData1 = bmp1.LockBits(rect, ImageLockMode.ReadWrite, pxf); IntPtr ptr1 = bmpData1.Scan0; BitmapData bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, pxf); IntPtr ptr2 = bmpData2.Scan0; int numBytes = bmp1.Width * bmp1.Height * bytesPerPixel; byte[] pixels1 = new byte[numBytes]; byte[] pixels2 = new byte[numBytes]; System.Runtime.InteropServices.Marshal.Copy(ptr1, pixels1, 0, numBytes); System.Runtime.InteropServices.Marshal.Copy(ptr2, pixels2, 0, numBytes); for (int i = 0; i < numBytes; i += bytesPerPixel) { if (pixels1[i + 0] == pixels2[i + 0] && pixels1[i + 1] == pixels2[i + 1] && pixels1[i + 2] == pixels2[i + 2]) { pixels1[i + 0] = 255; pixels1[i + 1] = 255; pixels1[i + 2] = 255; pixels1[i + 3] = 0; } } System.Runtime.InteropServices.Marshal.Copy(pixels1, 0, ptr1, numBytes); bmp1.UnlockBits(bmpData1); bmp2.UnlockBits(bmpData2); }
private static PNM DrawLines(PNM image, IEnumerable<Tuple<Point, Point>> lines) { // prepare the bitmap using (Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb)) { BitmapData data = bitmap.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); byte[] stridedBuffer = Stride(image.raster, image.Width, image.Height); Marshal.Copy(stridedBuffer, 0, data.Scan0, stridedBuffer.Length); bitmap.UnlockBits(data); using (Graphics graphics = Graphics.FromImage(bitmap)) { // draw the lines foreach(var tuple in lines) { graphics.DrawLine(Pens.Blue, tuple.Item1, tuple.Item2); } } // get raw data PNM lineImage = new PNM(image.Width, image.Height); data = bitmap.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); lineImage.raster = UnStride(data.Scan0, image.Width, image.Height); bitmap.UnlockBits(data); return lineImage; } }
public Bitmap ToBitmap(Int32 index, Bitmap bitmap) { BitmapData bdata; Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); switch (format) { case PixelFormat.PIXEL_FORMAT_RGB32: bdata = bitmap.LockBits(rect, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); PXCMImage_ImageData_Copy(planes[index], pitches[index], bdata.Scan0, bdata.Stride, (Int32)bitmap.Width * 4, (Int32)bitmap.Height); bitmap.UnlockBits(bdata); break; case PixelFormat.PIXEL_FORMAT_RGB24: bdata = bitmap.LockBits(rect, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); PXCMImage_ImageData_Copy(planes[index], pitches[index], bdata.Scan0, bdata.Stride, (Int32)bitmap.Width * 3, (Int32)bitmap.Height); bitmap.UnlockBits(bdata); break; case PixelFormat.PIXEL_FORMAT_DEPTH: case PixelFormat.PIXEL_FORMAT_DEPTH_RAW: bdata = bitmap.LockBits(rect, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale); PXCMImage_ImageData_Copy(planes[index], pitches[index], bdata.Scan0, bdata.Stride, (Int32)bitmap.Width * 2, (Int32)bitmap.Height); bitmap.UnlockBits(bdata); break; default: return null; } return bitmap; }
/// <summary> /// Create a texture of the given text in the given font. /// </summary> /// <param name="text">Text to display.</param> /// <param name="font">Font to display the text as.</param> /// <param name="size">Provides the size of the texture.</param> /// <returns>Int32 Handle to the texture.</returns> public static int CreateTextTexture(string text, Font font, out SizeF size) { int textureId; size = GetStringSize(text, font); using (Bitmap textBitmap = new Bitmap((int)size.Width, (int)size.Height)) { GL.GenTextures(1, out textureId); GL.BindTexture(TextureTarget.Texture2D, textureId); BitmapData data = textBitmap.LockBits(new Rectangle(0, 0, textBitmap.Width, textBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.Finish(); textBitmap.UnlockBits(data); var gfx = System.Drawing.Graphics.FromImage(textBitmap); gfx.Clear(Color.Transparent); gfx.TextRenderingHint = TextRenderingHint.AntiAlias; gfx.DrawString(text, font, new SolidBrush(Color.White), new RectangleF(0, 0, size.Width + 10, size.Height)); BitmapData data2 = textBitmap.LockBits(new Rectangle(0, 0, textBitmap.Width, textBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, textBitmap.Width, textBitmap.Height, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data2.Scan0); textBitmap.UnlockBits(data2); gfx.Dispose(); } return textureId; }
/// <summary> /// Convert Bitmap to HImage which Halcon dot net data type /// </summary> /// <param name="input"></param> /// <returns></returns> public static HalconDotNet.HImage Bitmap2HImage(System.Drawing.Bitmap input) { if (input == null) { return(new HalconDotNet.HImage()); } try { System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, input.Width, input.Height); HalconDotNet.HImage himg = new HalconDotNet.HImage(); if (input.PixelFormat == System.Drawing.Imaging.PixelFormat.Format8bppIndexed) { System.Drawing.Imaging.BitmapData srcBmpData = input.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); himg.GenImage1("byte", input.Width, input.Height, srcBmpData.Scan0); input.UnlockBits(srcBmpData); } else if (input.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb) { System.Drawing.Imaging.BitmapData srcBmpData = input.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); himg.GenImageInterleaved(srcBmpData.Scan0, "bgr", input.Width, input.Height, -1, "byte", 0, 0, 0, 0, -1, 0); input.UnlockBits(srcBmpData); } else if (input.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) { System.Drawing.Imaging.BitmapData srcBmpData = input.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, input.PixelFormat); himg.GenImageInterleaved(srcBmpData.Scan0, "bgrx", input.Width, input.Height, -1, "byte", input.Width, input.Height, 0, 0, -1, 0); input.UnlockBits(srcBmpData); } else // default: trans to color image { System.Drawing.Imaging.BitmapData srcBmpData = null; System.Drawing.Bitmap MetaBmp = new System.Drawing.Bitmap(input.Width, input.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(MetaBmp); g.DrawImage(input, rect); g.Dispose(); srcBmpData = MetaBmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); himg.GenImageInterleaved(srcBmpData.Scan0, "bgr", input.Width, input.Height, -1, "byte", 0, 0, 0, 0, -1, 0); MetaBmp.UnlockBits(srcBmpData); } return(himg); } catch (HalconDotNet.HalconException ex) { Console.WriteLine("In ImageTypeConverter.Bitmap2HImage: " + ex.Message); return(null); } catch (System.Exception ex) { Console.WriteLine("In ImageTypeConverter.Bitmap2HImage: " + ex.Message); return(null); } }
public static Graphic FromBitmap(Bitmap bmp) { Graphic ret=null; uint width=(uint)bmp.Width; uint height=(uint)bmp.Height; if ((bmp.PixelFormat&PixelFormat.Alpha)==PixelFormat.Alpha) { ret=new Graphic(width, height, Format.RGBA); BitmapData data=bmp.LockBits(new Rectangle(0, 0, (int)width, (int)height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Marshal.Copy(data.Scan0, ret.imageData, 0, (int)(width*height*4)); bmp.UnlockBits(data); } else { ret=new Graphic(width, height, Format.RGB); BitmapData data=bmp.LockBits(new Rectangle(0, 0, (int)width, (int)height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); if (((int)width*3)==data.Stride) { Marshal.Copy(data.Scan0, ret.imageData, 0, (int)(width*height*3)); } else { if (IntPtr.Size==4) { for (uint i=0; i<height; i++) { Marshal.Copy((IntPtr)(data.Scan0.ToInt32()+(int)(i*data.Stride)), ret.imageData, (int)(width*3*i), (int)(width*3)); } } else if (IntPtr.Size==8) { for (uint i=0; i<height; i++) { Marshal.Copy((IntPtr)(data.Scan0.ToInt64()+(long)(i*data.Stride)), ret.imageData, (int)(width*3*i), (int)(width*3)); } } } bmp.UnlockBits(data); data=null; bmp.Dispose(); bmp=null; } return ret; }
/// <summary> /// Apply filter to an image. /// </summary> /// /// <param name="image">Source image to apply filter to.</param> /// /// <returns>Returns filter's result obtained by applying the filter to /// the source image.</returns> /// /// <remarks>The method keeps the source image unchanged and returns /// the result of image processing filter as new image.</remarks> /// /// <exception cref="UnsupportedImageFormatException">Unsupported pixel format of the source image.</exception> /// public Bitmap Apply( Bitmap image ) { // lock source bitmap data BitmapData srcData = image.LockBits( new Rectangle( 0, 0, image.Width, image.Height ), ImageLockMode.ReadOnly, image.PixelFormat ); Bitmap dstImage = null; try { // apply the filter dstImage = Apply( srcData ); if ( ( image.HorizontalResolution > 0 ) && ( image.VerticalResolution > 0 ) ) { dstImage.SetResolution( image.HorizontalResolution, image.VerticalResolution ); } } finally { // unlock source image image.UnlockBits( srcData ); } return dstImage; }
public static bool CovertToGray(Bitmap b) { // GDI+ return format is BGR, NOT RGB. BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int stride = bmData.Stride; // bytes in a row 3*b.Width System.IntPtr Scan0 = bmData.Scan0; unsafe { byte* p = (byte*)(void*)Scan0; byte red, green, blue; int nOffset = stride - b.Width * 3; for (int y = 0; y < b.Height; ++y) { for (int x = 0; x < b.Width; ++x) { blue = p[0]; green = p[1]; red = p[2]; p[0] = p[1] = p[2] = (byte)(.299 * red + .587 * green + .114 * blue); p += 3; } p += nOffset; } } b.UnlockBits(bmData); return true; }
public static Bitmap Rotate90Unsafe(this Bitmap originalBitmap) { Bitmap rotatedBitmap = new Bitmap(originalBitmap.Height, originalBitmap.Width); int newWidth = rotatedBitmap.Width; int originalWidth = originalBitmap.Width; int originalHeight = originalBitmap.Height; int newWidthMinusOne = newWidth - 1; BitmapData originalData = originalBitmap.LockBits(new Rectangle(0, 0, originalWidth, originalHeight), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb); BitmapData rotatedData = rotatedBitmap.LockBits(new Rectangle(0, 0, rotatedBitmap.Width, rotatedBitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb); unsafe { int* originalPointer = (int*)originalData.Scan0.ToPointer(); int* rotatedPointer = (int*)rotatedData.Scan0.ToPointer(); for (int y = 0; y < originalHeight; ++y) { int destinationX = newWidthMinusOne - y; for (int x = 0; x < originalWidth; ++x) { int sourcePosition = (x + y * originalWidth); int destinationY = x; int destinationPosition = (destinationX + destinationY * newWidth); rotatedPointer[destinationPosition] = originalPointer[sourcePosition]; } } originalBitmap.UnlockBits(originalData); rotatedBitmap.UnlockBits(rotatedData); } return rotatedBitmap; }
public void FillByFlood(Bitmap image, Color color, Point pstart) { var colorFill = color; BitmapData pixelData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, image.PixelFormat); IntPtr ptr = pixelData.Scan0; int bytes = pixelData.Stride * pixelData.Height; //.ImageBuffer.Height; var rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); // Fill at here int stride = 4 * image.Width; // linesize var replaceColor = GetColorFromArray(ref rgbValues, pstart.X, pstart.X, stride); var queue = new Queue<Point>(); //start the loop QueueFloodFill4(ref rgbValues, ref queue, pstart.X, pstart.Y, image.Width, image.Height, stride, colorFill, replaceColor); //call next item on queue while (queue.Count > 0) { var pt = queue.Dequeue(); QueueFloodFill4(ref rgbValues, ref queue, pt.X, pt.Y, image.Width, image.Height, stride, colorFill, replaceColor); } // End Fill System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); image.UnlockBits(pixelData); }
public static byte[] BitmapToByteArray(System.Drawing.Bitmap bitmap) { using (Stream BitmapStream = System.IO.File.Open("", System.IO.FileMode.Open)) { Image img = Image.FromStream(BitmapStream); var bmp = new System.Drawing.Bitmap(img); //var thumbnail = bmp.GetThumbnailImage(100, 100, null); } BitmapData bmpdata = null; try { bmpdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); int numbytes = bmpdata.Stride * bitmap.Height; byte[] bytedata = new byte[numbytes]; IntPtr ptr = bmpdata.Scan0; Marshal.Copy(ptr, bytedata, 0, numbytes); return(bytedata); } finally { if (bmpdata != null) { bitmap.UnlockBits(bmpdata); } } }
public static Bitmap Array1DToBitmapRGB(int[] input, int width, int height) { // create new grayscale image Bitmap dstImg = new Bitmap(width, height); // lock destination bitmap data BitmapData dstData = dstImg.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int dstOffset = dstData.Stride - width * 3; // do the job unsafe { byte* dst = (byte*)dstData.Scan0.ToPointer(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++, dst += 3) { dst[RGB.R] = (byte)((input[y * width + x] & 0xFF0000) >> 16); dst[RGB.G] = (byte)((input[y * width + x] & 0xFF00) >> 8); dst[RGB.B] = (byte)((input[y * width + x] & 0xFF)); } dst += dstOffset; } } dstImg.UnlockBits(dstData); return dstImg; }
public static unsafe SD.Image ToImage(this Image <Rgba32> image) { if (!image.TryGetSinglePixelSpan(out var source)) { // Slow... using var ms = new MemoryStream(); image.SaveAsBmp(ms); return(SD.Image.FromStream(ms)); } var w = image.Width; var h = image.Height; var result = new SD.Bitmap(w, h, SD.Imaging.PixelFormat.Format32bppArgb); var bd = result.LockBits(new SD.Rectangle(0, 0, w, h), SD.Imaging.ImageLockMode.WriteOnly, SD.Imaging.PixelFormat.Format32bppArgb); try { var destination = new Span <Bgra32>((void *)bd.Scan0, w * h); for (var i = 0; i < w * h; i++) { var bgra = new Bgra32(); bgra.FromRgba32(source[i]); destination[i] = bgra; } } finally { result.UnlockBits(bd); } return(result); }
public static Bitmap ReduceBitmap(Bitmap sourceImage) { if (sourceImage == null || sourceImage.Width <= 1 || sourceImage.Height <= 1) return null; Bitmap sourceImageBitmap = sourceImage as Bitmap; if (sourceImageBitmap == null || sourceImageBitmap.PixelFormat != PixelFormat.Format1bppIndexed) return null; Bitmap tmpImage = new Bitmap(sourceImage.Width / 2, sourceImage.Height / 2, PixelFormat.Format1bppIndexed); BitmapData sourceData = sourceImageBitmap.LockBits(new Rectangle(0, 0, sourceImageBitmap.Width, sourceImageBitmap.Height), ImageLockMode.ReadOnly, sourceImageBitmap.PixelFormat); BitmapData destData = tmpImage.LockBits(new Rectangle(0, 0, tmpImage.Width, tmpImage.Height), ImageLockMode.ReadOnly, tmpImage.PixelFormat); try { for (int i = 0; i < tmpImage.Height; i++) { #region Older //byte* sourceRow = (byte*)sourceData.Scan0 + (i * 2 * sourceData.Stride); //byte* destRow = (byte*)destData.Scan0 + (i * destData.Stride); //for (int j = 0; j < destData.Stride; destRow[j++] = 0) ; //for (int j = 0; j < tmpImage.Width; j++) //{ // int sourceShift = 7 - (j % 4) * 2; // destRow[j / 8] |= (byte)(((sourceRow[j / 4] & (1 << sourceShift)) >> sourceShift) << (7 - (j % 8))); //} #endregion } } catch { } sourceImageBitmap.UnlockBits(sourceData); tmpImage.UnlockBits(destData); return tmpImage; }
private void DrawRawImages_Bitmap(byte[] rawImageData, int dWidth, int dHeight) { Dispatcher.BeginInvoke(new Action(delegate() { System.Drawing.Bitmap newFrame = new System.Drawing.Bitmap(dWidth, dHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); ColorPalette grayscale = newFrame.Palette; for (int i = 0; i < 256; i++) { grayscale.Entries[i] = System.Drawing.Color.FromArgb((int)255, i, i, i); } newFrame.Palette = grayscale; System.Drawing.Rectangle lockArea = new System.Drawing.Rectangle(0, 0, newFrame.Width, newFrame.Height); BitmapData bitmapData = newFrame.LockBits(lockArea, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); System.Runtime.InteropServices.Marshal.Copy(rawImageData, 0, bitmapData.Scan0, dWidth * dHeight); var bitmapSource = BitmapSource.Create(bitmapData.Width, bitmapData.Height, 96, 96, PixelFormats.Gray8, null, bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride); newFrame.UnlockBits(bitmapData); this.displayImages.Source = bitmapSource; })); }
public static unsafe SD.Image ToImage(this Image <Rgba32> image) { var w = image.Width; var h = image.Height; var result = new SD.Bitmap(w, h, SD.Imaging.PixelFormat.Format32bppArgb); var bd = result.LockBits(new SD.Rectangle(0, 0, w, h), SD.Imaging.ImageLockMode.WriteOnly, SD.Imaging.PixelFormat.Format32bppArgb); try { image.ProcessPixelRows(accessor => { var destination = new Span <Bgra32>((void *)bd.Scan0, w * h); // TODO: BUG! y should go from 0 to h, not w!!! for (var y = 0; y < w; y++) { var row = accessor.GetRowSpan(y); // TODO: BUG! x should go from 0 to w, not h!!! for (var x = 0; x < h; x++) { var bgra = new Bgra32(); bgra.FromRgba32(row[x]); destination[y * w + x] = bgra; } } }); } finally { result.UnlockBits(bd); } return(result); }
/// <summary> /// 生成二维码 /// </summary> /// <param name="url"></param> /// <returns></returns> public static MemoryStream GerQrCodeStream(string url) { BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 300, 300); var bw = new ZXing.BarcodeWriterPixelData(); var pixelData = bw.Write(bitMatrix); var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb); var fileStream = new MemoryStream(); var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } fileStream.Flush(); //.net core 必须要加 fileStream.Position = 0; //.net core 必须要加 bitmap.Save(fileStream, System.Drawing.Imaging.ImageFormat.Png); fileStream.Seek(0, SeekOrigin.Begin); return(fileStream); }
/// <summary> /// Invert Bitmap /// </summary> /// <param name="bm">Bitmap to use</param> public static void DoInvertBitmap(System.Drawing.Bitmap bm) { //direct bit manipulation Rectangle rect = new Rectangle(0, 0, bm.Width, bm.Height); BitmapData bmpData = bm.LockBits(rect, ImageLockMode.ReadWrite, bm.PixelFormat); IntPtr ptr = bmpData.Scan0; int bytes = bm.Width * bm.Height * 4; byte[] rgbValues = new byte[bytes]; //byte r = 0, g = 0, b = 0; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); for (int j = 0; j < bm.Height; j++) { for (int i = 0; i < bm.Width; i++) { int index = CoordsToIndex(i, j, bmpData.Stride); rgbValues[index] = (byte)(255 - rgbValues[index]); rgbValues[index + 1] = (byte)(255 - rgbValues[index + 1]); rgbValues[index + 2] = (byte)(255 - rgbValues[index + 2]); } } System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); // Unlock the bits. bm.UnlockBits(bmpData); }
private static System.Drawing.Bitmap ToSystemBitmap(Bitmap src) { var format = GetSystemPixelFormat(src); var bitmap = new System.Drawing.Bitmap(src.Width, src.Height, format); var bitmapData = bitmap.LockBits( new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.WriteOnly, format ); for (var i = 0; i < src.Height; i++) { unsafe { Buffer.MemoryCopy((src.Scan0 + i * src.Stride).ToPointer(), (bitmapData.Scan0 + i * bitmapData.Stride).ToPointer(), bitmapData.Stride, (src.Channel * src.Depth * src.Width) >> 3); } } bitmap.UnlockBits(bitmapData); return(bitmap); }
public SpriteSheet(Bitmap texbmp, int[] cycleStartNums, int[] cycleLengths, int _texw, int _texh, bool _hasAlpha, double _framesPerSecond = 1.0) { texw = _texw; texh = _texh; hasAlpha = _hasAlpha; framesPerSecond = _framesPerSecond; texID = -1; BitmapData bmp_data = texbmp.LockBits(new Rectangle(0, 0, texbmp.Width, texbmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); tex = new byte[cycleStartNums.Length][][]; for(int cycleNum = 0; cycleNum < cycleStartNums.Length; cycleNum++) { tex[cycleNum] = new byte[cycleLengths[cycleNum]][]; for(int frameNum = 0; frameNum < cycleLengths[cycleNum]; frameNum++) { IntPtr tex_addr = IntPtr.Add(bmp_data.Scan0, (cycleStartNums[cycleNum] + frameNum) * texw * texh * 4); tex[cycleNum][frameNum] = new byte[texw * texh * 4]; Marshal.Copy(tex_addr, tex[cycleNum][frameNum], 0, tex[cycleNum][frameNum].Length); //Rearrange BGRA -> RGBA and invert colors to proper encoding for(int i = 0; i < tex[cycleNum][frameNum].Length; i += 4) { byte temp = tex[cycleNum][frameNum][i]; tex[cycleNum][frameNum][i] = (byte)(tex[cycleNum][frameNum][i + 2]); tex[cycleNum][frameNum][i + 2] = (byte)temp; //tex[cycleNum][frameNum][i + 1] = (byte)~tex[cycleNum][frameNum][i + 1]; } } } texbmp.UnlockBits(bmp_data); /* texID = GL.GenTexture();*/ // GL.BindTexture(TextureTarget.Texture2D, texID); // GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, texw, texh, 0, PixelFormat.Rgba, PixelType.UnsignedByte, tex[0][0]); prevCycleNum = -1; prevFrameNum = -1; allSprites.Add(this); }
private double rowPixelDeviation(System.Drawing.Bitmap bmp, int row) { int count = 0; double total = 0; double totalVariance = 0; double standardDeviation = 0; System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat); int stride = bmpData.Stride; IntPtr firstPixelInImage = bmpData.Scan0; unsafe { byte *p = (byte *)(void *)firstPixelInImage; p += stride * row; // find starting pixel of the specified row for (int column = 0; column < bmp.Width; column++) { count++; //count the pixels byte blue = p[0]; byte green = p[1]; byte red = p[3]; int pixelValue = System.Drawing.Color.FromArgb(0, red, green, blue).ToArgb(); total += pixelValue; double average = total / count; totalVariance += Math.Pow(pixelValue - average, 2); standardDeviation = Math.Sqrt(totalVariance / count); //go to next pixel p += 3; } } bmp.UnlockBits(bmpData); return(standardDeviation); }
//缩小 public static void Dilation(Bitmap image, float horizon, float verticale) { BitmapData data = image.LockBits(new Rectangle(new Point(), image.Size), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);//将图像锁定到内存中 byte[] datasOld = new byte[data.Stride * image.Height]; //图像数组 byte[] datasNew = new byte[data.Stride * image.Height]; //图像数组 //将图像在内存中的数据复制到图像数组中 Marshal.Copy(data.Scan0, datasOld, 0, datasOld.Length); for (int y = 0; y < image.Height * data.Stride; y += data.Stride) { for (int x = 0; x < image.Width * 3; x += 3) { int xNew = x / 3, yNew = y / data.Stride; int xOld = (int)(xNew / horizon); int yOld = (int)(yNew / verticale); if (xOld < 0 || xOld >= image.Width || yOld < 0 || yOld >= image.Height) continue; int indexOld = yOld * data.Stride + xOld * 3; int indexNew = y + x; datasNew[indexNew] = datasNew[indexNew + 1] = datasNew[indexNew + 2] = datasOld[indexOld]; } } Marshal.Copy(datasNew, 0, data.Scan0, datasOld.Length); //将图像数组复制到内存中 image.UnlockBits(data); //将图像从内存中解锁 }
static System.Drawing.Bitmap getBarCodeBitmap() { var info = new { Width = 100, Height = 50, Margin = 10, Format = ZXing.BarcodeFormat.CODE_128, Code = "12345EAN12345678", ShowCode = false }; var width = info.Width; // width of the Qr Code var height = info.Height; // height of the Qr Code var margin = info.Margin; var CodeWriter = new ZXing.BarcodeWriterPixelData { Format = info.Format, Options = new ZXing.Common.EncodingOptions { Height = height, Width = width, Margin = margin }, }; var pixelData = CodeWriter.Write(info.Code); // creating a bitmap from the raw pixel data; if only black and white colors are used it makes no difference // that the pixel data ist BGRA oriented and the bitmap is initialized with RGB using (var bitmap = new System.Drawing.Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb)) using (var ms = new MemoryStream()) { var bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); try { // we assume that the row stride of the bitmap is aligned to 4 byte multiplied by the width of the image System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length); } finally { bitmap.UnlockBits(bitmapData); } return(new Bitmap(bitmap)); } }
/// <summary> /// Creates a bitmap of a palette with size 16x16. Each pixel has the /// color of the corresponding palette index. /// </summary> /// <param name="Palette"></param> /// <returns></returns> public unsafe static System.Drawing.Bitmap GetPaletteBitmap(ColorPalette Palette) { // create bitmap System.Drawing.Bitmap bmp = new System.Drawing.Bitmap( 16, 16, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); // lock pixels BitmapData data = bmp.LockBits( new Rectangle(0, 0, 16, 16), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); byte *ptrScan0 = (byte *)data.Scan0; // create pixels // this will set each pixel to an index from the colorpal for (int i = 0; i < 256; i++) { // set pixel to color i *ptrScan0 = (byte)i; // increase ptr to next pixel ptrScan0++; } // unlock bmp.UnlockBits(data); // set palette bmp.Palette = Palette; return(bmp); }
public unsafe void Fill(int[] indexes, System.Drawing.Size size, ref System.Drawing.Bitmap bitmap) { float scaleX = bitmap.Width / (float)size.Width; float scaleY = bitmap.Height / (float)size.Height; BitmapData bdata = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); try { IntPtr scan0 = bdata.Scan0; int stride = bdata.Stride; byte * ptr0 = (byte *)scan0.ToPointer(); byte * ptr = ptr0; int count = indexes.Length; int r = 0, c = 0; int w = size.Width; int h = size.Height; for (int i = 0; i < count; i++) { r = indexes[i] / w; c = indexes[i] - r * w; r = (int)(r * scaleY); c = (int)(c * scaleX); ptr = ptr0 + r * stride + c; *ptr = 1;//true value } } finally { bitmap.UnlockBits(bdata); } }
private bool _Draw(byte[] buffer) { var rgb = _scale.Convert(buffer); if (_image == null) { _image = new Bitmap(_width, _height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); } BitmapData imageData = _image.LockBits(new Rectangle(0, 0, _width, _height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb); Marshal.Copy(rgb, 0, imageData.Scan0, rgb.Length); _image.UnlockBits(imageData); try { if (_control.IsHandleCreated && !_control.IsDisposed) { var g = _control.CreateGraphics(); g.DrawImage(_image, new Rectangle(0, 0, _control.Width, _control.Height)); g.Dispose(); } } catch (Exception e) { if (_control.IsHandleCreated && !_control.IsDisposed) { } else { throw; } } return(true); }
/// <summary> /// Convert a <see cref="System.Drawing.Bitmap"/> to a <see cref="SharpDX.Direct2D1.Bitmap"/>. /// </summary> /// <param name="bitmap">The value to convert.</param> /// <param name="renderTarget">The Direct2D1 RenderTarget.</param> /// <returns>The converted value.</returns> public static SharpDX.Direct2D1.Bitmap ToDxBitmap(this System.Drawing.Bitmap bitmap, RenderTarget renderTarget) { var sourceArea = new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height); var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)); var size = new SharpDX.Size2(bitmap.Width, bitmap.Height); // Transform pixels from BGRA to RGBA int stride = bitmap.Width * sizeof(int); using (var tempStream = new DataStream(bitmap.Height * stride, true, true)) { // Lock System.Drawing.Bitmap var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // Convert all pixels for (int y = 0; y < bitmap.Height; y++) { int offset = bitmapData.Stride * y; for (int x = 0; x < bitmap.Width; x++) { // Not optimized byte B = Marshal.ReadByte(bitmapData.Scan0, offset++); byte G = Marshal.ReadByte(bitmapData.Scan0, offset++); byte R = Marshal.ReadByte(bitmapData.Scan0, offset++); byte A = Marshal.ReadByte(bitmapData.Scan0, offset++); int rgba = R | (G << 8) | (B << 16) | (A << 24); tempStream.Write(rgba); } } bitmap.UnlockBits(bitmapData); tempStream.Position = 0; return(new SharpDX.Direct2D1.Bitmap(renderTarget, size, tempStream, stride, bitmapProperties)); } }
public static void Transfer(SpanBitmap src, GDIBITMAP dst, SpanBitmap.Action2 action) { src = src.AsReadOnly(); var rect = new Rectangle(0, 0, dst.Width, dst.Height); GDIPTR dstBits = null; try { dstBits = dst.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, dst.PixelFormat); var dstSpan = dstBits .AsPointerBitmapDangerous() .AsSpanBitmap(); action(src, dstSpan); } finally { if (dstBits != null) { dst.UnlockBits(dstBits); } } }
private void HistForm_Load(object sender, EventArgs e) { Rectangle rect = new Rectangle(0, 0, bmpHist.Width, bmpHist.Height); System.Drawing.Imaging.BitmapData bmpData = bmpHist.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmpHist.PixelFormat); IntPtr ptr = bmpData.Scan0; int bytes = bmpHist.Width * bmpHist.Height; byte[] grayValue = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, grayValue, 0, bytes); byte temp = 0; maxPixel = 0; Array.Clear(countPixel, 0, 256); for (int i = 0; i < bytes; i++) { temp = grayValue[i]; countPixel[temp]++; if (countPixel[temp] > maxPixel) { maxPixel = countPixel[temp]; } } System.Runtime.InteropServices.Marshal.Copy(grayValue, 0, ptr, bytes); bmpHist.UnlockBits(bmpData); }
protected void createBitmap(int width, int height, ref double[] elems, ref Bitmap lbitmap) { getData(width, height, ref elems); // the return format is BGR, NOT RGB. BitmapData bmData = lbitmap.LockBits(new Rectangle(0, 0, lbitmap.Width, lbitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); byte r, g, b; int stride = bmData.Stride; System.IntPtr Scan0 = bmData.Scan0; unsafe { byte* p = (byte*)(void*)Scan0; int nOffset = stride - width * 3; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { int elem = y + x * height; //this is organized differently, height x width getcolors(elems[elem], out r, out g, out b); p[0] = b; p[1] = g; p[2] = r; p += 3; } p += nOffset; } } lbitmap.UnlockBits(bmData); }
private static void _LoadTextureLazyPremultiplyXNA(GraphicsDevice gd, Stream stream, out int w, out int h, out byte[] data) { using (SD.Bitmap bmp = new SD.Bitmap(stream)) { w = bmp.Width; h = bmp.Height; int depth = SD.Image.GetPixelFormatSize(bmp.PixelFormat); SD.Bitmap copy = null; if (depth != 32) { copy = bmp.Clone(new SD.Rectangle(0, 0, w, h), SDI.PixelFormat.Format32bppArgb); } using (copy) { SD.Bitmap src = copy ?? bmp; SDI.BitmapData srcData = src.LockBits( new SD.Rectangle(0, 0, w, h), SDI.ImageLockMode.ReadOnly, src.PixelFormat ); data = new byte[w * h * 4]; unsafe { byte *from = (byte *)srcData.Scan0; fixed(byte *to = data) { for (int i = data.Length - 1 - 3; i > -1; i -= 4) { byte r = from[i + 2]; byte g = from[i + 1]; byte b = from[i + 0]; byte a = from[i + 3]; if (a == 0) { continue; } if (a == 255) { to[i + 0] = r; to[i + 1] = g; to[i + 2] = b; to[i + 3] = a; continue; } to[i + 0] = (byte)Math.Round(r * a / 255D); to[i + 1] = (byte)Math.Round(g * a / 255D); to[i + 2] = (byte)Math.Round(b * a / 255D); to[i + 3] = a; } } } src.UnlockBits(srcData); } } }
/// <summary> /// 二值化Bitmap /// </summary> /// <param name="dm"></param> /// <param name="filePath"></param> /// <param name="newFilePath"></param> public static void Binarization(this DmPlugin dm,string filePath, string newFilePath) { Bitmap btmp = new Bitmap(filePath); BitmapData btmpd = btmp.LockBits(new Rectangle(0, 0, btmp.Width, btmp.Height), ImageLockMode.ReadWrite, btmp.PixelFormat); //32位深度为4,24位为3 int PixelSize = 3; unsafe { for (int i = 0; i < btmp.Height; i++) { for (int j = 0; j < btmp.Width; j++) { // ded8c7 byte* row = (byte*)btmpd.Scan0 + PixelSize * j + (i * btmpd.Stride); if (row[0] + row[1] + row[2] > 382) { // if(row[0]!=(int)0xde&&row[1]!=(int)0xd8&&row[2]!=(int)0xc7) row[0] = row[1] = row[2] = 255; continue; } row[0] = row[1] = row[2] = 0; } } } btmp.Save(newFilePath); }
// convert byte array to 8 bit grayscale bitmap protected Bitmap fCreateBitmap(byte[] bArray, int[] iSize, float[] fRes) { int iWidth = iSize[0]; int iHeight = iSize[1]; // create new bitmap System.Drawing.Bitmap bmBitmap = new System.Drawing.Bitmap(iWidth, iHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); bmBitmap.SetResolution(fRes[0], fRes[1]); // create new bitmap data BitmapData bmData = bmBitmap.LockBits(new System.Drawing.Rectangle(0, 0, iWidth, iHeight), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); // copy data Marshal.Copy(bArray, 0, bmData.Scan0, (int)(iWidth * iHeight)); bmBitmap.UnlockBits(bmData); // create grayscale color palette ColorPalette _palette = bmBitmap.Palette; System.Drawing.Color[] _entries = _palette.Entries; for (int i = 0; i < 256; i++) { System.Drawing.Color b = new System.Drawing.Color(); b = System.Drawing.Color.FromArgb((byte)i, (byte)i, (byte)i); _entries[i] = b; } bmBitmap.Palette = _palette; // return bitmap return(bmBitmap); }
public Texture2D(System.Drawing.Bitmap bitmap, bool genMipmap = true, PixelInternalFormat internalFormat = PixelInternalFormat.Rgba) : this(bitmap.Width, bitmap.Height) { internal_format = internalFormat; /* * for (int x = 0; x < Width; x++) { * for (int y = 0; y < Height; y++) { * Pixels[x, y] = bitmap.GetPixel(x, y); * } * } */ var data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat); var bytes = new byte[data.Stride * bitmap.Height]; System.Runtime.InteropServices.Marshal.Copy(data.Scan0, bytes, 0, bytes.Length); var bpp = data.Stride / data.Width; for (int i = 0; i < bytes.Length; i += bpp) { var pixelindex = (i / bpp); pixels[pixelindex % bitmap.Width, pixelindex / bitmap.Width] = new color32(bytes[i + 2], bytes[i + 1], bytes[i], bpp == 4 ? bytes[i + 3] : (byte)255); } bitmap.UnlockBits(data); apply(genMipmap); }
static int LoadTexture(string filename) { if (String.IsNullOrEmpty(filename)) { throw new ArgumentException(filename); } int id = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, id); // We will not upload mipmaps, so disable mipmapping (otherwise the texture will not appear). // We can use GL.GenerateMipmaps() or GL.Ext.GenerateMipmaps() to create // mipmaps automatically. In that case, use TextureMinFilter.LinearMipmapLinear to enable them. GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(filename); BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0); bmp.UnlockBits(bmp_data); return(id); }
// This method assumes that private void CreateBitmapTexture() { BindTexture(); System.Drawing.Bitmap textBmp = new System.Drawing.Bitmap(500, 500); // match window size // just allocate memory, so we can update efficiently using TexSubImage2D GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, textBmp.Width, textBmp.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); using (System.Drawing.Graphics gfx = System.Drawing.Graphics.FromImage(textBmp)) { gfx.Clear(System.Drawing.Color.Transparent); // TODO: Could create an enumeration for choosing btw different font families! Font drawFont = new Font("Arial", fontSize); SolidBrush drawBrush = new SolidBrush(color); // TODO: Maybe we should not use shape.Position here, because different coordinate system !!? System.Drawing.PointF drawPoint = new System.Drawing.PointF(shape.Position.X, shape.Position.Y); gfx.DrawString(text, drawFont, drawBrush, drawPoint); // Draw as many strings as you need } BitmapData data = textBmp.LockBits(new System.Drawing.Rectangle(0, 0, textBmp.Width, textBmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, textBmp.Width, textBmp.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); textBmp.UnlockBits(data); UnbindTexture(); }
// Add the static resources defined in the map; if the map lives // in a world use AddCustomTerrain instead public static Bitmap AddStaticResources(Map map, Bitmap terrainBitmap) { Bitmap terrain = new Bitmap(terrainBitmap); var tileset = Rules.TileSets[map.Tileset]; var bitmapData = terrain.LockBits(new Rectangle(0, 0, terrain.Width, terrain.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); unsafe { int* c = (int*)bitmapData.Scan0; for (var x = 0; x < map.Bounds.Width; x++) for (var y = 0; y < map.Bounds.Height; y++) { var mapX = x + map.Bounds.Left; var mapY = y + map.Bounds.Top; if (map.MapResources.Value[mapX, mapY].type == 0) continue; var res = Rules.Info["world"].Traits.WithInterface<ResourceTypeInfo>() .Where(t => t.ResourceType == map.MapResources.Value[mapX, mapY].type) .Select(t => t.TerrainType).FirstOrDefault(); if (res == null) continue; *(c + (y * bitmapData.Stride >> 2) + x) = tileset.Terrain[res].Color.ToArgb(); } } terrain.UnlockBits(bitmapData); return terrain; }
public Texture(string _mapPath, bool flipY = true) { using (Stream s = Interface.GetStreamFromPath (_mapPath)) { try { Map = _mapPath; Bitmap bitmap = new Bitmap (s); if (flipY) bitmap.RotateFlip (RotateFlipType.RotateNoneFlipY); BitmapData data = bitmap.LockBits (new System.Drawing.Rectangle (0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); createTexture (data.Scan0, data.Width, data.Height); bitmap.UnlockBits (data); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear); GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.GenerateMipmap (GenerateMipmapTarget.Texture2D); } catch (Exception ex) { Debug.WriteLine ("Error loading texture: " + Map + ":" + ex.Message); } } }
public static Bitmap ScreenShot(int xx, int yy, int width, int height, ReadBufferMode buffer) { Bitmap transfermap = new Bitmap(width, height); System.Drawing.Imaging.BitmapData data = transfermap.LockBits(new Rectangle(0, 0, transfermap.Width, transfermap.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.ReadBuffer(buffer); GL.ReadPixels(xx, yy, transfermap.Width, transfermap.Height, OpenTK.Graphics.OpenGL4.PixelFormat.Rgba, PixelType.UnsignedByte, data.Scan0); unsafe { int PixelSize = 4; unsafe { for (int y = 0; y < data.Height; y++) { byte* row = (byte*)data.Scan0 + (y * data.Stride); for (int x = 0; x < data.Width; x++) { byte r = row[x * PixelSize + 2]; byte b = row[x * PixelSize]; row[x * PixelSize] = r; row[x * PixelSize + 2] = b; } } } } transfermap.UnlockBits(data); transfermap.RotateFlip(RotateFlipType.RotateNoneFlipY); return transfermap; }
public JBitmap(int w, int h, JBitmapPixelFormat _format) { format = _format; bitmap = new Bitmap(w, h, GetPixFormat(format)); bitmapData = bitmap.LockBits(new Rectangle(0, 0, w, h),ImageLockMode.ReadWrite, GetPixFormat(format)); }
public Object LoadImage(String filename) { Object image = null; if (File.Exists(filename)) { using (System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)System.Drawing.Bitmap.FromFile(filename)) { System.Drawing.Imaging.BitmapData bData = bmp.LockBits( new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb ); SharpDX.DataStream stream = new SharpDX.DataStream(bData.Scan0, bData.Stride * bData.Height, true, false); SharpDX.Direct2D1.PixelFormat pFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, SharpDX.Direct2D1.AlphaMode.Premultiplied); SharpDX.Direct2D1.BitmapProperties bProps = new SharpDX.Direct2D1.BitmapProperties(pFormat); image = new SharpDX.Direct2D1.Bitmap(d2dRenderTarget, new Size2(bmp.Width, bmp.Height), stream, bData.Stride, bProps); bmp.UnlockBits(bData); stream.Dispose(); } } return(image); }
public static Bitmap ActorsBitmap(World world) { var map = world.Map; var size = Util.NextPowerOf2(Math.Max(map.Bounds.Width, map.Bounds.Height)); Bitmap bitmap = new Bitmap(size, size); var bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); unsafe { int* c = (int*)bitmapData.Scan0; foreach (var t in world.Queries.WithTrait<IRadarSignature>()) { if (!world.LocalShroud.IsVisible(t.Actor)) continue; var color = t.Trait.RadarSignatureColor(t.Actor); foreach (var cell in t.Trait.RadarSignatureCells(t.Actor)) if (world.Map.IsInMap(cell)) *(c + ((cell.Y - world.Map.Bounds.Top) * bitmapData.Stride >> 2) + cell.X - world.Map.Bounds.Left) = color.ToArgb(); } } bitmap.UnlockBits(bitmapData); return bitmap; }
public static void Transfer(GDIBITMAP src, SpanBitmap dst, SpanBitmap.Action2 action) { var rect = new Rectangle(0, 0, dst.Width, dst.Height); GDIPTR srcBits = null; try { srcBits = src.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, src.PixelFormat); var srcSpan = srcBits .AsPointerBitmapDangerous() .AsSpanBitmap() .AsReadOnly(); action(srcSpan, dst); } finally { if (srcBits != null) { src.UnlockBits(srcBits); } } }
public static void CalcDifference(Bitmap bmp1, Bitmap bmp2) { Rectangle rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height); BitmapData bitmapdata = bmp1.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); IntPtr source = bitmapdata.Scan0; BitmapData data2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); IntPtr ptr2 = data2.Scan0; int length = (bmp1.Width * bmp1.Height) * 4; byte[] destination = new byte[length]; byte[] buffer2 = new byte[length]; Marshal.Copy(source, destination, 0, length); Marshal.Copy(ptr2, buffer2, 0, length); for (int i = 0; i < length; i += 4) { if (((destination[i] == buffer2[i]) && (destination[i + 1] == buffer2[i + 1])) && (destination[i + 2] == buffer2[i + 2])) { destination[i] = 0xff; destination[i + 1] = 0xff; destination[i + 2] = 0xff; destination[i + 3] = 0; } } Marshal.Copy(destination, 0, source, length); bmp1.UnlockBits(bitmapdata); bmp2.UnlockBits(data2); }
public static Bitmap ConvertTo8bppFormat(Bitmap image) { // Create new image with 8BPP format Bitmap destImage = new Bitmap( image.Width, image.Height, PixelFormat.Format8bppIndexed ); // Lock bitmap in memory BitmapData bitmapData = destImage.LockBits( new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, destImage.PixelFormat ); for (int i = 0; i < image.Width; i++) { for (int j = 0; j < image.Height; j++) { // Get source color Color color = image.GetPixel(i, j); // Get index of similar color byte index = GetSimilarColor(destImage.Palette, color); WriteBitmapData(i, j, index, bitmapData, 8); } } destImage.UnlockBits(bitmapData); return destImage; }
public static NativeBmp CreateNativeWrapper(System.Drawing.Bitmap bmp) { var bmpdata = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat); int bpp = 24; switch (bmpdata.PixelFormat) { case System.Drawing.Imaging.PixelFormat.Format24bppRgb: { bpp = 24; } break; case System.Drawing.Imaging.PixelFormat.Format32bppArgb: { bpp = 32; } break; default: { throw new NotSupportedException(); } } NativeBmp nativeBmp = CreateNativeWrapper(bmp.Width, bmp.Height, bmpdata.Stride, bpp, bmpdata.Scan0); bmp.UnlockBits(bmpdata); return(nativeBmp); }
/// <summary> /// System.Drawing.Bitmapから変換 /// </summary> /// <param name="bitmap">ベットムップ</param> /// <returns>XPM</returns> public static ぉ[] ぉに変換(System.Drawing.Bitmap bitmap) { var arr = new ぉ[bitmap.Width * bitmap.Height]; BitmapData data = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); int bytes = bitmap.Width * bitmap.Height * 4; for (int i = 0, j = 0; i < bytes; i += 4, j++) { Int32 value = Marshal.ReadInt32(data.Scan0, i); byte b = (byte)(value & 0xff); byte g = (byte)((value >> 8) & 0xff); byte r = (byte)((value >> 16) & 0xff); byte a = (byte)((value >> 24) & 0xff); if (a == 0) { r = g = b = 0; } else { a = 0xff; } arr[j] = new ぉ(r, g, b, a); } bitmap.UnlockBits(data); return(arr); }
/// <summary> /// Loads a bitmap from the given texture. Be careful: The texture must have CPU read access and this only matches for staging textures. /// </summary> /// <param name="texture">The texture to be loaded into the bitmap.</param> public static GDI.Bitmap LoadBitmapFromMemoryMappedTexture(MemoryMappedTexture <int> texture) { texture.EnsureNotNullOrDisposed(nameof(texture)); var width = texture.Width; var height = texture.Height; // Create and lock bitmap so it can be accessed for texture loading var resultBitmap = new GDI.Bitmap(width, height); var bitmapData = resultBitmap.LockBits( new GDI.Rectangle(0, 0, resultBitmap.Width, resultBitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); try { SeeingSharpUtil.CopyMemory( texture.Pointer, bitmapData.Scan0, texture.SizeInBytes); } finally { resultBitmap.UnlockBits(bitmapData); } return(resultBitmap); }
private void LoadBitmap(Bitmap BitmapImage, bool FlipY = true) { /* .net library has methods for converting many image formats so I exploit that by using * .net to convert any filetype to a bitmap. Then the bitmap is locked into memory so * that the garbage collector doesn't touch it, and it is read via OpenGL glTexImage2D. */ if (FlipY) BitmapImage.RotateFlip(RotateFlipType.RotateNoneFlipY); // bitmaps read from bottom up, so flip it this.Size = BitmapImage.Size; // must be Format32bppArgb file format, so convert it if it isn't in that format BitmapData bitmapData = BitmapImage.LockBits(new Rectangle(0, 0, BitmapImage.Width, BitmapImage.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // set the texture target and then generate the texture ID this.TextureTarget = TextureTarget.Texture2D; this.TextureID = Gl.GenTexture(); Gl.PixelStorei(PixelStoreParameter.UnpackAlignment, 1); // set pixel alignment Gl.BindTexture(TextureTarget, TextureID); // bind the texture to memory in OpenGL //Gl.TexParameteri(TextureTarget, TextureParameterName.GenerateMipmap, 0); Gl.TexImage2D(TextureTarget, 0, PixelInternalFormat.Rgba8, BitmapImage.Width, BitmapImage.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bitmapData.Scan0); Gl.TexParameteri(TextureTarget, TextureParameterName.TextureMagFilter, TextureParameter.Nearest); Gl.TexParameteri(TextureTarget, TextureParameterName.TextureMinFilter, TextureParameter.Nearest);//(int)TextureParam.Linear); // linear filter BitmapImage.UnlockBits(bitmapData); BitmapImage.Dispose(); }
public void Plot(ref byte[] fileBufferArray, int fileSize, int offset) { int columns = pictureBox1.Width; int rows = pictureBox1.Height; byte currentByte; int currentColumn; int location = offset; Bitmap b = new Bitmap(columns, rows, PixelFormat.Format24bppRgb); BitmapData bmd = b.LockBits(new Rectangle(0, 0, columns, rows), ImageLockMode.ReadWrite, b.PixelFormat); unsafe { for (int j = 0; j < rows; j++) { byte* row = (byte*)bmd.Scan0 + (j * bmd.Stride); for (int i = 0; i<640; i++) { if (location < fileSize) { currentByte = fileBufferArray[location]; row[currentByte * 3 + 1] = 255; //green location++; } } } b.UnlockBits(bmd); pictureBox1.Image = b; }//unsafe }
public unsafe static bool AreEqual(Bitmap imageA, Bitmap imageB) { if (imageA.Width != imageB.Width) return false; if (imageA.Height != imageB.Height) return false; var d1 = imageA.LockBits(new Rectangle(0, 0, imageA.Width - 1, imageA.Height - 1), ImageLockMode.ReadOnly, imageA.PixelFormat); var d2 = imageB.LockBits(new Rectangle(0, 0, imageB.Width - 1, imageB.Height - 1), ImageLockMode.ReadOnly, imageB.PixelFormat); var data1 = (byte*)d1.Scan0; var data2 = (byte*)d2.Scan0; bool result = true; for (int n = 0; n < d1.Height * d1.Stride; n++) { if (data1[n] != data2[n]) { result = false; break; } } imageA.UnlockBits(d1); imageB.UnlockBits(d2); return result; }
/// <summary> /// ぉをベットムッピに変換する /// </summary> /// <param name="width">幅</param> /// <param name="height">高さ</param> /// <param name="arr">ピクセルデター</param> /// <returns>ベットムッピ</returns> public static System.Drawing.Bitmap ベットムップに変換(int width, int height, ぉ[] arr) { var bitmap = new System.Drawing.Bitmap(width, height); var data = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int k = 0; for (int i = 0; i < (width * height); i++, k += 4) { var c = arr[i]; byte r = (byte)(c.R & 0xff); byte g = (byte)(c.G & 0xff); byte b = (byte)(c.B & 0xff); byte a = (byte)(c.A & 0xff); Int32 value = (a << 24) | (r << 16) | (g << 8) | b; Marshal.WriteInt32(data.Scan0, k, value); } bitmap.UnlockBits(data); return(bitmap); }
/// <summary> /// Create a new <see cref="Bitmap"/> instance using an array of <see cref="Color"/> pixels and the image width and height. /// </summary> /// <param name="colors"><see cref="Color"/> array containing the color of each pixel in the image.</param> /// <param name="width">The width of the image.</param> /// <param name="height">The height of the image.</param> /// <returns>A new <see cref="Bitmap"/> instance created using the data provided.</returns> public static Bitmap Create(Color[] colors, int width, int height) { Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); BitmapData bitmapData = bitmap.LockBits ( new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, bitmap.PixelFormat ); unsafe { byte* p = (byte*)bitmapData.Scan0; Parallel.For(0, height, y => { for (int x = 0; x < width; x++) { int offset = (x * 4) + y * bitmapData.Stride; Color color = colors[x + y * width]; p[offset] = color.B; p[offset + 1] = color.G; p[offset + 2] = color.R; p[offset + 3] = color.A; } }); } bitmap.UnlockBits(bitmapData); return bitmap; }
/* Class regroupant les fonctions permettant de chercher une image dans un Stream Image par comparaison de pixel */ public Boolean checkImagePresentInStreamImage(MemoryStream screen_check, string img_check) { int i = 0; bool trouve = false; System.Drawing.Bitmap sourceImage = (Bitmap)Bitmap.FromStream(new MemoryStream(screen_check.ToArray())); System.Drawing.Bitmap template = (Bitmap)Bitmap.FromFile(img_check); // System.Drawing.Bitmap template = (Bitmap)Properties.Resources.r_egide; // avec les images en resources(not working) // create template matching algorithm's instance (hreshold ~ 92.5%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template); // highlight found matchings System.Drawing.Imaging.BitmapData data = sourceImage.LockBits(new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { // on compte le nombre de tour dans le foreach(1 tour = image trouvée, 0 = image non trouvée) i++; AForge.Imaging.Drawing.Rectangle(data, m.Rectangle, System.Drawing.Color.White); //affiche la localisation de l'image trouvée //MessageBox.Show("position= " + m.Rectangle.Location.ToString()); } // à revoir pour faire chaque perso de chaque groupe if (i != 0) { trouve = true; } sourceImage.UnlockBits(data); return(trouve); }
/// <summary> /// 查找图片,不能镂空 /// </summary> /// <param name="subPic"></param> /// <param name="parPic"></param> /// <param name="searchRect">如果为empty,则默认查找整个图像</param> /// <param name="errorRange">容错,单个色值范围内视为正确0~255</param> /// <param name="matchRate">图片匹配度,默认90%</param> /// <param name="isFindAll">是否查找所有相似的图片</param> /// <returns>返回查找到的图片的中心点坐标</returns> public System.Drawing.Point FindPicture(string subPic, float matchRate, bool isFindAll = false) { System.Drawing.Point Rst = new System.Drawing.Point(); System.Drawing.Bitmap sourceImage = getScreen(); System.Drawing.Bitmap template = (Bitmap)Bitmap.FromFile(subPic); // create template matching algorithm's instance // (set similarity threshold to 92.1%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(matchRate); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template); // highlight found matchings BitmapData data = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { Drawing.Rectangle(data, m.Rectangle, Color.White); Rst = m.Rectangle.Location; //MessageBox.Show(m.Rectangle.Location.ToString()); // do something else with matching } sourceImage.UnlockBits(data); return(Rst); }
public static Image CopyTextureToBitmap(D3D.Texture2D texture) { int width = texture.Description.Width; if (width % 16 != 0) width = MathExtensions.Round(width, 16) + 16; Bitmap bmp = new Bitmap(texture.Description.Width, texture.Description.Height, PixelFormat.Format32bppArgb); BitmapData bData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); using (DataStream stream = new DataStream(bData.Scan0, bData.Stride * bData.Height, false, true)) { DataRectangle rect = texture.Map(0, D3D.MapMode.Read, D3D.MapFlags.None); using (DataStream texStream = rect.Data) { for (int y = 0; y < texture.Description.Height; y++) for (int x = 0; x < rect.Pitch; x+=4) { byte[] bytes = texStream.ReadRange<byte>(4); if (x < bmp.Width*4) { stream.Write<byte>(bytes[2]); // DXGI format is BGRA, GDI format is RGBA. stream.Write<byte>(bytes[1]); stream.Write<byte>(bytes[0]); stream.Write<byte>(255); } } } } bmp.UnlockBits(bData); return bmp; }
private void znajdzToolStripMenuItem_Click(object sender, EventArgs e) { System.Drawing.Bitmap sourceImage = (Bitmap)pictureBox2.Image; System.Drawing.Bitmap template = (Bitmap)pictureBox3.Image; // create template matching algorithm's instance // (set similarity threshold to 92.1%) ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0.921f); // find all matchings with specified above similarity TemplateMatch[] matchings = tm.ProcessImage(sourceImage, template); // highlight found matchings BitmapData data = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); foreach (TemplateMatch m in matchings) { Drawing.Rectangle(data, m.Rectangle, Color.White); //MessageBox.Show(m.Rectangle.Location.ToString()); richTextBox1.Text += "Obrazek znaleziony: m.Rectangle.Location.ToString() /n"; lokalizacja = m.Rectangle.Location; // do something else with matching } sourceImage.UnlockBits(data); }
public int ProcessBuffer(double sampleTime, IntPtr buffer, int bufferLength) { using (Bitmap bitmap = new Bitmap(_width, _height, _format)) { BitmapData data = bitmap.LockBits(_bounds, ImageLockMode.ReadWrite, _format); NativeMethods.CopyMemory(data.Scan0, buffer, (uint) bufferLength); bitmap.UnlockBits(data); if (_flipImages) bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); UpdateImage(sampleTime, bitmap); if (_flipImages) bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); data = bitmap.LockBits(_bounds, ImageLockMode.ReadOnly, _format); NativeMethods.CopyMemory(buffer, data.Scan0, (uint) bufferLength); bitmap.UnlockBits(data); } return 0; }