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); }
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; }
/// <summary>Loads a texture from the specified file.</summary> /// <param name="file">The file that holds the texture.</param> /// <param name="texture">Receives the texture.</param> /// <returns>Whether loading the texture was successful.</returns> internal bool Parse(string file, out Texture texture) { /* * Read the bitmap. This will be a bitmap of just * any format, not necessarily the one that allows * us to extract the bitmap data easily. * */ System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(file); Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); /* * If the bitmap format is not already 32-bit BGRA, * then convert it to 32-bit BGRA. * */ if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) { Bitmap compatibleBitmap = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format32bppArgb); Graphics graphics = Graphics.FromImage(compatibleBitmap); graphics.DrawImage(bitmap, rect, rect, GraphicsUnit.Pixel); graphics.Dispose(); bitmap.Dispose(); bitmap = compatibleBitmap; } /* * Extract the raw bitmap data. * */ BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat); if (data.Stride == 4 * data.Width) { /* * Copy the data from the bitmap * to the array in BGRA format. * */ byte[] raw = new byte[data.Stride * data.Height]; System.Runtime.InteropServices.Marshal.Copy(data.Scan0, raw, 0, data.Stride * data.Height); bitmap.UnlockBits(data); int width = bitmap.Width; int height = bitmap.Height; bitmap.Dispose(); /* * Change the byte order from BGRA to RGBA. * */ for (int i = 0; i < raw.Length; i += 4) { byte temp = raw[i]; raw[i] = raw[i + 2]; raw[i + 2] = temp; } texture = new Texture(width, height, 32, raw); return true; } else { /* * The stride is invalid. This indicates that the * CLI either does not implement the conversion to * 32-bit BGRA correctly, or that the CLI has * applied additional padding that we do not * support. * */ bitmap.UnlockBits(data); bitmap.Dispose(); CurrentHost.ReportProblem(ProblemType.InvalidOperation, "Invalid stride encountered."); texture = null; return false; } }
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; }
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 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; }
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 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 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 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; }
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 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; }
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> /// 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 Texture(String File) { Type = Types.TEXTURE; base.Filename = File; bmp = new Bitmap (File); glId = GL.GenTexture (); GL.BindTexture (TextureTarget.Texture2D, glId); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); BitmapData bmpd = bmp.LockBits (new Rectangle(0,0,bmp.Width,bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D (TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmpd.Width, bmpd.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmpd.Scan0); bmp.UnlockBits (bmpd); }
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 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; }
/// <summary> /// Create a new <see cref="Bitmap"/> instance using a color palette, per-pixel palette color indices and the image width and height. /// </summary> /// <param name="palette">The color palette used by the image.</param> /// <param name="indices">The per-pixel palette color indices used by 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[] palette, byte[] indices, 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 = palette[indices[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; }
public static void Save(Bitmap bmp, string filePath) { var bmpData = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb); try { using (var writer = new BinaryWriter(new FileStream(filePath, FileMode.Create, FileAccess.Write), Encoding.ASCII)) { writer.Write(Encoding.ASCII.GetBytes("PSF")); //PSF Mark writer.Write((byte)1); //version writer.Write((Int16)bmp.Width); //width writer.Write((Int16)bmp.Height); //height writer.Write((byte)0xcc); //alpha Mark var scanPointer = bmpData.Scan0; var dataBuffer = new byte[bmpData.Width * 4]; for (var y = 0; y < bmpData.Height; y++, scanPointer += bmpData.Stride) { Marshal.Copy(scanPointer, dataBuffer, 0, dataBuffer.Length); writer.Write(dataBuffer); } } } finally { bmp.UnlockBits(bmpData); } }
public PieceOfText(Font font, string text) { _font = font; Text = text; _texture = GL.GenTexture(); var measure = MeasureText(); using (var bmp = new Bitmap(MakeEven((int)Math.Ceiling(measure.Width)), MakeEven((int)Math.Ceiling(measure.Height)))) { using (var g = Graphics.FromImage(bmp)) { g.Clear(Color.Transparent); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; g.DrawString(Text, _font, Brushes.Black, new RectangleF(0, 0, measure.Width, measure.Height)); } GL.BindTexture(TextureTarget.Texture2D, _texture); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); var data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp.Width, bmp.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); GL.BindTexture(TextureTarget.Texture2D, 0); bmp.UnlockBits(data); _bmpWidth = bmp.Width; _bmpHeight = bmp.Height; } }
/// <summary> /// Most of the time it just returns a black screen, this is because the game is rendering straight to the /// graphics card using directx and bypassing whatever windows usually uses for PrintWindow /// AFAIK directx screenshots only work if the window is currently visible (not overlaid by the bot itself) /// </summary> /// <returns></returns> public Image<Bgr, byte> TakeScreenshot() { Bitmap frame = new Bitmap(1024, 768); using (Graphics g = Graphics.FromImage(frame)) { IntPtr deviceContextHandle = g.GetHdc(); PrintWindow(GetGameWindowHandle(), deviceContextHandle, 1); g.ReleaseHdc(); } //we have the bitmap now //turn it into an Image for emgu BitmapData bmpData = frame.LockBits(new Rectangle(0, 0, frame.Width, frame.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); Image<Bgr, byte> tempImage = new Image<Bgr, byte>(frame.Width, frame.Height, bmpData.Stride, bmpData.Scan0); //to prevent any corrupted memory errors that crop up for some reason Image<Bgr, byte> image = tempImage.Clone(); frame.UnlockBits(bmpData); //dispose all unused image data to prevent memory leaks frame.Dispose(); tempImage.Dispose(); image.Save("screenshot.png"); return image; }
public static Bitmap Open(string filePath) { using (var reader = new BinaryReader(new FileStream(filePath, FileMode.Open, FileAccess.Read))) { if(new string(reader.ReadChars(3)) != "PSF" || reader.ReadByte() != 1) throw new Exception(); var width = reader.ReadInt16(); var height = reader.ReadInt16(); var alphaMark = reader.ReadByte(); var bmp = new Bitmap(width, height); var bmpData = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb); try { var scanPointer = bmpData.Scan0; for (var y = 0; y < bmpData.Height; y++, scanPointer += bmpData.Stride) { var dataBuffer = reader.ReadBytes(bmpData.Width * 4); Marshal.Copy(dataBuffer, 0, scanPointer, dataBuffer.Length); } return bmp; } finally { bmp.UnlockBits(bmpData); } } }
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 Bitmap CopyDataToBitmap(int width, int height, IntPtr data, long length, PixelFormat format, int bytesPerSrcRow = 0) { Bitmap bmp = null; BitmapData bmpData = null; try { bmp = new Bitmap(width, height, format); bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); int pixelSize = Image.GetPixelFormatSize(bmp.PixelFormat) / 8; int bytesPerRow = bytesPerSrcRow == 0 ? bmp.Width * pixelSize : bytesPerSrcRow; IntPtr dataPtr = bmpData.Scan0; for (int i = 0; i < height; i++) { MemoryUtilities.MoveMemory(dataPtr, data, bytesPerRow); dataPtr = (IntPtr)((long)dataPtr + bmpData.Stride); data = (IntPtr)((long)data + bytesPerRow); } } catch (Exception ex) { throw new DjvuAggregateException(ex); } finally { bmp?.UnlockBits(bmpData); } return(bmp); }
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 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); }
public double GetDrawingFitness(DnaDrawing newDrawing) { double error = 0; using (var b = new Bitmap(newDrawing.Width, newDrawing.Height, PixelFormat.Format24bppRgb)) using (Graphics g = Graphics.FromImage(b)) { Renderer.Render(newDrawing, g, 1); BitmapData bmd1 = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); for (int y = 0; y < b.Height; y++) { for (int x = 0; x < b.Width; x++) { Color c1 = GetPixel(bmd1, x, y); Color c2 = _sourceColors[x, y]; double pixelError = GetColorFitness(c1, c2); error += pixelError; } } b.UnlockBits(bmd1); } return error; }
/// <summary> /// Fast copy of managed pixel array data into System.Drawing.Bitmap image. /// No checking of passed parameters, therefore, it is a caller responsibility /// to provid valid parameter values. /// </summary> /// <param name="width"> /// Image width <see cref="System.Int32"/> in pixels /// </param> /// <param name="height"> /// Image height <see cref="System.Int32"/> in pixels /// </param> /// <param name="data"> /// Pointer <see cref="System.IntPtr"/> to buffer with image data /// </param> /// <param name="length"> /// Length <see cref="System.Int64"/> of buffer in bytes /// </param> /// <param name="format"> /// Format of image pixel expressed with <see cref="System.Drawing.Imaging.PixelFormat"/> enumeration /// </param> /// <returns> /// <see cref="System.Drawing.Bitmap"/> created with data copied from Data buffer /// of this instance of <see cref="DjvuNet.Graphics.Map"/> /// </returns> public static System.Drawing.Bitmap CopyDataToBitmap( int width, int height, IntPtr data, long length, PixelFormat format) { System.Drawing.Bitmap bmp = null; BitmapData bmpData = null; try { bmp = new System.Drawing.Bitmap(width, height, format); bmpData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); MemoryUtilities.MoveMemory(bmpData.Scan0, data, length); } catch (Exception ex) { throw new DjvuAggregateException(ex); } finally { bmp?.UnlockBits(bmpData); } return(bmp); }
public static Texture2D TextureFromBitmap(Bitmap image) { BitmapData data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, image.PixelFormat); int bytes = data.Stride*image.Height; DataStream stream = new DataStream(bytes, true, true); stream.WriteRange(data.Scan0, bytes); stream.Position = 0; DataRectangle dRect = new DataRectangle(data.Stride, stream); Texture2DDescription texDesc = new Texture2DDescription { ArraySize = 1, MipLevels = 1, SampleDescription = new SampleDescription(1, 0), Format = Format.B8G8R8A8_UNorm, CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.ShaderResource, Usage = ResourceUsage.Immutable, Height = image.Height, Width = image.Width }; image.UnlockBits(data); image.Dispose(); Texture2D texture = new Texture2D(Game.Context.Device, texDesc, dRect); stream.Dispose(); return texture; }
/// <summary> /// Function to convert a WIC bitmap to a System.Drawing.Image /// </summary> /// <param name="bitmap">Bitmap to convert.</param> /// <param name="format">Pixel format to use.</param> /// <returns>The converted bitmap.</returns> public Image CreateGDIImageFromWICBitmap(WIC.Bitmap bitmap, PixelFormat format) { Bitmap result = null; BitmapData lockData = null; Guid conversionFormat = GetGUID(format); if (conversionFormat == Guid.Empty) { throw new GorgonException(GorgonResult.FormatNotSupported, string.Format(Resources.GORGFX_FORMAT_NOT_SUPPORTED, format)); } try { // Create the new bitmap. result = new Bitmap(bitmap.Size.Width, bitmap.Size.Height, format); lockData = result.LockBits(new Rectangle(0, 0, bitmap.Size.Width, bitmap.Size.Height), ImageLockMode.WriteOnly, format); // We need to convert, so copy using the format converter. if (bitmap.PixelFormat != conversionFormat) { using (var converter = new WIC.FormatConverter(Factory)) { converter.Initialize(bitmap, conversionFormat, WIC.BitmapDitherType.None, null, 0, WIC.BitmapPaletteType.Custom); converter.CopyPixels(lockData.Stride, lockData.Scan0, lockData.Stride * lockData.Height); } } else { // Otherwise, copy it all in one shot. bitmap.CopyPixels(lockData.Stride, lockData.Scan0, lockData.Stride * lockData.Height); } return(result); } finally { if (lockData != null) { result.UnlockBits(lockData); } } }
private static void FromSystemBitmap(System.Drawing.Bitmap src, Bitmap dst) { var bitmapData = src.LockBits( new Rectangle(0, 0, src.Width, src.Height), ImageLockMode.ReadOnly, src.PixelFormat ); for (var i = 0; i < src.Height; i++) { unsafe { Buffer.MemoryCopy((bitmapData.Scan0 + i * bitmapData.Stride).ToPointer(), (dst.Scan0 + i * dst.Stride).ToPointer(), dst.Stride, (dst.Channel * dst.Depth * dst.Width) >> 3); } } src.UnlockBits(bitmapData); }
private void ClearImage_Paint(object sender, PaintEventArgs e) { System.Drawing.Imaging.BitmapData bitmapData = _Bitmap.LockBits(new Rectangle(0, 0, _Bitmap.Width, _Bitmap.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); _Queue.Submit(new VkSubmitInfo[] { new VkSubmitInfo() { commandBuffers = new VkCommandBuffer[] { _CommandBuffer } } }, _Fence); if (_Fence.WaitForFence(1000)) { // If the submission completed we copy the image data into the bitmap data Copy(bitmapData.Scan0, _ImagePtr, (int)_Image.MemoryRequirements.size); } _Bitmap.UnlockBits(bitmapData); e.Graphics.DrawImage(_Bitmap, new Rectangle(0, 0, Width, Height)); }
public static System.Drawing.Bitmap GetBitmap(this DesignPattern pattern) { int width = pattern.Width; int height = pattern.Height; var bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); var data = bitmap.LockBits(new Rectangle(Point.Empty, bitmap.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); var pixelSize = data.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb ? 4 : 3; var padding = data.Stride - (data.Width * pixelSize); unsafe { byte *ptr = (byte *)data.Scan0.ToPointer(); var index = 0; for (var y = 0; y < data.Height; y++) { for (var x = 0; x < data.Width; x++) { var b = pattern.GetPixel(x, y); if (b == 15) { *(ptr + index + 2) = 0; *(ptr + index + 1) = 0; *(ptr + index + 0) = 0; *(ptr + index + 3) = 0; } else { var c = pattern.Palette[b]; *(ptr + index + 2) = c.R; *(ptr + index + 1) = c.G; *(ptr + index + 0) = c.B; *(ptr + index + 3) = 255; } index += pixelSize; } index += padding; } } bitmap.UnlockBits(data); return(bitmap); }
public static SD.Bitmap AsBitmap(object backend) { var bmp = backend as SD.Bitmap; if (bmp == null) { var bs = backend as SWM.Imaging.BitmapSource; if (bs != null) { bmp = new SD.Bitmap(bs.PixelWidth, bs.PixelHeight, bs.Format.ToPixelFormat()); SDI.BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), SDI.ImageLockMode.WriteOnly, bmp.PixelFormat); bs.CopyPixels(new Int32Rect(0, 0, bmp.Width, bmp.Height), data.Scan0, data.Height * data.Stride, data.Stride); bmp.UnlockBits(data); } } return(bmp); }
public System.Drawing.Bitmap ImageSourceToBitmap(ImageSource imageSource) { BitmapSource m = (BitmapSource)imageSource; if (m == null) { return(null); } System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // 坑点:选Format32bppRgb将不带透明度 System.Drawing.Imaging.BitmapData data = bmp.LockBits( new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bmp.UnlockBits(data); return(bmp); }
private static System.Drawing.Bitmap ConvertToBitmap(WICBitmap wicBitmap) { var width = wicBitmap.Size.Width; var height = wicBitmap.Size.Height; var gdiBitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); var gdiBitmapData = gdiBitmap.LockBits( new System.Drawing.Rectangle(0, 0, gdiBitmap.Width, gdiBitmap.Height), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); var buffer = new int[width * height]; wicBitmap.CopyPixels(buffer); Marshal.Copy(buffer, 0, gdiBitmapData.Scan0, buffer.Length); gdiBitmap.UnlockBits(gdiBitmapData); return(gdiBitmap); }
/// <summary> /// 二値白黒画像を取得します。1 bit が 1 pixel に対応します。 /// 高位を先に読み取り、低位を後に読み取ります。 /// 行がバイトの途中で終わった場合、次の行は新しいバイトから始まります。 /// </summary> /// <param name="width">画像の幅を指定します。</param> /// <param name="height">画像の高さを指定します。</param> /// <param name="imageData">画像のデータが格納されている配列の先頭を指定します。 /// (width+7)/8*height 以上の長さの配列である必要があります。</param> /// <returns>生成した画像を System.Drawing.Bitmap として返します。</returns> public static unsafe System.Drawing.Bitmap GetByteAlignedImage(int width, int height, byte *imageData) { Bitmap bmp = new System.Drawing.Bitmap(width, height, PixelFormat.Format1bppIndexed); BitmapData data = bmp.LockBits( new Rectangle(0, 0, width, height) , ImageLockMode.WriteOnly , PixelFormat.Format1bppIndexed); byte *px = (byte *)data.Scan0; byte *pxM = px + ((width + 7) >> 3) * height * 4; int i = 0; while (px < pxM) { *px = imageData[i++]; px += 4; } bmp.UnlockBits(data); return(bmp); }
public static void Bitmap2Pixels(System.Drawing.Bitmap bm, byte[] b) { //direct bit manipulation System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bm.Width, bm.Height); //lock the bits System.Drawing.Imaging.BitmapData bmpData = bm.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bm.PixelFormat); IntPtr ptr = bmpData.Scan0; int bytes = b.Length; Marshal.Copy(ptr, b, 0, bytes); // Unlock the bits. bm.UnlockBits(bmpData); bmpData = null; }
/// <summary> /// Arithmetic Blend /// </summary> /// <param name="sourceBitmap">Set source Bitmap</param> /// <param name="blendBitmap">Set blend Bitmap</param> /// <param name="calculationType">Set calculation type</param> /// <returns></returns> public static System.Drawing.Bitmap ArithmeticBlend(this System.Drawing.Bitmap sourceBitmap, System.Drawing.Bitmap blendBitmap, ColorCalculator.ColorCalculationType calculationType) { BitmapData sourceData = sourceBitmap.LockBits(new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); byte[] pixelBuffer = new byte[sourceData.Stride * sourceData.Height]; Marshal.Copy(sourceData.Scan0, pixelBuffer, 0, pixelBuffer.Length); sourceBitmap.UnlockBits(sourceData); BitmapData blendData = blendBitmap.LockBits(new Rectangle(0, 0, blendBitmap.Width, blendBitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); byte[] blendBuffer = new byte[blendData.Stride * blendData.Height]; Marshal.Copy(blendData.Scan0, blendBuffer, 0, blendBuffer.Length); blendBitmap.UnlockBits(blendData); for (int k = 0; (k + 4 < pixelBuffer.Length) && (k + 4 < blendBuffer.Length); k += 4) { pixelBuffer[k] = ColorCalculator.Calculate(pixelBuffer[k], blendBuffer[k], calculationType); pixelBuffer[k + 1] = ColorCalculator.Calculate(pixelBuffer[k + 1], blendBuffer[k + 1], calculationType); pixelBuffer[k + 2] = ColorCalculator.Calculate(pixelBuffer[k + 2], blendBuffer[k + 2], calculationType); } System.Drawing.Bitmap resultBitmap = new System.Drawing.Bitmap(sourceBitmap.Width, sourceBitmap.Height); BitmapData resultData = resultBitmap.LockBits(new Rectangle(0, 0, resultBitmap.Width, resultBitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); Marshal.Copy(pixelBuffer, 0, resultData.Scan0, pixelBuffer.Length); resultBitmap.UnlockBits(resultData); return(resultBitmap); }
private void image_MouseDown(object sender, MouseButtonEventArgs e) { Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog(); ofd.DefaultExt = ".*"; ofd.Filter = "二维码图像|*.*"; if (ofd.ShowDialog() == true) { image.Stretch = Stretch.Uniform; image.Source = new BitmapImage(new Uri(ofd.FileName, UriKind.Absolute)); BarcodeReader reader = new BarcodeReader(); BitmapSource m = new BitmapImage(new Uri(ofd.FileName, UriKind.Absolute)); System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(m.PixelWidth, m.PixelHeight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); System.Drawing.Imaging.BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(System.Drawing.Point.Empty, bmp.Size), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); m.CopyPixels(Int32Rect.Empty, data.Scan0, data.Height * data.Stride, data.Stride); bmp.UnlockBits(data); Result result = reader.Decode(bmp); textBox.Text = "识别的文本:" + result.ToString(); } }
/// <summary> /// Gets a System.Drawing.Bitmap from a BitmapSource. /// </summary> /// <param name="source">The source image from which to create our Bitmap.</param> /// <param name="transparencyKey">The transparency key. This is used by the DragDropHelper /// in rendering transparent pixels.</param> /// <returns>An instance of Bitmap which is a copy of the BitmapSource's image.</returns> protected Drawing.Bitmap GetBitmapFromBitmapSource(BitmapSource source, Color transparencyKey) { // Copy at full size Int32Rect sourceRect = new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight); // Convert to our destination pixel format Imaging.PixelFormat pxFormat = ConvertPixelFormat(source.Format); // Create the Bitmap, full size, full rez Drawing.Bitmap bmp = new Drawing.Bitmap(sourceRect.Width, sourceRect.Height, pxFormat); // If the format is an indexed format, copy the color palette if ((pxFormat & Imaging.PixelFormat.Indexed) == Imaging.PixelFormat.Indexed) { ConvertColorPalette(bmp.Palette, source.Palette); } // Get the transparency key as a System.Drawing.Color Drawing.Color transKey = ToDrawingColor(transparencyKey); // Lock our Bitmap bits, we need to write to it Imaging.BitmapData bmpData = bmp.LockBits( ToDrawingRectangle(sourceRect), Imaging.ImageLockMode.ReadWrite, pxFormat); { // Copy the source bitmap data to our new Bitmap source.CopyPixels(sourceRect, bmpData.Scan0, bmpData.Stride * sourceRect.Height, bmpData.Stride); // The drag image seems to work in full 32-bit color, except when // alpha equals zero. Then it renders those pixels at black. So // we make a pass and set all those pixels to the transparency key // color. This is only implemented for 32-bit pixel colors for now. if ((pxFormat & Imaging.PixelFormat.Alpha) == Imaging.PixelFormat.Alpha) { ReplaceTransparentPixelsWithTransparentKey(bmpData, transKey); } } // Done, unlock the bits bmp.UnlockBits(bmpData); return(bmp); }
private void LoadFromBitmap(Drawing.Bitmap sourceImage) { mSourceRect.Size = Interop.Convert(sourceImage.Size); Size newSize = GetOGLSize(sourceImage); // create a new bitmap of the size OpenGL expects, and copy the source image to it. Drawing.Bitmap textureImage = new Drawing.Bitmap(newSize.Width, newSize.Height); Drawing.Graphics g = Drawing.Graphics.FromImage(textureImage); g.Transform = new System.Drawing.Drawing2D.Matrix(); g.Clear(Drawing.Color.FromArgb(0, 0, 0, 0)); g.DrawImage(sourceImage, new Drawing.Rectangle(new Drawing.Point(0, 0), sourceImage.Size)); g.Dispose(); mTextureSize = Interop.Convert(textureImage.Size); mTexCoord = GetTextureCoords(mSourceRect); // Rectangle For Locking The Bitmap In Memory Rectangle rectangle = new Rectangle(0, 0, textureImage.Width, textureImage.Height); // Get The Bitmap's Pixel Data From The Locked Bitmap BitmapData bitmapData = textureImage.LockBits(Interop.Convert(rectangle), ImageLockMode.ReadOnly, Drawing.Imaging.PixelFormat.Format32bppArgb); // use a pixelbuffer to do format conversion. PixelBuffer buffer = new PixelBuffer(PixelFormat.RGBA8888, mTextureSize, bitmapData.Scan0, PixelFormat.BGRA8888, bitmapData.Stride); // Create The GL Texture object int textureID; GL.GenTextures(1, out textureID); AddTextureRef(textureID); WritePixels(buffer); textureImage.UnlockBits(bitmapData); // Unlock The Pixel Data From Memory textureImage.Dispose(); // Dispose The Bitmap }
public static System.Drawing.Bitmap CreateAlphaBitmap(System.Drawing.Bitmap srcBitmap, PixelFormat targetPixelFormat) { var result = new System.Drawing.Bitmap(srcBitmap.Width, srcBitmap.Height, targetPixelFormat); Rectangle bmpBounds = new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height); BitmapData srcData = srcBitmap.LockBits(bmpBounds, ImageLockMode.ReadOnly, srcBitmap.PixelFormat); bool isAlplaBitmap = false; try { for (int y = 0; y <= srcData.Height - 1; y++) { for (int x = 0; x <= srcData.Width - 1; x++) { Color pixelColor = Color.FromArgb( Marshal.ReadInt32(srcData.Scan0, (srcData.Stride * y) + (4 * x))); if (pixelColor.A > 0 & pixelColor.A < 255) { isAlplaBitmap = true; } result.SetPixel(x, y, pixelColor); } } } finally { srcBitmap.UnlockBits(srcData); } if (isAlplaBitmap) { return(result); } else { return(srcBitmap); } }
public void Draw(String str) { using (Graphics gfx = Graphics.FromImage(TextureBitmap)) { gfx.Clear(Color.Transparent); gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; gfx.DrawString(str, TextFont, Brushes.White, new PointF(0, 0)); } System.Drawing.Imaging.BitmapData data = TextureBitmap.LockBits(new Rectangle(0, 0, TextureBitmap.Width, TextureBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, TextureBitmap.Width, TextureBitmap.Height, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); TextureBitmap.UnlockBits(data); GL.MatrixMode(MatrixMode.Projection); GL.PushMatrix(); GL.LoadIdentity(); GL.Ortho(0, rect.Width, 0, rect.Height, -1, 1); GL.MatrixMode(MatrixMode.Modelview); GL.PushMatrix(); GL.LoadIdentity(); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.One); GL.Disable(EnableCap.DepthTest); GL.DepthMask(false); GL.Disable(EnableCap.CullFace); GL.BindVertexArray(vao); GL.BindBuffer(BufferTarget.ArrayBuffer, vbo); GL.BindBuffer(BufferTarget.ElementArrayBuffer, ebo); GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, texture); GL.UseProgram(ShaderProgram); GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvParameter.CombineAlpha); GL.DrawElements(BeginMode.Triangles, 6, DrawElementsType.UnsignedInt, 0); GL.MatrixMode(MatrixMode.Projection); GL.PopMatrix(); GL.MatrixMode(MatrixMode.Modelview); GL.PopMatrix(); }
/// <summary> /// Adjusts the color. /// </summary> /// <param name="bmp">The BMP.</param> /// <param name="format">The format.</param> /// <param name="PalleteAdjust">The pallete adjust.</param> /// <param name="ConvertScanLine">The convert scan line.</param> public void AdjustColor(ref System.Drawing.Bitmap bmp, PixelFormat format, PaletteAdjustEvent PalleteAdjust, ConvertScanLineEvent ConvertScanLine) { Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Bitmap bmpOut = new System.Drawing.Bitmap(bmp.Width, bmp.Height, format); bmpOut.Palette = PalleteAdjust(bmpOut.Palette); PixelFormat srcFmt = bmp.PixelFormat; PixelFormat dstFmt = bmpOut.PixelFormat; int srcPixBit = GetPixelSize(srcFmt); int dstPixBit = GetPixelSize(dstFmt); BitmapData srcData = null; BitmapData dstData = null; try { srcData = bmp.LockBits(rect, ImageLockMode.ReadOnly, srcFmt); dstData = bmpOut.LockBits(rect, ImageLockMode.WriteOnly, dstFmt); unsafe { byte *srcLine = (byte *)srcData.Scan0.ToPointer(); byte *dstLine = (byte *)dstData.Scan0.ToPointer(); for (int L = 0; L < srcData.Height; L++) { ConvertScanLine((IntPtr)srcLine, (IntPtr)dstLine, srcData.Width, srcPixBit, dstPixBit, bmp, bmpOut); srcLine += srcData.Stride; dstLine += dstData.Stride; } } } finally { bmp.UnlockBits(srcData); bmpOut.UnlockBits(dstData); } bmp = bmpOut; }
public void UpdateText() { if (_lines.Count > 0) { using (drw.Graphics gfx = drw.Graphics.FromImage(TextBitmap)) { gfx.Clear(drw.Color.Black); gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; for (int i = 0; i < _lines.Count; i++) { gfx.DrawString(_lines[i], TextFont, _colours[i], _positions[i]); } } System.Drawing.Imaging.BitmapData data = TextBitmap.LockBits(new drw.Rectangle(0, 0, TextBitmap.Width, TextBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, TextBitmap.Width, TextBitmap.Height, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); TextBitmap.UnlockBits(data); } }
public static BitmapSource ConvertToBitmapSource(System.Drawing.Bitmap bitmap) { if (bitmap == null) { return(null); } var bitmapData = bitmap.LockBits( new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat); var bitmapSource = BitmapSource.Create( bitmapData.Width, bitmapData.Height, bitmap.HorizontalResolution, bitmap.VerticalResolution, PixelFormats.Bgr24, null, bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride); bitmap.UnlockBits(bitmapData); return(bitmapSource); }
public System.Drawing.Bitmap getImageFromDataBox(DataBox mapSource) { var image = new System.Drawing.Bitmap(mOutputDesc.DesktopBounds.Width, mOutputDesc.DesktopBounds.Height, PixelFormat.Format32bppRgb); var boundsRect = new System.Drawing.Rectangle(0, 0, mOutputDesc.DesktopBounds.Width, mOutputDesc.DesktopBounds.Height); var sourcePtr = mapSource.DataPointer; var mapDest = image.LockBits(boundsRect, ImageLockMode.WriteOnly, image.PixelFormat); var destPtr = mapDest.Scan0; // Test 1 unsafe { Utilities.CopyMemory(destPtr, sourcePtr, mOutputDesc.DesktopBounds.Width * mOutputDesc.DesktopBounds.Height * 4); } image.UnlockBits(mapDest); return(image); }
public static void glNitroTexImage2D(System.Drawing.Bitmap b, HBDF.MDLFBlock.TextureBlock m, int Nr) { Gl.glBindTexture(3553, Nr); Gl.glColor3f(1f, 1f, 1f); BitmapData bitmapdata = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Gl.glTexImage2D(3553, 0, 32856, b.Width, b.Height, 0, 32993, 5121, bitmapdata.Scan0); b.UnlockBits(bitmapdata); Gl.glTexParameteri(3553, 10241, 9728); Gl.glTexParameteri(3553, 10240, 9728); bool flag1 = ((int)(m.texImageParam >> 16) & 1) == 1; bool flag2 = ((int)(m.texImageParam >> 17) & 1) == 1; bool flag3 = ((int)(m.texImageParam >> 18) & 1) == 1; bool flag4 = ((int)(m.texImageParam >> 19) & 1) == 1; int num1 = !flag1 || !flag3 ? (!flag1 ? 10496 : 10497) : 33648; int num2 = !flag2 || !flag4 ? (!flag2 ? 10496 : 10497) : 33648; Gl.glTexParameterf(3553, 10242, (float)num1); Gl.glTexParameterf(3553, 10243, (float)num2); }
/// <summary> /// 指定した Bitmap の色を反転します。 /// </summary> /// <param name="source">反転前の画像を指定します。</param> /// <returns>反転後の画像を指定します。</returns> public static System.Drawing.Bitmap Invert(System.Drawing.Bitmap source) { System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)source.Clone(); System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height); Imaging.BitmapData data = bmp.LockBits(rect, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format32bppArgb); System.IntPtr scan0 = data.Scan0; int M = bmp.Width * bmp.Height; unsafe { Color32Argb *p = (Color32Argb *)(void *)scan0; Color32Argb *pM = p + M; while (p < pM) { *p = ~*p; p++; } } bmp.UnlockBits(data); return(bmp); }
/// <summary> /// /// </summary> /// <param name="width"></param> /// <param name="height"></param> /// <param name="data"></param> /// <returns></returns> public static System.Drawing.Bitmap CopyDataToBitmap(int width, int height, byte[] data, PixelFormat format) { //Here create the Bitmap to the know height, width and format //PixelFormat.Format24bppRgb System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height, format); //Create a BitmapData and Lock all pixels to be written BitmapData bmpData = bmp.LockBits( new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); //Copy the data from the byte array into BitmapData.Scan0 Marshal.Copy(data, 0, bmpData.Scan0, data.Length); //Unlock the pixels bmp.UnlockBits(bmpData); //Return the bitmap return(bmp); }
public static void WriteAsSpanBitmap(GDIBITMAP bmp, SpanBitmap.Action1 action) { var rect = new Rectangle(0, 0, bmp.Width, bmp.Height); GDIPTR dstBits = null; try { dstBits = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat); action(dstBits.AsSpanBitmapDangerous()); } finally { if (dstBits != null) { bmp.UnlockBits(dstBits); } } }
private void CreateBitmap() { BitmapData bitmapData = orgBitmap.LockBits(new Rectangle(0, 0, orgBitmap.Width, orgBitmap.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); using (DataStream dataStream = new DataStream(bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, true, false)) { PixelFormat format = new PixelFormat(Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied); BitmapProperties properties = new BitmapProperties(); properties.HorizontalDpi = properties.VerticalDpi = 96; properties.PixelFormat = format; if (SpriteBitmap != null && !SpriteBitmap.Disposed) { SpriteBitmap.Dispose(); } SpriteBitmap = new SlimDX.Direct2D.Bitmap(batch.DWRenderTarget, new Size(orgBitmap.Width, orgBitmap.Height), dataStream, bitmapData.Stride, properties); orgBitmap.UnlockBits(bitmapData); } }
private static System.Drawing.Bitmap ChangePixelFormat(System.Drawing.Bitmap bmp) { System.Drawing.Bitmap ret = new System.Drawing.Bitmap(bmp.Width, bmp.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height); Imaging.BitmapData bmpdat = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Imaging.BitmapData retdat = ret.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); unsafe { int *src = (int *)bmpdat.Scan0; int *dst = (int *)retdat.Scan0; int *srcM = src + bmp.Width * bmp.Height; while (src < srcM) { *dst++ = *src++; } } ret.UnlockBits(retdat); bmp.UnlockBits(bmpdat); return(ret); }
internal void GiveFrame(DepthImageFrame depthFrame, PointCluster floodFill) { short[] imagePixelData = new short[depthFrame.PixelDataLength]; depthFrame.CopyPixelDataTo(imagePixelData); float RenderWidth = 640.0f; float RenderHeight = 480.0f; Bitmap bmap = new System.Drawing.Bitmap(depthFrame.Width, depthFrame.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); System.Drawing.Imaging.BitmapData bmapdata = bmap.LockBits(new System.Drawing.Rectangle(0, 0, depthFrame.Width , depthFrame.Height), ImageLockMode.WriteOnly, bmap.PixelFormat); IntPtr ptr = bmapdata.Scan0; System.Runtime.InteropServices.Marshal.Copy(imagePixelData, 0, ptr, depthFrame.Width * depthFrame.Height); bmap.UnlockBits(bmapdata); /*System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmap); * this.myImageBox.Source = * System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( * bmap.GetHbitmap(), * IntPtr.Zero, * System.Windows.Int32Rect.Empty, * BitmapSizeOptions.FromWidthAndHeight((int)this.myImageBox.Width, (int)this.myImageBox.Height));*/ using (DrawingContext lfdc = drawingGroup.Open())//this.liveFeedbackGroup.Open()) { lfdc.DrawImage(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmap.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight((int)RenderWidth, (int)RenderHeight)), //BitmapSizeOptions.FromWidthAndHeight((int)this.myImageBox.ActualWidth, (int)this.myImageBox.ActualHeight)), new Rect(0.0, 0.0, RenderWidth, RenderHeight)); foreach (DepthPoint point in floodFill.points) { lfdc.DrawRoundedRectangle(System.Windows.Media.Brushes.Red, null, new Rect(point.x, point.y, 3, 3), null, 1, null, 1, null); } } }
private void timer6_Tick(object sender, EventArgs e) // Timer 6 to jest szykanie obrazka i klikniecie jesli znajdzie { timer2.Stop(); timer6.Stop(); richTextBox1.Text += "!!! Szukam: z" + znajdz + ".jpg w " + js + ".jpg /n"; System.Drawing.Bitmap template = (Bitmap)pictureBox3.Image; System.Drawing.Bitmap sourceImage = (Bitmap)pictureBox2.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); richTextBox1.Text += "Znalazlem: z" + znajdz + ".jpg w " + js + ".jpg /n"; //MessageBox.Show(m.Rectangle.Location.ToString()); lokalizacja = m.Rectangle.Location; richTextBox1.Text += "lok: " + lokalizacja.ToString() + "\n"; // do something else with matching } sourceImage.UnlockBits(data); if (lokalizacja != null) // jesli znalazło to kliknij { timer5.Start(); // co 5 sekund klik w znaleziona pozycje richTextBox1.Text += "klikam: " + lokalizacja.ToString() + "\n"; } richTextBox1.Text += "Kontrona znajdz: " + znajdz + " ## "; richTextBox1.Text += "Kontrona zrzut ekranu: " + js + " ## /n"; timer7.Start(); // To jest zrzut ekranu i załadowanie obrazkow do boksów }
public override bool WriteCoinToQRCode(CloudCoin cloudCoin, string OutputFile, string tag) { var width = 250; // width of the Qr Code var height = 250; // height of the Qr Code var margin = 0; var qrCodeWriter = new ZXing.BarcodeWriterPixelData { Format = ZXing.BarcodeFormat.QR_CODE, Options = new QrCodeEncodingOptions { Height = height, Width = width, Margin = margin } }; string coinJson = JsonConvert.SerializeObject(cloudCoin); var pixelData = qrCodeWriter.Write(coinJson); // 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); } // save to stream as PNG bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); bitmap.Save(OutputFile); } return(true); }
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; }