public DisplacementMapFilter(BitmapData mapBitmap, Point mapPoint) { }
/// <summary> /// This method for loading/saving a font file generated from MakeSpriteFont. /// </summary> /// <param name="serializer">The binary serializer to use.</param> /// <returns></returns> private void SerializeMakeSpriteFont(BinarySerializer serializer) { FourCC magicCode2 = "font"; serializer.Serialize(ref magicCode2); if (magicCode2 != "font") return; // Writes the version if (serializer.Mode == SerializerMode.Read) { int version = serializer.Reader.ReadInt32(); if (version != Version) { throw new NotSupportedException(string.Format("SpriteFontData version [0x{0:X}] is not supported. Expecting [0x{1:X}]", version, Version)); } } else { serializer.Writer.Write(Version); } // Deserialize Glyphs int glyphCount = 0; serializer.Serialize(ref glyphCount); // For MakeSpriteFont, there is only one GlyphPage. Glyphs = new Glyph[glyphCount]; for (int i = 0; i < glyphCount; i++) { serializer.Serialize(ref Glyphs[i].Character); serializer.Serialize(ref Glyphs[i].Subrect); serializer.Serialize(ref Glyphs[i].Offset); serializer.Serialize(ref Glyphs[i].XAdvance); // Fix XAdvance with Right/Left for MakeSpriteFont Glyphs[i].XAdvance += Glyphs[i].Subrect.Right - Glyphs[i].Subrect.Left; } serializer.Serialize(ref LineSpacing); serializer.Serialize(ref DefaultCharacter); var image = new BitmapData(); Bitmaps = new Bitmap[1] {new Bitmap()}; Bitmaps[0].Data = image; serializer.Serialize(ref image.Width); serializer.Serialize(ref image.Height); serializer.SerializeEnum(ref image.PixelFormat); serializer.Serialize(ref image.RowStride); serializer.Serialize(ref image.CompressedHeight); serializer.Serialize(ref image.Data, image.RowStride * image.CompressedHeight); }
public static Bitmap LoadBitmapFromFile(string filename, out BitmapData bitmapData) { Bitmap bitmap = null; Rectangle rectangle; bitmapData = null; bitmap = new System.Drawing.Bitmap(filename); bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height); bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); return bitmap; }
void IDataSerializable.Serialize(BinarySerializer serializer) { if (serializer.Mode == SerializerMode.Read) { var data = new BitmapData(); serializer.Serialize(ref data); Data = data; } else { var data = (BitmapData)Data; serializer.Serialize(ref data); } }
public static Bitmap IBitmapImageToBitmap(IBitmapImage imageBitmap) { if (imageBitmap == null) throw new ArgumentNullException(); Size size; imageBitmap.GetSize(out size); Rectangle rect = new Rectangle(0, 0, size.Width, size.Height); BitmapData lockedBitmapData = new BitmapData(); imageBitmap.LockBits(ref rect, 0U, PixelFormatID.PixelFormat16bppRGB565, out lockedBitmapData); Bitmap bitmap = new Bitmap((int)lockedBitmapData.Width, (int)lockedBitmapData.Height, PixelFormat.Format16bppRgb565); System.Drawing.Imaging.BitmapData bitmapdata = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, PixelFormat.Format16bppRgb565); ImageHelpers.CopyMemory(bitmapdata.Scan0, lockedBitmapData.Scan0, (int)(lockedBitmapData.Height * lockedBitmapData.Stride)); imageBitmap.UnlockBits(ref lockedBitmapData); bitmap.UnlockBits(bitmapdata); return bitmap; }
public H2BitmapCollection(Stream stream, int offset, int magic) { BinaryReader binReader = new BinaryReader(stream); stream.Position = offset; Type = (EType)binReader.ReadInt16(); Format = (EFormat)binReader.ReadInt16(); Usage = (EUsage)binReader.ReadInt16(); Flags = (EFlags)binReader.ReadInt16(); DetailFadeFactor = binReader.ReadSingle(); SharpenAmount = binReader.ReadSingle(); BumpHeight = binReader.ReadSingle(); SpriteBudgetSize = (ESpriteBudgetSize)binReader.ReadInt16(); SpriteBudgetCount = binReader.ReadInt16(); ColourPlateWidth = binReader.ReadInt16(); ColourPlateHeight = binReader.ReadInt16(); CompressedColourPlateDataCount = binReader.ReadInt32(); CompressedColourPlateDataPointer = binReader.ReadInt32(); ProcessedPixelDataCount = binReader.ReadInt32(); ProcessedPixelDataPointer = binReader.ReadInt32(); BlueFilterSize = binReader.ReadSingle(); AlphaBias = binReader.ReadSingle(); MipmapCount = binReader.ReadInt16(); SpriteUsage = (ESpriteUsage)binReader.ReadInt16(); SpriteSpacing = binReader.ReadInt16(); ForceFormat = binReader.ReadInt16(); int sequenceCount = binReader.ReadInt32(); int sequencePointer = binReader.ReadInt32(); int bitmapCount = binReader.ReadInt32(); int bitmapPointer = binReader.ReadInt32(); Sequences = new Sequence[sequenceCount]; for (int i = 0; i < sequenceCount; i++) Sequences[i] = new Sequence(stream, (sequencePointer - magic) + (i * Sequence.SizeOf), magic); Bitmaps = new BitmapData[bitmapCount]; for (int i = 0; i < bitmapCount; i++) Bitmaps[i] = new BitmapData(stream, (bitmapPointer - magic) + (i * BitmapData.SizeOf)); }
/// <summary> /// 匹配 /// </summary> public void Match() { if (bmpList == null || bmpList.Count <= 1) return; Rectangle rect = new Rectangle(new Point(),bmpList[0].Size); for (int k = 0; k < bmpList.Count - 1;k++ ) { Bitmap b1 = bmpList[k], b2 = bmpList[k + 1]; BitmapData bdata1 = new BitmapData(), bdata2 = new BitmapData(); b1.LockBits(rect, ImageLockMode.ReadOnly, b1.PixelFormat); b2.LockBits(rect, ImageLockMode.ReadOnly, b2.PixelFormat); IntPtr bp1 = bdata1.Scan0, bp2 = bdata2.Scan0; int bytes = bdata1.Stride * bdata1.Height; byte[] b1bytes=new byte[bytes],b2bytes=new byte[bytes]; Marshal.Copy(bp1, b1bytes, 0, bytes); Marshal.Copy(bp2, b2bytes, 0, bytes); b1.UnlockBits(bdata1); b2.UnlockBits(bdata2); } }
/// <summary> /// This method for loading/saving a font file generated from MakeSpriteFont. /// </summary> /// <param name="serializer">The binaryserializer to use.</param> /// <returns></returns> private void SerializeMakeSpriteFont(BinarySerializer serializer) { FourCC magicCode2 = "font"; serializer.Serialize(ref magicCode2); if (magicCode2 != "font") return; // Deserialize Glyphs int glyphCount = 0; serializer.Serialize(ref glyphCount); // For MakeSpriteFont, there is only one GlyphPage. Glyphs = new Glyph[glyphCount]; for (int i = 0; i < glyphCount; i++) { serializer.Serialize(ref Glyphs[i].Character); serializer.Serialize(ref Glyphs[i].Subrect); serializer.Serialize(ref Glyphs[i].Offset); serializer.Serialize(ref Glyphs[i].XAdvance); // Fix XAdvance with Right/Left for MakeSpriteFont Glyphs[i].XAdvance += Glyphs[i].Subrect.Right - Glyphs[i].Subrect.Left; } serializer.Serialize(ref LineSpacing); serializer.Serialize(ref DefaultCharacter); var image = new BitmapData(); Bitmaps = new Bitmap[1] {new Bitmap()}; Bitmaps[0].Data = image; serializer.Serialize(ref image.Width); serializer.Serialize(ref image.Height); serializer.SerializeEnum(ref image.PixelFormat); serializer.Serialize(ref image.RowStride); serializer.Serialize(ref image.CompressedHeight); serializer.Serialize(ref image.Data, image.RowStride * image.CompressedHeight); }
public void Lock() { if (this.locked) throw new Exception("Bitmap already locked."); Rectangle rect = new Rectangle(0, 0, this.Width, this.Height); this.bmpData = this.Bitmap.LockBits(rect, ImageLockMode.ReadWrite, this.Bitmap.PixelFormat); this.bmpPtr = this.bmpData.Scan0; if (this.IsAlphaBitmap) { int bytes = (this.Width * this.Height) * 4; this.rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(this.bmpPtr, rgbValues, 0, this.rgbValues.Length); } else { int bytes = (this.Width * this.Height) * 3; this.rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(this.bmpPtr, rgbValues, 0, this.rgbValues.Length); } this.locked = true; }
protected unsafe override string Process(Bitmap bitmap) { BitmapData bitmapData = null; string ret = null; try { // 二値化 bitmap.ToThresholding(); bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); int bpp = 3; int stride = bitmapData.Stride; byte *startPtr = (byte *)bitmapData.Scan0; // y=0の列 byte *endPtr = startPtr + bitmapData.Width * bpp; int skipPixel = 0; // 解析アルゴリズムはDetailScoreと同一(フォント・文字サイズが同じため) for (byte *ptr = startPtr; ptr < endPtr; ptr += bpp) { // 白でなければ次のピクセル if (ToColor(ptr) != White) { continue; } var r1c = ToColor(ptr + 1 * bpp); // 1px横のピクセルの色 var r2c = ToColor(ptr + 2 * bpp); // 2px横のピクセルの色 var r3c = ToColor(ptr + 3 * bpp); // 3px横のピクセルの色 if (r1c != White) { // Group:1px // (-1, +2)pxの色をチェック if (ToColor(ptr + stride * 2 - 1 * bpp) == White) { ret += "4"; } else { ret += "1"; } skipPixel = 0; } else if (r1c == White && r2c != White) { // Group:2px // 指定のピクセルの色をチェック var c1 = ToColor(ptr + stride * 3 - 1 * bpp); // (-1, +3)px var c2 = ToColor(ptr + stride * 4 - 1 * bpp); // (-1, +4)px var c3 = ToColor(ptr + stride * 5 - 1 * bpp); // (-1, +5)px var c4 = ToColor(ptr + stride * 4 - 0 * bpp); // ( 0, +4)px if (c1 == White && c2 == White && c3 == White && c4 == White) // true, true, true, true :6 { ret += "6"; } else if (c1 == White && c2 == White && c3 == White && c4 != White) // true, true, true, false:0 { ret += "0"; } else if (c1 == White && c2 != White && c3 == White && c4 == White) // true, false, true, true :8 { ret += "8"; } else if (c1 == White && c2 != White && c3 != White && c4 == White) // true, false, false, true :9 { ret += "9"; } else if (c1 != White && c2 != White && c3 != White && c4 != White) // false, false, false, false:2 { ret += "2"; } else if (c1 != White && c2 != White && c3 != White && c4 == White) // false, false, false, true :3 { ret += "3"; } skipPixel = 1; } else if (r1c == White && r2c == White && r3c == White) { // Group:4px // (0, +1)pxの色をチェック if (ToColor(ptr + stride * 1 - 0 * bpp) == White) { ret += "5"; } else { ret += "7"; } skipPixel = 3; } // 同じ数字の部分は走査をスキップさせる ptr += skipPixel * bpp; } } finally { try { if (bitmapData != null) { bitmap.UnlockBits(bitmapData); bitmapData = null; } } catch { } } if (!string.IsNullOrEmpty(ret)) { // retには数字のみ入っているため、経過時間に変換する var min = ret.Substring(0, ret.Length - 2); var sec = ret.Substring(ret.Length - 2, 2); ret = $"00:{min}:{sec}"; } return(ret); }
public List<uint> siteColors(BitmapData referenceImage = null) { return _sites.siteColors(referenceImage); }
/// <summary> /// Initializes the roto zoomer. /// </summary> private void InitRotoZoomer(string filename) { _fpsTimer.Enabled = false; _animTimer.Enabled = false; CreateCanvas(); // load bitmap specified by the user. Bitmap srcImage = new Bitmap(filename); _imageWidth = srcImage.Width; _imageHeight = srcImage.Height; _imageInfoString = filename; _imageSizeString = string.Format("Image: {0} x {1}", _imageWidth, _imageHeight); // initialize our parameters. _zoomCounter = 0; _zoomIn = false; // deltaGamma value, controls rotation. _deltaGamma = 2.0; // deltas for x and y zooming. If they're not the same the image gets stretched. _xZoomDelta = 2.0; _yZoomDelta = 1.0; // zoom counter values when the zoom action (in/out) will swap. Give this different values for wicked results. _zoomInMax = 200; _zoomOutMax = 300; if ((_imageWidth == 0) || (_imageHeight == 0)) { throw new ApplicationException("The image you selected has a width and/or height of 0 and isn't usable"); } double imageWidthD = (double)_imageWidth; double imageHeightD = (double)_imageHeight; _sourcePixels = new uint[_imageWidth * _imageHeight]; if (_xZoomDelta != 0) { _zoomInMax = (int)(((imageWidthD / 2.0) / _xZoomDelta) - 10.0); } _zoomOutMax = _zoomInMax * 5; _yZoomDelta = (imageHeightD / imageWidthD) * _xZoomDelta; // read the initial pixels into the srcpixel array. This makes it possible to perform an in-place rendering to avoid memory trashing BitmapData srcData = srcImage.LockBits(new Rectangle(0, 0, _imageWidth, _imageHeight), ImageLockMode.ReadWrite, srcImage.PixelFormat); unsafe { switch (srcImage.PixelFormat) { case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppRgb: uint *pSrc32bpp = (uint *)srcData.Scan0; for (int i = 0; i < _imageHeight; i++) { for (int j = 0; j < _imageWidth; j++) { _sourcePixels[(i * _imageWidth) + j] = pSrc32bpp[(i * _imageWidth) + j]; } } srcImage.UnlockBits(srcData); break; case PixelFormat.Format8bppIndexed: // first convert the palet to uint's (ARGB). This is an operation which needs to be done once, so we don't convert // the same color over and over again. byte * pSrc8bindexed = (byte *)srcData.Scan0; uint[] paletteColors = new uint[srcImage.Palette.Entries.Length]; for (int i = 0; i < srcImage.Palette.Entries.Length; i++) { paletteColors[i] = (uint)srcImage.Palette.Entries[i].ToArgb(); } // now convert the pixels to uints for (int i = 0; i < _imageHeight; i++) { for (int j = 0; j < _imageWidth; j++) { _sourcePixels[(i * _imageWidth) + j] = paletteColors[pSrc8bindexed[(i * _imageWidth) + j]]; } } srcImage.UnlockBits(srcData); break; default: // first unlock, as GetPixel will lock/unlock the source for every pixel read... srcImage.UnlockBits(srcData); // use slow getpixel method. This is slow because GetPixel is very slow and also the on-the-fly ARGB conversion. this.Cursor = Cursors.WaitCursor; Application.DoEvents(); for (int i = 0; i < _imageHeight; i++) { for (int j = 0; j < _imageWidth; j++) { Color pixel = srcImage.GetPixel(j, i); _sourcePixels[(i * _imageWidth) + j] = (uint)pixel.ToArgb(); } } this.Cursor = Cursors.Default; Application.DoEvents(); break; } } // init coord arrays for the three points we're using to read the source pixels // A ---------- B // | read direction -> // | // | // | // C double halfWidthSrc = imageWidthD / 2.0; double halfHeightSrc = imageHeightD / 2.0; _xSourceCoords[0] = -halfWidthSrc; _xSourceCoords[1] = halfWidthSrc; _xSourceCoords[2] = -halfWidthSrc; _ySourceCoords[0] = -halfHeightSrc; _ySourceCoords[1] = -halfHeightSrc; _ySourceCoords[2] = halfHeightSrc; _animTimer.Enabled = true; _fpsTimer.Enabled = true; _animTimer.Start(); _fpsTimer.Start(); }
/// <summary> /// Animates the actual image. It renders a new destination image into the rendercanvas pixelbuffer and invalidates the form so the image gets drawn /// in the paint event handler. /// </summary> private void Animate() { _timePreviousFrame = _timeCurrentFrame; _timeCurrentFrame = DateTime.Now; double xa = _xDestinationCoords[0]; double xb = _xDestinationCoords[1]; double xc = _xDestinationCoords[2]; double ya = _yDestinationCoords[0]; double yb = _yDestinationCoords[1]; double yc = _yDestinationCoords[2]; double canvasWidthD = (double)_canvasWidth; double canvasHeightD = (double)_canvasHeight; double xab_delta = (xb - xa) / canvasWidthD; double yab_delta = (yb - ya) / canvasWidthD; double xac_delta = (xc - xa) / canvasHeightD; double yac_delta = (yc - ya) / canvasHeightD; // transpose the rotating centre to the middle of the picture. double x_off = xa + (canvasWidthD * 0.5); double y_off = ya + (canvasHeightD * 0.5); // lock the bits so we can grab a 32bit pointer to the buffer which we can use to write to the buffer directly. BitmapData imageDst = _renderCanvas.LockBits(new Rectangle(0, 0, _canvasWidth, _canvasHeight), ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb); System.IntPtr scan0 = imageDst.Scan0; unsafe { // grab the destination pointer into the pixelbuffer. uint *pDest = (uint *)scan0; for (int i = 0; i < _canvasHeight; i++) { for (int j = 0; j < _canvasWidth; j++) { // calculate for the current pixel on (j,i) in the rendercanvas the x, y for the pixel in the source image. int readX = (int)x_off; int readY = (int)y_off; if (readX < 0) { // clamp readX = (_imageWidth - 1) - (-readX % (_imageWidth - 1)); } if (readY < 0) { // clamp readY = (_imageHeight - 1) - (-readY % (_imageHeight - 1)); } if (readX >= _imageWidth) { // clamp readX = 0 + (readX % (_imageWidth - 1)); } if (readY >= _imageHeight) { // clamp readY = 0 + (readY % (_imageHeight - 1)); } // write the pixel pDest[0] = _sourcePixels[(readY * _imageWidth) + readX]; // set the offsets to the new sourcepixel coordinates for the next pixel on this rasterline. Remember that these pixels // are read using a rotated rectangle on the sourcepixels and the deltas for x and y are used to determine the next sourcepixel // on a rotated line on the sourcepixels. x_off += xab_delta; y_off += yab_delta; pDest++; } double iD = (double)i; // calculates the new start of the next line of the rendercanvas in the sourcepixel. We apply a little offset to the xac/yac deltas to get // a funny rubber effect. x_off = xa + (iD * (xac_delta - 0.002 * iD)) + (canvasWidthD * 0.5); y_off = ya + (iD * (yac_delta + 0.001 * iD)) + (canvasHeightD * 0.5); } } // done, unlock the buffer so we can render the canvas. _renderCanvas.UnlockBits(imageDst); this.Invalidate(); }
public DisplacementMapFilter(BitmapData mapBitmap) { }
/// <summary> /// /// </summary> /// <param name="sourceBitmap">Set source of Bitmap</param> /// <param name="blueLevel">Set Blue in byte</param> /// <param name="greenLevel">Set Green in byte</param> /// <param name="redLevel">Set Red in byte</param> /// <returns></returns> public static System.Drawing.Bitmap ColorBalance(this System.Drawing.Bitmap sourceBitmap, byte blueLevel, byte greenLevel, byte redLevel) { 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); float blue = 0; float green = 0; float red = 0; float blueLevelFloat = blueLevel; float greenLevelFloat = greenLevel; float redLevelFloat = redLevel; for (int k = 0; k + 4 < pixelBuffer.Length; k += 4) { blue = 255.0f / blueLevelFloat * (float)pixelBuffer[k]; green = 255.0f / greenLevelFloat * (float)pixelBuffer[k + 1]; red = 255.0f / redLevelFloat * (float)pixelBuffer[k + 2]; if (blue > 255) { blue = 255; } else if (blue < 0) { blue = 0; } if (green > 255) { green = 255; } else if (green < 0) { green = 0; } if (red > 255) { red = 255; } else if (red < 0) { red = 0; } pixelBuffer[k] = (byte)blue; pixelBuffer[k + 1] = (byte)green; pixelBuffer[k + 2] = (byte)red; } 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); }
public static unsafe void Save(string path) { string idx = Path.Combine(path, "texidx.mul"); string mul = Path.Combine(path, "texmaps.mul"); _checkSums = new List <Checksums>(); using (var fsidx = new FileStream(idx, FileMode.Create, FileAccess.Write, FileShare.Write)) using (var fsmul = new FileStream(mul, FileMode.Create, FileAccess.Write, FileShare.Write)) { var memidx = new MemoryStream(); var memmul = new MemoryStream(); using (BinaryWriter binidx = new BinaryWriter(memidx), binmul = new BinaryWriter(memmul)) { var sha = new SHA256Managed(); //StreamWriter Tex = new StreamWriter(new FileStream("d:/texlog.txt", FileMode.Create, FileAccess.ReadWrite)); for (int index = 0; index < GetIdxLength(); ++index) { if (_cache[index] == null) { _cache[index] = GetTexture(index); } Bitmap bmp = _cache[index]; if ((bmp == null) || (_removed[index])) { binidx.Write(-1); // lookup binidx.Write(0); // length binidx.Write(-1); // extra } else { var ms = new MemoryStream(); bmp.Save(ms, ImageFormat.Bmp); byte[] checksum = sha.ComputeHash(ms.ToArray()); if (compareSaveImages(checksum, out Checksums sum)) { binidx.Write(sum.pos); //lookup binidx.Write(sum.length); binidx.Write(0); //Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, (int)sum.pos, (int)sum.length)); //Tex.WriteLine(System.String.Format("0x{0:X4} -> 0x{1:X4}", sum.index, index)); continue; } BitmapData bd = bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format16bppArgb1555); var line = (ushort *)bd.Scan0; int delta = bd.Stride >> 1; binidx.Write((int)binmul.BaseStream.Position); //lookup var length = (int)binmul.BaseStream.Position; for (int y = 0; y < bmp.Height; ++y, line += delta) { ushort *cur = line; for (int x = 0; x < bmp.Width; ++x) { binmul.Write((ushort)(cur[x] ^ 0x8000)); } } int start = length; length = (int)binmul.BaseStream.Position - length; binidx.Write(length); binidx.Write((bmp.Width == 64 ? 0 : 1)); bmp.UnlockBits(bd); var s = new Checksums { pos = start, length = length, checksum = checksum, index = index }; //Tex.WriteLine(System.String.Format("0x{0:X4} : 0x{1:X4} 0x{2:X4}", index, start, length)); _checkSums.Add(s); } } memidx.WriteTo(fsidx); memmul.WriteTo(fsmul); } } }
public DisplacementMapFilter(BitmapData mapBitmap, Point mapPoint, uint componentX, uint componentY, float scaleX, float scaleY, DisplacementMapFilterMode mode, uint color) { }
public BaseConverter(BmpImage image) { Image = image; oldData = (BitmapData)Image.Data.Clone(); }
/// <summary> /// Returns Bitmap of Texture with verdata bool /// </summary> /// <param name="index"></param> /// <param name="patched"></param> /// <returns></returns> public static unsafe Bitmap GetTexture(int index, out bool patched) { if (_patched.Contains(index)) { patched = (bool)_patched[index]; } else { patched = false; } if (_removed[index]) { return(null); } if (_cache[index] != null) { return(_cache[index]); } Stream stream = _fileIndex.Seek(index, out int length, out int extra, out patched); if (stream == null) { return(null); } if (length == 0) { return(null); } if (patched) { _patched[index] = true; } int size = extra == 0 ? 64 : 128; var bmp = new Bitmap(size, size, PixelFormat.Format16bppArgb1555); BitmapData bd = bmp.LockBits(new Rectangle(0, 0, size, size), ImageLockMode.WriteOnly, PixelFormat.Format16bppArgb1555); var line = (ushort *)bd.Scan0; int delta = bd.Stride >> 1; int max = size * size * 2; if (_streamBuffer == null || _streamBuffer.Length < max) { _streamBuffer = new byte[max]; } stream.Read(_streamBuffer, 0, max); fixed(byte *data = _streamBuffer) { var binData = (ushort *)data; for (int y = 0; y < size; ++y, line += delta) { ushort *cur = line; ushort *end = cur + size; while (cur < end) { *cur++ = (ushort)(*binData++ ^ 0x8000); } } } bmp.UnlockBits(bd); stream.Close(); if (!Files.CacheData) { return(_cache[index] = bmp); } return(bmp); }
public unsafe void Save(string path) { string idx = Path.Combine(path, "Gumpidx.mul"); string mul = Path.Combine(path, "Gumpart.mul"); using ( FileStream fsidx = new FileStream(idx, FileMode.Create, FileAccess.Write, FileShare.Write), fsmul = new FileStream(mul, FileMode.Create, FileAccess.Write, FileShare.Write)) { using (BinaryWriter binidx = new BinaryWriter(fsidx), binmul = new BinaryWriter(fsmul)) { for (int index = 0; index < m_Cache.Length; index++) { if (m_Cache[index] == null) { m_Cache[index] = GetGump(index); } Bitmap bmp = m_Cache[index]; if ((bmp == null) || (m_Removed[index])) { binidx.Write(-1); // lookup binidx.Write(-1); // length binidx.Write(-1); // extra } else { BitmapData bd = bmp.LockBits( new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format16bppArgb1555); var line = (ushort*)bd.Scan0; int delta = bd.Stride >> 1; binidx.Write((int)fsmul.Position); //lookup var length = (int)fsmul.Position; int fill = 0; for (int i = 0; i < bmp.Height; ++i) { binmul.Write(fill); } for (int Y = 0; Y < bmp.Height; ++Y, line += delta) { ushort* cur = line; int X = 0; var current = (int)fsmul.Position; fsmul.Seek(length + Y * 4, SeekOrigin.Begin); int offset = (current - length) / 4; binmul.Write(offset); fsmul.Seek(length + offset * 4, SeekOrigin.Begin); while (X < bd.Width) { int Run = 1; ushort c = cur[X]; while ((X + Run) < bd.Width) { if (c != cur[X + Run]) { break; } ++Run; } if (c == 0) { binmul.Write(c); } else { binmul.Write((ushort)(c ^ 0x8000)); } binmul.Write((short)Run); X += Run; } } length = (int)fsmul.Position - length; binidx.Write(length); binidx.Write((bmp.Width << 16) + bmp.Height); bmp.UnlockBits(bd); } } } } }
/// <summary> /// Returns Bitmap of index and if verdata patched /// </summary> /// <param name="index"></param> /// <param name="patched"></param> /// <returns></returns> public unsafe Bitmap GetGump(int index, out bool patched) { if (m_patched.Contains(index)) { patched = (bool)m_patched[index]; } else { patched = false; } if (index > m_Cache.Length - 1) { return null; } if (m_Removed[index]) { return null; } if (m_Cache[index] != null) { return m_Cache[index]; } int length, extra; Stream stream = m_FileIndex.Seek(index, out length, out extra, out patched); if (stream == null) { return null; } if (extra == -1) { stream.Close(); return null; } if (patched) { m_patched[index] = true; } int width = (extra >> 16) & 0xFFFF; int height = extra & 0xFFFF; if (width <= 0 || height <= 0) { return null; } var bmp = new Bitmap(width, height, PixelFormat.Format16bppArgb1555); BitmapData bd = bmp.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format16bppArgb1555); if (m_StreamBuffer == null || m_StreamBuffer.Length < length) { m_StreamBuffer = new byte[length]; } stream.Read(m_StreamBuffer, 0, length); fixed (byte* data = m_StreamBuffer) { var lookup = (int*)data; var dat = (ushort*)data; var line = (ushort*)bd.Scan0; int delta = bd.Stride >> 1; int count = 0; for (int y = 0; y < height; ++y, line += delta) { count = (*lookup++ * 2); ushort* cur = line; ushort* end = line + bd.Width; while (cur < end) { ushort color = dat[count++]; ushort* next = cur + dat[count++]; if (color == 0) { cur = next; } else { color ^= 0x8000; while (cur < next) { *cur++ = color; } } } } } bmp.UnlockBits(bd); if (_Files.CacheData) { return m_Cache[index] = bmp; } else { return bmp; } }
public unsafe void CreateTexture(BinaryReader reader, int[] palette) { if (Width == 0 || Height == 0) { return; } Image = new Bitmap(Width, Height); MaskImage = new Bitmap(1, 1); BitmapData data = Image.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); byte[] bytes = new byte[0]; byte[] maskbytes = new byte[0]; MemoryStream output; switch (nType) { case 0: //wemade wil file uncompressed if (palette.Length > 256) { bo16bit = true; nSize = nSize * 2; } bytes = reader.ReadBytes(nSize); break; case 1: //shanda wzl file compressed case 4: //shanda miz file compressed output = new MemoryStream(); Ionic.Zlib.ZlibStream deflateStream = new Ionic.Zlib.ZlibStream(output, Ionic.Zlib.CompressionMode.Decompress); deflateStream.Write(reader.ReadBytes(nSize), 0, nSize); bytes = output.ToArray(); deflateStream.Close(); output.Close(); break; case 2: byte Compressed = reader.ReadByte(); reader.ReadBytes(5); if (Compressed != 8) { bytes = reader.ReadBytes(nSize - 6); break; } MemoryStream input = new MemoryStream(reader.ReadBytes(nSize - 6)); output = new MemoryStream(); byte[] buffer = new byte[10]; System.IO.Compression.DeflateStream decompress = new System.IO.Compression.DeflateStream(input, System.IO.Compression.CompressionMode.Decompress); int len; while ((len = decompress.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, len); } bytes = output.ToArray(); decompress.Close(); output.Close(); input.Close(); break; case 3: MaskImage = new Bitmap(Width, Height); byte[][] DecodedPixels = DecompressWemadeMir3(reader, Width, Height, nSize); if (DecodedPixels != null) { bytes = DecodedPixels[0]; if (HasMask) { maskbytes = DecodedPixels[1]; } } else { HasMask = false; bytes = new byte[Width * Height * 2]; } break; } int index = 0; if (bytes.Length <= 1) { Image.UnlockBits(data); Image.Dispose(); Image = null; MaskImage.Dispose(); return; } int *scan0 = (int *)data.Scan0; { for (int y = Height - 1; y >= 0; y--) { for (int x = 0; x < Width; x++) { if (bo16bit) { scan0[y * Width + x] = convert16bitTo32bit(bytes[index++] + (bytes[index++] << 8)); } else { scan0[y * Width + x] = palette[bytes[index++]]; } } if (((nType == 1) || (nType == 4)) & (Width % 4 > 0)) { index += WidthBytes(bo16bit ? 16 : 8, Width) - (Width * (bo16bit ? 2 : 1)); } } } Image.UnlockBits(data); index = 0; if (HasMask) { BitmapData Maskdata = MaskImage.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); int * maskscan0 = (int *)Maskdata.Scan0; { for (int y = Height - 1; y >= 0; y--) { for (int x = 0; x < Width; x++) { maskscan0[y * Width + x] = convert16bitTo32bit(maskbytes[index++] + (maskbytes[index++] << 8)); } } } MaskImage.UnlockBits(Maskdata); } }
public List<LineSegment> delaunayTriangulation( BitmapData keepOutMask = null) { return DelaunayTools.delaunayLinesForEdges(Tools.Instance.selectNonIntersectingEdges(keepOutMask, _edges)); }
public static bool Contrast(Bitmap b, sbyte nContrast) { if (nContrast < -100) { return(false); } if (nContrast > 100) { return(false); } double pixel = 0, contrast = (100.0 + nContrast) / 100.0; contrast *= contrast; int red, green, blue; // GDI+ still lies to us - the 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; System.IntPtr Scan0 = bmData.Scan0; unsafe { byte *p = (byte *)(void *)Scan0; 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]; pixel = red / 255.0; pixel -= 0.5; pixel *= contrast; pixel += 0.5; pixel *= 255; if (pixel < 0) { pixel = 0; } if (pixel > 255) { pixel = 255; } p[2] = (byte)pixel; pixel = green / 255.0; pixel -= 0.5; pixel *= contrast; pixel += 0.5; pixel *= 255; if (pixel < 0) { pixel = 0; } if (pixel > 255) { pixel = 255; } p[1] = (byte)pixel; pixel = blue / 255.0; pixel -= 0.5; pixel *= contrast; pixel += 0.5; pixel *= 255; if (pixel < 0) { pixel = 0; } if (pixel > 255) { pixel = 255; } p[0] = (byte)pixel; p += 3; } p += nOffset; } } b.UnlockBits(bmData); return(true); }
public JPGEncoder( Texture2D texture, float quality, string path, bool blocking ) { this.path = path; // save out texture data to our own data structure image = new BitmapData(texture); quality = Mathf.Clamp(quality, 1, 100); sf = (quality < 50) ? (int)(5000 / quality) : (int)(200 - quality*2); cores = SystemInfo.processorCount; Thread thread = new Thread(DoEncoding); thread.Start(); if( blocking ) thread.Join(); }
public static bool Conv3x3(Bitmap b, ConvMatrix m) { // Avoid divide by zero errors if (0 == m.Factor) { return(false); } Bitmap bSrc = (Bitmap)b.Clone(); // GDI+ still lies to us - the return format is BGR, NOT RGB. BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); BitmapData bmSrc = bSrc.LockBits(new Rectangle(0, 0, bSrc.Width, bSrc.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int stride = bmData.Stride; int stride2 = stride * 2; System.IntPtr Scan0 = bmData.Scan0; System.IntPtr SrcScan0 = bmSrc.Scan0; unsafe { byte *p = (byte *)(void *)Scan0; byte *pSrc = (byte *)(void *)SrcScan0; int nOffset = stride + 6 - b.Width * 3; int nWidth = b.Width - 2; int nHeight = b.Height - 2; int nPixel; for (int y = 0; y < nHeight; ++y) { for (int x = 0; x < nWidth; ++x) { nPixel = ((((pSrc[2] * m.TopLeft) + (pSrc[5] * m.TopMid) + (pSrc[8] * m.TopRight) + (pSrc[2 + stride] * m.MidLeft) + (pSrc[5 + stride] * m.Pixel) + (pSrc[8 + stride] * m.MidRight) + (pSrc[2 + stride2] * m.BottomLeft) + (pSrc[5 + stride2] * m.BottomMid) + (pSrc[8 + stride2] * m.BottomRight)) / m.Factor) + m.Offset); if (nPixel < 0) { nPixel = 0; } if (nPixel > 255) { nPixel = 255; } p[5 + stride] = (byte)nPixel; nPixel = ((((pSrc[1] * m.TopLeft) + (pSrc[4] * m.TopMid) + (pSrc[7] * m.TopRight) + (pSrc[1 + stride] * m.MidLeft) + (pSrc[4 + stride] * m.Pixel) + (pSrc[7 + stride] * m.MidRight) + (pSrc[1 + stride2] * m.BottomLeft) + (pSrc[4 + stride2] * m.BottomMid) + (pSrc[7 + stride2] * m.BottomRight)) / m.Factor) + m.Offset); if (nPixel < 0) { nPixel = 0; } if (nPixel > 255) { nPixel = 255; } p[4 + stride] = (byte)nPixel; nPixel = ((((pSrc[0] * m.TopLeft) + (pSrc[3] * m.TopMid) + (pSrc[6] * m.TopRight) + (pSrc[0 + stride] * m.MidLeft) + (pSrc[3 + stride] * m.Pixel) + (pSrc[6 + stride] * m.MidRight) + (pSrc[0 + stride2] * m.BottomLeft) + (pSrc[3 + stride2] * m.BottomMid) + (pSrc[6 + stride2] * m.BottomRight)) / m.Factor) + m.Offset); if (nPixel < 0) { nPixel = 0; } if (nPixel > 255) { nPixel = 255; } p[3 + stride] = (byte)nPixel; p += 3; pSrc += 3; } p += nOffset; pSrc += nOffset; } } b.UnlockBits(bmData); bSrc.UnlockBits(bmSrc); return(true); }
public DisplacementMapFilter(BitmapData mapBitmap, Point mapPoint, uint componentX) { }
/// <summary>Initialize the AviFile.</summary> /// <param name="path">The path to the output file.</param> /// <param name="frameRate">The frame rate for the video.</param> /// <param name="width">The width of the video.</param> /// <param name="height">The height of the video.</param> /// <param name="quality">Video quality 0 to 10000.</param> public AviWriter(string path, int frameRate, int width, int height, uint quality = 10000) { // Validate parameters if (path == null) { throw new ArgumentNullException("path"); } if (frameRate <= 0) { throw new ArgumentOutOfRangeException("frameRate", frameRate, "The frame rate must be at least 1 frame per second."); } if (width <= 0) { throw new ArgumentOutOfRangeException("width", width, "The width must be at least 1."); } if (height <= 0) { throw new ArgumentOutOfRangeException("height", height, "The height must be at least 1."); } // Store parameters uint fccType = GetFourCc("vids"); _width = width; _height = height; _disposed = false; //Get the stride information by creating a new bitmap and querying it using (Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb)) { BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); _stride = (uint)bmpData.Stride; bmp.UnlockBits(bmpData); } try { // Initialize the AVI library AVIFileInit(); // Open the output AVI file int rv = AVIFileOpenW(ref _aviFile, path, AVI_OPEN_MODE_CREATEWRITE, 0); if (rv != 0) { throw new Win32Exception(((AviErrors)rv).ToString()); } // Create a new stream in the avi file var aviStreamInfo = new AVISTREAMINFOW(); aviStreamInfo.fccType = fccType; aviStreamInfo.fccHandler = 0; aviStreamInfo.dwScale = 1; aviStreamInfo.dwRate = (uint)frameRate; aviStreamInfo.dwSuggestedBufferSize = (uint)(_height * _stride); aviStreamInfo.dwQuality = quality; //-1 default 0xffffffff aviStreamInfo.rcFrame = new RECT(); aviStreamInfo.rcFrame.bottom = _height; aviStreamInfo.rcFrame.right = _width; rv = AVIFileCreateStream(_aviFile, out _aviStream, ref aviStreamInfo); if (rv != 0) { throw new Win32Exception(((AviErrors)rv).ToString()); } // Configure the compressed stream var streamFormat = new BITMAPINFOHEADER(); streamFormat.biSize = 40; streamFormat.biWidth = _width; streamFormat.biHeight = _height; streamFormat.biPlanes = 1; streamFormat.biBitCount = 24; streamFormat.biSizeImage = (uint)(_stride * _height); rv = AVIStreamSetFormat(_aviStream, 0, ref streamFormat, 40); if (rv != 0) { throw new Win32Exception(((AviErrors)rv).ToString()); //, "Unable to set the AVI stream format."); } } catch { // Clean up Dispose(false); try { if (File.Exists(path)) { File.Delete(path); } } catch { } throw; } }
/// <summary> /// Constructs a new Integral image from a BitmapData image. /// </summary> /// /// <param name="imageData">The source image from where the integral image should be computed.</param> /// /// <returns> /// The <see cref="IntegralImage2"/> representation of /// the <paramref name="imageData">source image</paramref>.</returns> /// public static IntegralImage2 FromBitmap(BitmapData imageData) { return(FromBitmap(imageData, 0)); }
/// <summary> /// Process image looking for interest points. /// </summary> /// /// <param name="imageData">Source image data to process.</param> /// /// <returns>Returns list of found interest points.</returns> /// /// <exception cref="UnsupportedImageFormatException"> /// The source image has incorrect pixel format. /// </exception> /// public List <double[]> ProcessImage(BitmapData imageData) { return(ProcessImage(new UnmanagedImage(imageData))); }
public static Texture LoadImage(Bitmap image, IEnumerable <Payload.TextArea> textAreas = null) { int frameCount = image.FrameDimensionsList.Any(d => d == FrameDimension.Time.Guid) ? image.GetFrameCount(FrameDimension.Time) : 1; Debug.WriteLine($"Texture: The image has {frameCount} frames."); if (frameCount > 0) { Bitmap[] Frames = new Bitmap[frameCount]; int[] frameTimes = new int[frameCount]; if (frameCount > 1) { byte[] times = image.GetPropertyItem(0x5100).Value; for (int i = 0; i < frameCount; i++) { int dur = BitConverter.ToInt32(times, (i * 4) % times.Length) * 10; frameTimes[i] = dur; image.SelectActiveFrame(FrameDimension.Time, i); Frames[i] = new Bitmap(image.Size.Width, image.Size.Height); var g = Graphics.FromImage(Frames[i]); g.DrawImage(image, new Point(0, 0)); g.Dispose(); if (!(textAreas is null)) { Frames[i].DrawTextAreas(textAreas); } Frames[i].RotateFlip(RotateFlipType.RotateNoneFlipY); } } var textureId = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2DArray, textureId); GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); GL.TexParameter(TextureTarget.Texture2DArray, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); int depth = frameCount; GL.TexStorage3D(TextureTarget3d.Texture2DArray, 1, SizedInternalFormat.Rgba8, image.Width, image.Height, depth); GL.PixelStore(PixelStoreParameter.UnpackRowLength, image.Width); if (frameCount > 1) { for (int i = 0; i < depth; i++) { // image.SelectActiveFrame(FrameDimension.Time, i); BitmapData data = Frames[i].LockBits( new System.Drawing.Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexSubImage3D( // 4 bytes in an Bgra value. TextureTarget.Texture2DArray, 0, 0, 0, i, image.Size.Width, image.Size.Height, 1, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0 ); Frames[i].UnlockBits(data); } } else { if (!(textAreas is null)) { image.DrawTextAreas(textAreas); } image.RotateFlip(RotateFlipType.RotateNoneFlipY); BitmapData data = image.LockBits( new System.Drawing.Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb ); GL.TexSubImage3D( // 4 bytes in an Bgra value. TextureTarget.Texture2DArray, 0, 0, 0, 0, image.Size.Width, image.Size.Height, 1, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0 ); image.UnlockBits(data); } return(new Texture(textureId, image.Width, image.Height, depth, frameTimes)); } return(null); }
List <FeatureDescriptor> IFeatureDetector <FeatureDescriptor, double[]> .ProcessImage(BitmapData imageData) { return(ProcessImage(imageData).ConvertAll(p => new FeatureDescriptor(p))); }
private void UnlockBitmap(ref Bitmap bmp) { int total_size = bmpData.Stride * bmpData.Height; Marshal.Copy(imageBytes, 0, bmpData.Scan0, total_size); bmp.UnlockBits(bmpData); imageBytes = null; bmpData = null; }
// Apply filter public Bitmap Apply(Bitmap srcImg) { // get source image size int width = srcImg.Width; int height = srcImg.Height; // convert input to grayscale if it's not yet bool disposeSource = false; if (srcImg.PixelFormat != PixelFormat.Format8bppIndexed) { disposeSource = true; // create grayscale image IFilter filter = new GrayscaleRMY(); srcImg = filter.Apply(srcImg); } // lock source bitmap data BitmapData srcData = srcImg.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed); // create new image Bitmap dstImg = AForge.Imaging.Image.CreateGrayscaleImage(width, height); // lock destination bitmap data BitmapData dstData = dstImg.LockBits( new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed); int stride = srcData.Stride; int offset = stride - width; int widthM1 = width - 1; int heightM1 = height - 1; double ex, ey, weight, weightTotal = 0, total = 0; // do the job unsafe { byte *src = (byte *)srcData.Scan0.ToPointer() + stride; byte *dst = (byte *)dstData.Scan0.ToPointer(); // --- 1st pass - collecting statistics // for each line for (int y = 1; y < heightM1; y++) { src++; // for each pixels for (int x = 1; x < widthM1; x++, src++) { // the equations are: // ex = I(x + 1, y) - I(x - 1, y) // ey = I(x, y + 1) - I(x, y - 1) // weight = max(ex, ey) // weightTotal += weight // total += weight * I(x, y) ex = src[1] - src[-1]; ey = src[stride] - src[-stride]; weight = (ex > ey) ? ex : ey; weightTotal += weight; total += weight * (*src); } src += offset + 1; } // calculate threshold threshold = (weightTotal == 0) ? (byte)0 : (byte)(total / weightTotal); // --- 2nd pass - thresholding src = (byte *)srcData.Scan0.ToPointer(); // for each line for (int y = 0; y < height; y++) { // for all pixels for (int x = 0; x < width; x++, src++, dst++) { *dst = (byte)((*src <= threshold) ? 0 : 255); } src += offset; dst += offset; } } // unlock both images dstImg.UnlockBits(dstData); srcImg.UnlockBits(srcData); if (disposeSource == true) { srcImg.Dispose(); } return(dstImg); }
public static void DoWork(Object pUri) { string uri = pUri.ToString(); int testnumber = 0; int width = 640; int height = 480; int fps = 30; H264Encoder enc = new H264Encoder(); //enc.SetupEncode(@"E:\TEMP\encoded.mp4", width, height, fps); enc.SetupEncode(uri, width, height, fps); // "rtsp://127.0.0.1:8554/live.sdp"; Font drawFont = new Font("Arial", 16); SolidBrush drawBrush = new SolidBrush(Color.Red); StringFormat drawFormat = new StringFormat(); drawFormat.FormatFlags = StringFormatFlags.FitBlackBox; float font_x = 480.0F; float font_y = 450.0F; string drawString; Bitmap image = new Bitmap(width, height); Graphics g = Graphics.FromImage(image); g.FillRectangle(Brushes.Black, 0, 0, width, height); Brush[] brushList = new Brush[] { Brushes.Green, Brushes.Red, Brushes.Yellow, Brushes.Pink, Brushes.LimeGreen }; Random rnd = new Random(); for (int j = 0; j < 100; j++) { for (int i = 0; i < 100; i++) { int rndTmp = rnd.Next(1, 3); g.FillRectangle(brushList[i % 5], (i % width) * 2, (i % height) * 0.5f, i % 30, i % 30); g.FillRectangle(brushList[i % 5], (i % width) * 2, (i % height) * 2, i % 30, i % 30); g.FillRectangle(brushList[i % 5], (i % width) * 0.5f, (i % height) * 2, i % 30, i % 30); drawString = String.Format("i:{0},T:{1}", i, testnumber); g.FillRectangle(Brushes.Black, font_x, font_y, width, height); g.DrawString(drawString, drawFont, drawBrush, font_x, font_y, drawFormat); g.Save(); Rectangle rect = new Rectangle(0, 0, image.Width, image.Height); BitmapData bmpData = image.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * image.Height; byte[] rgbValues = new byte[bytes]; // Copy the RGB values into the array. System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); enc.WriteFrame(rgbValues); testnumber++; System.Threading.Thread.Sleep(10); // Unlock the bits. image.UnlockBits(bmpData); } g.FillRectangle(Brushes.Black, 0, 0, width, height); } }
void getImage() { GMapProvider type = GMap.NET.MapProviders.GoogleSatelliteMapProvider.Instance; PureProjection prj = type.Projection; if (!area.IsEmpty) { try { //string bigImage = zoom + "-" + type + "-vilnius.png"; //Console.WriteLine("Preparing: " + bigImage); //Console.WriteLine("Zoom: " + zoom); //Console.WriteLine("Type: " + type.ToString()); //Console.WriteLine("Area: " + area); var types = type;// GMaps.Instance.GetAllLayersOfType(type); // max zoom level zoom = 16; GPoint topLeftPx = prj.FromLatLngToPixel(area.LocationTopLeft, zoom); GPoint rightButtomPx = prj.FromLatLngToPixel(area.Bottom, area.Right, zoom); GPoint pxDelta = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y); // zoom based on pixel density while (pxDelta.X > 2000) { zoom--; // current area topLeftPx = prj.FromLatLngToPixel(area.LocationTopLeft, zoom); rightButtomPx = prj.FromLatLngToPixel(area.Bottom, area.Right, zoom); pxDelta = new GPoint(rightButtomPx.X - topLeftPx.X, rightButtomPx.Y - topLeftPx.Y); } // get type list at new zoom level List <GPoint> tileArea = prj.GetAreaTileList(area, zoom, 0); DateTime startimage = DateTime.Now; int padding = 0; { using (Bitmap bmpDestination = new Bitmap((int)pxDelta.X + padding * 2, (int)pxDelta.Y + padding * 2)) { using (Graphics gfx = Graphics.FromImage(bmpDestination)) { gfx.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; // get tiles & combine into one foreach (var p in tileArea) { Console.WriteLine("Downloading[" + p + "]: " + tileArea.IndexOf(p) + " of " + tileArea.Count); foreach (var tp in type.Overlays) { Exception ex; GMapImage tile = GMaps.Instance.GetImageFrom(tp, p, zoom, out ex) as GMapImage; //GMapImage tile = type.GetTileImage(p, zoom) as GMapImage; //tile.Img.Save(zoom + "-" + p.X + "-" + p.Y + ".bmp"); if (tile != null) { using (tile) { long x = p.X * prj.TileSize.Width - topLeftPx.X + padding; long y = p.Y * prj.TileSize.Width - topLeftPx.Y + padding; { gfx.DrawImage(tile.Img, x, y, prj.TileSize.Width, prj.TileSize.Height); } } } } } } _terrain = new Bitmap(bmpDestination, 1024 * 2, 1024 * 2); // _terrain.Save(zoom +"-map.bmp"); GL.BindTexture(TextureTarget.Texture2D, texture); BitmapData data = _terrain.LockBits(new System.Drawing.Rectangle(0, 0, _terrain.Width, _terrain.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //Console.WriteLine("w {0} h {1}",data.Width, data.Height); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); _terrain.UnlockBits(data); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); } } } catch (Exception ex) { Console.WriteLine(ex); } } }
/** * * @param proximityMap a BitmapData whose regions are filled with the site index values; see PlanePointsCanvas::fillRegions() * @param x * @param y * @return coordinates of nearest Site to (x, y) * */ public Vector2 nearestSitePoint(BitmapData proximityMap, float x, float y) { return _sites.nearestSitePoint(proximityMap, x, y); }
public static List <System.Drawing.Point> FindPic(int left, int top, int width, int height, Bitmap S_bmp, Bitmap P_bmp, SearchMethod method, out double matchDegree) { if (S_bmp.PixelFormat != PixelFormat.Format24bppRgb) { throw new Exception("颜色格式只支持24位bmp"); } if (P_bmp.PixelFormat != PixelFormat.Format24bppRgb) { throw new Exception("颜色格式只支持24位bmp"); } int S_Width = S_bmp.Width; int S_Height = S_bmp.Height; int P_Width = P_bmp.Width; int P_Height = P_bmp.Height; Color BackColor = P_bmp.GetPixel(0, 0); //背景色 BitmapData S_Data = null; BitmapData P_Data = null; List <System.Drawing.Point> List; int similar = 10; if ((int)method > 5) { S_Data = S_bmp.LockBits(new Rectangle(0, 0, S_Width, S_Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); P_Data = P_bmp.LockBits(new Rectangle(0, 0, P_Width, P_Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); } switch (method) { case SearchMethod.SqDiff: List = OpenCvFindPic(left, top, width, height, S_bmp, P_bmp, 0, out matchDegree); break; case SearchMethod.SqDiffNormed: List = OpenCvFindPic(left, top, width, height, S_bmp, P_bmp, 1, out matchDegree); break; case SearchMethod.CCorr: List = OpenCvFindPic(left, top, width, height, S_bmp, P_bmp, 2, out matchDegree); break; case SearchMethod.CCorrNormed: List = OpenCvFindPic(left, top, width, height, S_bmp, P_bmp, 3, out matchDegree); break; case SearchMethod.CCoeff: List = OpenCvFindPic(left, top, width, height, S_bmp, P_bmp, 4, out matchDegree); break; case SearchMethod.CCoeffNormed: List = OpenCvFindPic(left, top, width, height, S_bmp, P_bmp, 5, out matchDegree); break; case SearchMethod.StrictMatch: List = StrictMatch(left, top, width, height, S_Data, P_Data); matchDegree = 1; break; case SearchMethod.StrictMatchRND: List = StrictMatchRND(left, top, width, height, S_Data, P_Data); matchDegree = 1; break; case SearchMethod.OpacityDiff: List = OpacityDiff(left, top, width, height, S_Data, P_Data, GetPixelData(P_Data, BackColor), similar); matchDegree = 1; break; case SearchMethod.SimilarMatch: List = SimilarMatch(left, top, width, height, S_Data, P_Data, similar); matchDegree = 1; break; default: List = StrictMatchRND(left, top, width, height, S_Data, P_Data); matchDegree = 1; break; } if ((int)method > 5) { S_bmp.UnlockBits(S_Data); P_bmp.UnlockBits(P_Data); } return(List); }
public List<LineSegment> spanningTree(string type = "minimum", BitmapData keepOutMask = null) { List<Edge> edges = Tools.Instance.selectNonIntersectingEdges(keepOutMask, _edges); List<LineSegment> segments = DelaunayTools.delaunayLinesForEdges(edges); return Tools.Instance.kruskal(segments, type); }
// Process new frame public void ProcessFrame( ref Bitmap image ) { if ( backgroundFrame == null ) { // create initial backgroung image backgroundFrame = grayscaleFilter.Apply( image ); // get image dimension width = image.Width; height = image.Height; // just return for the first time return; } Bitmap tmpImage; // apply the grayscale file tmpImage = grayscaleFilter.Apply( image ); // set backgroud frame as an overlay for difference filter differenceFilter.OverlayImage = backgroundFrame; // apply difference filter Bitmap tmpImage2 = differenceFilter.Apply( tmpImage ); // lock the temporary image and apply some filters on the locked data bitmapData = tmpImage2.LockBits( new Rectangle( 0, 0, width, height ), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed ); // threshold filter thresholdFilter.ApplyInPlace( bitmapData ); // erosion filter Bitmap tmpImage3 = erosionFilter.Apply( bitmapData ); // unlock temporary image tmpImage2.UnlockBits( bitmapData ); tmpImage2.Dispose( ); // calculate amount of changed pixels pixelsChanged = ( calculateMotionLevel ) ? CalculateWhitePixels( tmpImage3 ) : 0; // dispose old background backgroundFrame.Dispose( ); // set backgound to current backgroundFrame = tmpImage; // extract red channel from the original image Bitmap redChannel = extrachChannel.Apply( image ); // merge red channel with moving object mergeFilter.OverlayImage = tmpImage3; Bitmap tmpImage4 = mergeFilter.Apply( redChannel ); redChannel.Dispose( ); tmpImage3.Dispose( ); // replace red channel in the original image if(replaceChannel == null) replaceChannel = new ReplaceChannel(RGB.R, tmpImage4); else replaceChannel.ChannelImage = tmpImage4; Bitmap tmpImage5 = replaceChannel.Apply( image ); tmpImage4.Dispose( ); image.Dispose( ); image = tmpImage5; }
public JPGEncoder(Texture2D texture, float quality) { // save out texture data to our own data structure image = new BitmapData(texture); if (quality <= 0) { quality = 1; } if (quality > 100.0f) { quality = 100.0f; } if (quality < 50.0f) { sf = Mathf.RoundToInt(5000f / quality); } else { sf = Mathf.RoundToInt(200f - quality*2f); } // spin this off into the background //var thread = new Thread(doEncoding); //thread.Start(); doEncoding(); }
/// <summary> /// Populate the data buffer. In this class I'm retrieving bitmaps /// from files based on the current frame number. /// </summary> /// <param name="iFrameNumber">Frame number</param> /// <param name="ip">A pointer to the memory to populate with the bitmap data</param> /// <param name="iRead">returns the number of parameters read</param> /// <returns>0 on success and 1 on end of stream</returns> public override int GetImage(int iFrameNumber, IntPtr ip, int iSize, out int iRead) { int hr = 0; if (iFrameNumber % DIV == 0) { try { // Open the next image string sFileName = String.Format(@"{1}\{0:00000000}.jpg", iFrameNumber / DIV + 1, m_sPath); Bitmap bmp = new Bitmap(sFileName); Rectangle r = new Rectangle(0, 0, bmp.Width, bmp.Height); // Release the previous image if (m_bmd != null) { m_bmp.UnlockBits(m_bmd); m_bmp.Dispose(); } // Store the pointers m_bmp = bmp; m_bmd = m_bmp.LockBits(r, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); // Only do the copy if we have a place to put the data if (ip != IntPtr.Zero) { // Copy from the bmd to the MediaSample CopyMemory(ip, m_bmd.Scan0, iSize); } } catch { // Presumably we ran out of files. Terminate the stream hr = 1; } } iRead = iSize; return hr; }
private void RGB2YUV( BitmapData image, int xpos, int ypos) { int pos = 0; for (int y = 0; y < 8; y++) { for (int x = 0; x < 8; x++) { Color32 C = image.GetPixelColor(xpos+x, image.height - (ypos+y)); YDU[pos]=((( 0.29900f)*C.r +( 0.58700f)*C.g+( 0.11400f)*C.b))-128; UDU[pos]=(((-0.16874f)*C.r +(-0.33126f)*C.g+( 0.50000f)*C.b)); VDU[pos]=((( 0.50000f)*C.r +(-0.41869f)*C.g+(-0.08131f)*C.b)); pos++; } } }
/// <summary> /// 设置 BitmapData 指定坐标的颜色信息 /// </summary> /// <param name="destData">设置图像数据的颜色 必须为 PixelFormat.Format24bppRgb 格式图像数据</param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="color">待设置颜色</param> /// <remarks> /// Format24BppRgb 已知X,Y坐标,像素第一个元素的位置为Scan0+(Y*Stride)+(X*3)。 /// 这是blue字节的位置,接下来的2个字节分别含有green、red数据。 /// </remarks> private void BitmapDataColorSet(BitmapData destData, int x, int y, Color color) { byte[] rgbValues = new byte[3] { color.B, color.G, color.R }; Marshal.Copy(rgbValues, 0, (IntPtr)((long)destData.Scan0 + ((y * destData.Stride) + (x * 3))), 3); }
public DisplacementMapFilter(BitmapData mapBitmap, Point mapPoint, uint componentX, uint componentY, float scaleX) { }
// compute imageDiff from imageTest and imageRef public TestResult ComputeDiff(uint Threshold) { if (imageDiff != null) { imageDiff.Dispose(); imageDiff = null; } TestResult Ret = new TestResult(); if (imageTest == null) { Ret.ErrorText = "missing Test"; return(Ret); } if (imageRef == null) { Ret.ErrorText = "missing Ref"; return(Ret); } System.Drawing.Size sizeTest = GetImageSize(imageTest); System.Drawing.Size sizeRef = GetImageSize(imageRef); if (sizeTest != sizeRef) { Ret.ErrorText = "Size " + sizeTest.Width.ToString() + "x" + sizeTest.Height.ToString() + " != " + sizeRef.Width.ToString() + "x" + sizeRef.Height.ToString(); return(Ret); } System.Drawing.Size size = GetImagesSize(); // todo: exit if Size or format is not the same Debug.Assert(imageTest.PixelFormat == PixelFormat.Format32bppArgb); imageDiff = new Bitmap(size.Width, size.Height); uint CountedErrorPixels = 0; BitmapData dataTest = imageTest.LockBits(new Rectangle(0, 0, size.Width, size.Height), ImageLockMode.ReadOnly, imageTest.PixelFormat); BitmapData dataDiff = imageDiff.LockBits(new Rectangle(0, 0, size.Width, size.Height), ImageLockMode.WriteOnly, imageTest.PixelFormat); BitmapData dataRef = imageRef.LockBits(new Rectangle(0, 0, size.Width, size.Height), ImageLockMode.ReadOnly, imageTest.PixelFormat); unsafe { for (int x = 0; x < size.Width; ++x) { for (int y = 0; y < size.Height; ++y) { PixelElement *valueTest = (PixelElement *)((byte *)dataTest.Scan0.ToPointer() + dataTest.Stride * y + x * sizeof(PixelElement)); PixelElement *valueDiff = (PixelElement *)((byte *)dataDiff.Scan0.ToPointer() + dataDiff.Stride * y + x * sizeof(PixelElement)); PixelElement *valueRef = (PixelElement *)((byte *)dataRef.Scan0.ToPointer() + dataRef.Stride * y + x * sizeof(PixelElement)); // float Diff = PixelElement.ComputeSquaredError(*valueDiff, *valueRef); uint localError = PixelElement.ComputeAbsDiff(*valueTest, *valueRef); // all pixels opaque valueDiff->a = 0xff; if (localError >= Threshold) { ++CountedErrorPixels; // valueDiff->SetErrorColor(PixelElement.ComputeSquaredError(*valueTest, *valueRef)); valueDiff->SetErrorColor(localError); // *valueDiff = *valueRef; } } } } imageRef.UnlockBits(dataRef); imageDiff.UnlockBits(dataDiff); imageTest.UnlockBits(dataTest); Ret.ErrorPixels = CountedErrorPixels; // update Thumbnails { Ret.ThumbnailTest = resizeImage(imageTest); Ret.ThumbnailDiff = resizeImage(imageDiff); Ret.ThumbnailRef = resizeImage(imageRef); } return(Ret); }
protected static void FillBitmap <T>(IRegularGridCoverageLayer gridLayer, IRegularGridCoverage gridCoverage, Bitmap bitmap, PixelFormat pixelFormat, IVariableFilter[] filters) where T : IComparable, IComparable <T> { // HACK: free memory before getting large block GC.Collect(1, GCCollectionMode.Optimized); T[] gridValues = gridCoverage.Components[0].GetValues <T>(filters).ToArray(); var imageWidth = bitmap.Width; var imageHeight = bitmap.Height; Trace.Assert(imageHeight * imageWidth == gridValues.Count()); //flip upside down for (int k = 0; k < imageWidth; k++) { for (int j = 0; j < imageHeight / 2; j++) { T swap1 = gridValues[k + j * imageWidth]; T swap2 = gridValues[(imageHeight - 1 - j) * imageWidth + k]; gridValues[k + j * imageWidth] = swap2; gridValues[(imageHeight - 1 - j) * imageWidth + k] = swap1; } } if (gridLayer.Theme == null) { object minValue = gridCoverage.Components[0].MinValue; object maxValue = gridCoverage.Components[0].MaxValue; gridLayer.Theme = GenerateDefaultTheme(gridCoverage.Components[0].Name, gridCoverage.Components[0].NoDataValues, minValue, maxValue); } // Add NoDataValues from grid coverage if it was unspecified: var theme = gridLayer.Theme as Theme; if (theme != null && theme.NoDataValues == null) { theme.NoDataValues = gridCoverage.Components[0].NoDataValues; } BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, imageWidth, imageHeight), ImageLockMode.ReadWrite, pixelFormat); try { unsafe { // use a pointer to get direct access to the bits in the bitmap. // this is faster and removes the need to copy values from // unmanaged to managed memory and vice versa. IntPtr array = bitmapData.Scan0; int * pByte = (int *)array.ToPointer(); int bytes = bitmapData.Width * bitmapData.Height; ((Theme)gridLayer.Theme).GetFillColors(pByte, bytes, (T[])gridValues); } } catch (Exception e) { throw e; } finally { if (bitmapData != null) { bitmap.UnlockBits(bitmapData); // force a collect to reclaim large allocated arrays that have survived the first generations GC.Collect(1, GCCollectionMode.Optimized); } } }
/** * Handle our initialization and encoding */ public void doEncoding() { isDone = false; // Create tables -- technically we could only do this once for multiple encodes initHuffmanTbl(); initCategoryfloat(); initQuantTables(sf); // Do actual encoding encode(); // signal that our data is ok to use now isDone = true; // tell the thread to stop--not sure if this is actually needed image = null; }
private static unsafe List <System.Drawing.Point> StrictMatchRND(int left, int top, int width, int height, BitmapData S_Data, BitmapData P_Data) { List <System.Drawing.Point> List = new List <System.Drawing.Point>(); int S_stride = S_Data.Stride; int P_stride = P_Data.Stride; IntPtr S_Iptr = S_Data.Scan0; IntPtr P_Iptr = P_Data.Scan0; byte * S_ptr; byte * P_ptr; bool IsOk = false; int _BreakW = width - P_Data.Width + 1; int _BreakH = height - P_Data.Height + 1; Random r = new Random(); // fitst we generate a random num list int pix_num = P_Data.Height * P_Data.Width; List <int> pix_list = new List <int>(); for (int i = 0; i < pix_num; i++) { pix_list.Add(i); } List <int> random_pix_list = new List <int>(); for (int i = 0; i < pix_num; i++) { int index = r.Next(pix_num - i); //Debug.WriteLine(index); random_pix_list.Add(pix_list[index]); pix_list.RemoveAt(index); } //Debug.WriteLine("WH:"+P_Data.Width.ToString() + " " + P_Data.Height.ToString()); for (int h = top; h < _BreakH; h++) { for (int w = left; w < _BreakW; w++) { P_ptr = (byte *)(P_Iptr); // there could be a random check for quick jump the loop for (int i = 0; i < pix_num; i++) { int y = (int)(random_pix_list[i] / P_Data.Width); int x = random_pix_list[i] % P_Data.Width; //Debug.WriteLine(random_pix_list[i]); //Debug.WriteLine(x.ToString() +" "+ y.ToString()); S_ptr = (byte *)((int)S_Iptr + S_stride * (h + y) + (w + x) * 3); P_ptr = (byte *)((int)P_Iptr + P_stride * y + x * 3); //Debug.WriteLine(S_ptr[0].ToString() + " " + S_ptr[1].ToString() + " " + S_ptr[2].ToString()); //Debug.WriteLine(P_ptr[0].ToString() + " " + P_ptr[1].ToString() + " " + P_ptr[2].ToString()); if (S_ptr[0] == P_ptr[0] && S_ptr[1] == P_ptr[1] && S_ptr[2] == P_ptr[2]) { IsOk = true; } else { IsOk = false; break; } } if (IsOk) { //Debug.WriteLine("find"); List.Add(new System.Drawing.Point(w, h)); } IsOk = false; } } return(List); }
/// <summary> /// Save media to stream. /// </summary> /// <param name="stream"> /// A <see cref="IO.Stream"/> which stores the media data. /// </param> /// <param name="image"> /// A <see cref="Image"/> holding the data to be stored. /// </param> /// <param name="format"> /// A <see cref="String"/> that specify the media format to used for saving <paramref name="image"/>. /// </param> /// <param name="criteria"> /// A <see cref="MediaCodecCriteria"/> that specify parameters for loading an image stream. /// </param> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="stream"/>, <paramref name="image"/> or <paramref name="criteria"/> is null. /// </exception> public void Save(Stream stream, Image image, string format, ImageCodecCriteria criteria) { System.Drawing.Imaging.ImageFormat bitmapFormat; System.Drawing.Imaging.PixelFormat bitmapPixelFormat; int iBitmapFlags; ConvertImageFormat(format, out bitmapFormat); ConvertPixelFormat(image.PixelLayout, out bitmapPixelFormat, out iBitmapFlags); // Obtain source and destination data pointers using (Bitmap bitmap = new Bitmap((int)image.Width, (int)image.Height, bitmapPixelFormat)) { #region Copy Image To Bitmap BitmapData iBitmapData = null; IntPtr imageData = image.ImageBuffer; try { iBitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat); // Copy Image data dst Bitmap unsafe { byte *hImageDataPtr = (byte *)imageData.ToPointer(); byte *iBitmapDataPtr = (byte *)iBitmapData.Scan0.ToPointer(); uint hImageDataStride = image.Stride; uint iBitmapDataStride = (uint)iBitmapData.Stride; // .NET Image Library stores bitmap scan line data in memory padded dst 4 bytes boundaries // .NET Image Library expect a bottom up image, so invert the scan line order iBitmapDataPtr = iBitmapDataPtr + ((image.Height - 1) * iBitmapDataStride); for (uint line = 0; line < image.Height; line++, hImageDataPtr += hImageDataStride, iBitmapDataPtr -= iBitmapDataStride) { Memory.MemoryCopy(iBitmapDataPtr, hImageDataPtr, hImageDataStride); } } } finally { if (iBitmapData != null) { bitmap.UnlockBits(iBitmapData); } } #endregion #region Support Indexed Pixel Formats if ((iBitmapFlags & (int)ImageFlags.ColorSpaceGray) != 0) { ColorPalette bitmapPalette = bitmap.Palette; switch (bitmapPixelFormat) { case System.Drawing.Imaging.PixelFormat.Format8bppIndexed: // Create grayscale palette for (int i = 0; i <= 255; i++) { bitmapPalette.Entries[i] = Color.FromArgb(i, i, i); } break; } bitmap.Palette = bitmapPalette; } #endregion // Save image with the specified format ImageCodecInfo encoderInfo = Array.Find(ImageCodecInfo.GetImageEncoders(), delegate(ImageCodecInfo item) { return(item.FormatID == bitmapFormat.Guid); }); EncoderParameters encoderParams = null; try { EncoderParameters encoderInfoParamList = bitmap.GetEncoderParameterList(encoderInfo.Clsid); EncoderParameter[] encoderInfoParams = encoderInfoParamList != null ? encoderInfoParamList.Param : null; bool supportQuality = false; int paramsCount = 0; if (encoderInfoParams != null) { Array.ForEach(encoderInfoParams, delegate(EncoderParameter item) { if (item.Encoder.Guid == Encoder.Quality.Guid) { supportQuality = true; paramsCount++; } }); } encoderParams = new EncoderParameters(paramsCount); paramsCount = 0; if (supportQuality) { encoderParams.Param[paramsCount++] = new EncoderParameter(Encoder.Quality, 100); } } catch (Exception) { // Encoder does not support parameters } bitmap.Save(stream, encoderInfo, encoderParams); } }
/// <summary> /// Dispose /// </summary> public override void Dispose() { // Release any outstanding bitmaps if (m_bmp != null) { m_bmp.UnlockBits(m_bmd); m_bmp = null; m_bmd = null; } }
private static unsafe List <System.Drawing.Point> SimilarMatch(int left, int top, int width, int height, BitmapData S_Data, BitmapData P_Data, int similar) { List <System.Drawing.Point> List = new List <System.Drawing.Point>(); int S_stride = S_Data.Stride; int P_stride = P_Data.Stride; IntPtr S_Iptr = S_Data.Scan0; IntPtr P_Iptr = P_Data.Scan0; byte * S_ptr; byte * P_ptr; bool IsOk = false; int _BreakW = width - P_Data.Width + 1; int _BreakH = height - P_Data.Height + 1; for (int h = top; h < _BreakH; h++) { for (int w = left; w < _BreakW; w++) { P_ptr = (byte *)(P_Iptr); for (int y = 0; y < P_Data.Height; y++) { for (int x = 0; x < P_Data.Width; x++) { S_ptr = (byte *)((int)S_Iptr + S_stride * (h + y) + (w + x) * 3); P_ptr = (byte *)((int)P_Iptr + P_stride * y + x * 3); if (ScanColor(S_ptr[0], S_ptr[1], S_ptr[2], P_ptr[0], P_ptr[1], P_ptr[2], similar)) //比较颜色 { IsOk = true; } else { IsOk = false; break; } } if (IsOk == false) { break; } } if (IsOk) { List.Add(new System.Drawing.Point(w, h)); } IsOk = false; } } return(List); }
/// <summary> /// 获得 BitmapData 指定坐标的颜色信息 /// </summary> /// <param name="srcData">从图像数据获得颜色 必须为 PixelFormat.Format24bppRgb 格式图像数据</param> /// <param name="x"></param> /// <param name="y"></param> /// <returns>x,y 坐标的颜色数据</returns> /// <remarks> /// Format24BppRgb 已知X,Y坐标,像素第一个元素的位置为Scan0+(Y*Stride)+(X*3)。 /// 这是blue字节的位置,接下来的2个字节分别含有green、red数据。 /// </remarks> private Color BitmapDataColorAt(BitmapData srcData, int x, int y) { byte[] rgbValues = new byte[3]; Marshal.Copy((IntPtr)((long)srcData.Scan0 + ((y * srcData.Stride) + (x * 3))), rgbValues, 0, 3); return Color.FromArgb(rgbValues[2], rgbValues[1], rgbValues[0]); }
private static unsafe List <System.Drawing.Point> OpacityDiff(int left, int top, int width, int height, BitmapData S_Data, BitmapData P_Data, int[,] PixelData, int similar) { List <System.Drawing.Point> List = new List <System.Drawing.Point>(); int Len = PixelData.GetLength(0); int S_stride = S_Data.Stride; int P_stride = P_Data.Stride; IntPtr S_Iptr = S_Data.Scan0; IntPtr P_Iptr = P_Data.Scan0; byte * S_ptr; byte * P_ptr; bool IsOk = false; int _BreakW = width - P_Data.Width + 1; int _BreakH = height - P_Data.Height + 1; for (int h = top; h < _BreakH; h++) { for (int w = left; w < _BreakW; w++) { for (int i = 0; i < Len; i++) { S_ptr = (byte *)((int)S_Iptr + S_stride * (h + PixelData[i, 1]) + (w + PixelData[i, 0]) * 3); P_ptr = (byte *)((int)P_Iptr + P_stride * PixelData[i, 1] + PixelData[i, 0] * 3); if (ScanColor(S_ptr[0], S_ptr[1], S_ptr[2], P_ptr[0], P_ptr[1], P_ptr[2], similar)) //比较颜色 { IsOk = true; } else { IsOk = false; break; } } if (IsOk) { List.Add(new System.Drawing.Point(w, h)); } IsOk = false; } } return(List); }
/// <summary> /// Lock bitmap data /// </summary> public void LockBits() { try { // Get width and height of bitmap Width = source.Width; Height = source.Height; // get total locked pixels count int PixelCount = Width * Height; // Create rectangle to lock Rectangle rect = new Rectangle(0, 0, Width, Height); // get source bitmap pixel format size Depth = System.Drawing.Bitmap.GetPixelFormatSize(source.PixelFormat); // Check if bpp (Bits Per Pixel) is 8, 24, or 32 if (Depth != 8 && Depth != 24 && Depth != 32) { throw new ArgumentException("Only 8, 24 and 32 bpp images are supported."); } // Lock bitmap and return bitmap data bitmapData = source.LockBits(rect, ImageLockMode.ReadWrite, source.PixelFormat); // create byte array to copy pixel values int step = Depth / 8; Pixels = new byte[PixelCount * step]; Iptr = bitmapData.Scan0; // Copy data from pointer to array Marshal.Copy(Iptr, Pixels, 0, Pixels.Length); } catch (Exception ex) { throw ex; } }
private static unsafe List <System.Drawing.Point> StrictMatch(int left, int top, int width, int height, BitmapData S_Data, BitmapData P_Data) { List <System.Drawing.Point> List = new List <System.Drawing.Point>(); int S_stride = S_Data.Stride; int P_stride = P_Data.Stride; IntPtr S_Iptr = S_Data.Scan0; IntPtr P_Iptr = P_Data.Scan0; byte * S_ptr; byte * P_ptr; bool IsOk = false; int _BreakW = width - P_Data.Width + 1; int _BreakH = height - P_Data.Height + 1; for (int h = top; h < _BreakH; h++) { for (int w = left; w < _BreakW; w++) { P_ptr = (byte *)(P_Iptr); // there could be a random check for quick jump the loop for (int y = 0; y < P_Data.Height; y++) { for (int x = 0; x < P_Data.Width; x++) { S_ptr = (byte *)((int)S_Iptr + S_stride * (h + y) + (w + x) * 3); P_ptr = (byte *)((int)P_Iptr + P_stride * y + x * 3); if (S_ptr[0] == P_ptr[0] && S_ptr[1] == P_ptr[1] && S_ptr[2] == P_ptr[2]) { IsOk = true; } else { IsOk = false; break; } } if (!IsOk) { break; } } if (IsOk) { List.Add(new System.Drawing.Point(w, h)); } IsOk = false; } } return(List); }
public JPGEncoder(Color[] pixels, int width, int height, float quality) { // save out texture data to our own data structure image = new BitmapData(pixels, width, height); if ( quality <= 0.0f ) quality = 1.0f; if ( quality > 100.0f ) quality = 100.0f; if ( quality < 50.0f ) sf = (int)(5000.0f / quality); else sf = (int)(200.0f - quality * 2.0f); }
public void Bitmap32bitsData() { string sInFile = getInFile("bitmaps/almogaver32bits.tif"); using (Bitmap bmp = new Bitmap(sInFile)) { BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); try { Assert.AreEqual(bmp.Height, data.Height, "Height"); Assert.AreEqual(bmp.Width, data.Width, "Width"); Assert.AreEqual(PixelFormat.Format24bppRgb, data.PixelFormat, "PixelFormat"); Assert.AreEqual(520, data.Stride, "Stride"); int size = data.Height * data.Stride; unsafe { byte *scan = (byte *)data.Scan0; #if false // 1009 is the first prime after 1000 (so we're not affected by a recurring pattern) for (int p = 0; p < size; p += 1009) { Console.WriteLine("\t\t\t\t\t\tAssert.AreEqual ({0}, *(scan + {1}), \"{1}\");", *(scan + p), p); } #else // sampling values from a well known bitmap Assert.AreEqual(217, *(scan + 0), "0"); Assert.AreEqual(192, *(scan + 1009), "1009"); Assert.AreEqual(210, *(scan + 2018), "2018"); Assert.AreEqual(196, *(scan + 3027), "3027"); Assert.AreEqual(216, *(scan + 4036), "4036"); Assert.AreEqual(215, *(scan + 5045), "5045"); Assert.AreEqual(218, *(scan + 6054), "6054"); Assert.AreEqual(218, *(scan + 7063), "7063"); Assert.AreEqual(95, *(scan + 8072), "8072"); Assert.AreEqual(9, *(scan + 9081), "9081"); Assert.AreEqual(247, *(scan + 10090), "10090"); Assert.AreEqual(161, *(scan + 11099), "11099"); Assert.AreEqual(130, *(scan + 12108), "12108"); Assert.AreEqual(131, *(scan + 13117), "13117"); Assert.AreEqual(175, *(scan + 14126), "14126"); Assert.AreEqual(217, *(scan + 15135), "15135"); Assert.AreEqual(201, *(scan + 16144), "16144"); Assert.AreEqual(183, *(scan + 17153), "17153"); Assert.AreEqual(236, *(scan + 18162), "18162"); Assert.AreEqual(242, *(scan + 19171), "19171"); Assert.AreEqual(125, *(scan + 20180), "20180"); Assert.AreEqual(193, *(scan + 21189), "21189"); Assert.AreEqual(227, *(scan + 22198), "22198"); Assert.AreEqual(44, *(scan + 23207), "23207"); Assert.AreEqual(230, *(scan + 24216), "24216"); Assert.AreEqual(224, *(scan + 25225), "25225"); Assert.AreEqual(164, *(scan + 26234), "26234"); Assert.AreEqual(43, *(scan + 27243), "27243"); Assert.AreEqual(200, *(scan + 28252), "28252"); Assert.AreEqual(255, *(scan + 29261), "29261"); Assert.AreEqual(226, *(scan + 30270), "30270"); Assert.AreEqual(230, *(scan + 31279), "31279"); Assert.AreEqual(178, *(scan + 32288), "32288"); Assert.AreEqual(224, *(scan + 33297), "33297"); Assert.AreEqual(233, *(scan + 34306), "34306"); Assert.AreEqual(212, *(scan + 35315), "35315"); Assert.AreEqual(153, *(scan + 36324), "36324"); Assert.AreEqual(143, *(scan + 37333), "37333"); Assert.AreEqual(215, *(scan + 38342), "38342"); Assert.AreEqual(116, *(scan + 39351), "39351"); Assert.AreEqual(26, *(scan + 40360), "40360"); Assert.AreEqual(28, *(scan + 41369), "41369"); Assert.AreEqual(75, *(scan + 42378), "42378"); Assert.AreEqual(50, *(scan + 43387), "43387"); Assert.AreEqual(244, *(scan + 44396), "44396"); Assert.AreEqual(191, *(scan + 45405), "45405"); Assert.AreEqual(200, *(scan + 46414), "46414"); Assert.AreEqual(197, *(scan + 47423), "47423"); Assert.AreEqual(232, *(scan + 48432), "48432"); Assert.AreEqual(186, *(scan + 49441), "49441"); Assert.AreEqual(210, *(scan + 50450), "50450"); Assert.AreEqual(215, *(scan + 51459), "51459"); Assert.AreEqual(155, *(scan + 52468), "52468"); Assert.AreEqual(56, *(scan + 53477), "53477"); Assert.AreEqual(149, *(scan + 54486), "54486"); Assert.AreEqual(137, *(scan + 55495), "55495"); Assert.AreEqual(141, *(scan + 56504), "56504"); Assert.AreEqual(36, *(scan + 57513), "57513"); Assert.AreEqual(39, *(scan + 58522), "58522"); Assert.AreEqual(25, *(scan + 59531), "59531"); Assert.AreEqual(44, *(scan + 60540), "60540"); Assert.AreEqual(12, *(scan + 61549), "61549"); Assert.AreEqual(161, *(scan + 62558), "62558"); Assert.AreEqual(179, *(scan + 63567), "63567"); Assert.AreEqual(181, *(scan + 64576), "64576"); Assert.AreEqual(165, *(scan + 65585), "65585"); Assert.AreEqual(182, *(scan + 66594), "66594"); Assert.AreEqual(186, *(scan + 67603), "67603"); Assert.AreEqual(201, *(scan + 68612), "68612"); Assert.AreEqual(49, *(scan + 69621), "69621"); Assert.AreEqual(161, *(scan + 70630), "70630"); Assert.AreEqual(140, *(scan + 71639), "71639"); Assert.AreEqual(2, *(scan + 72648), "72648"); Assert.AreEqual(15, *(scan + 73657), "73657"); Assert.AreEqual(33, *(scan + 74666), "74666"); Assert.AreEqual(17, *(scan + 75675), "75675"); Assert.AreEqual(0, *(scan + 76684), "76684"); Assert.AreEqual(47, *(scan + 77693), "77693"); Assert.AreEqual(4, *(scan + 78702), "78702"); Assert.AreEqual(142, *(scan + 79711), "79711"); Assert.AreEqual(151, *(scan + 80720), "80720"); Assert.AreEqual(124, *(scan + 81729), "81729"); Assert.AreEqual(81, *(scan + 82738), "82738"); Assert.AreEqual(214, *(scan + 83747), "83747"); Assert.AreEqual(217, *(scan + 84756), "84756"); Assert.AreEqual(30, *(scan + 85765), "85765"); Assert.AreEqual(185, *(scan + 86774), "86774"); Assert.AreEqual(200, *(scan + 87783), "87783"); Assert.AreEqual(37, *(scan + 88792), "88792"); Assert.AreEqual(2, *(scan + 89801), "89801"); Assert.AreEqual(41, *(scan + 90810), "90810"); Assert.AreEqual(16, *(scan + 91819), "91819"); Assert.AreEqual(0, *(scan + 92828), "92828"); Assert.AreEqual(146, *(scan + 93837), "93837"); Assert.AreEqual(163, *(scan + 94846), "94846"); #endif } } finally { bmp.UnlockBits(data); } } }
private void RGB2YUV(BitmapData img, int xpos, int ypos) { int pos = 0; for ( int y=0; y < 8; y++ ) { for ( int x=0; x < 8; x++ ) { Color C = img.getPixelColor(xpos + x, img.height - (ypos + y)); float R = C.r * 255.0f; float G = C.g * 255.0f; float B = C.b * 255.0f; YDU[pos] = (((0.29900f) * R + (0.58700f) * G + (0.11400f) * B)) - 128.0f; UDU[pos] = (((-0.16874f) * R + (-0.33126f) * G + (0.50000f) * B)); VDU[pos] = (((0.50000f) * R + (-0.41869f) * G + (-0.08131f) * B)); pos++; } } }
public static void Main(string[] args) { if (args.Length != 1) { usage(); } Gdal.AllRegister(); Bitmap bmp = new Bitmap(args[0]); // set up MEM driver to read bitmap data int bandCount = 1; int pixelOffset = 1; DataType dataType = DataType.GDT_Byte; switch (bmp.PixelFormat) { case PixelFormat.Format16bppGrayScale: dataType = DataType.GDT_Int16; bandCount = 1; pixelOffset = 2; break; case PixelFormat.Format24bppRgb: dataType = DataType.GDT_Byte; bandCount = 3; pixelOffset = 3; break; case PixelFormat.Format32bppArgb: dataType = DataType.GDT_Byte; bandCount = 4; pixelOffset = 4; break; case PixelFormat.Format48bppRgb: dataType = DataType.GDT_UInt16; bandCount = 3; pixelOffset = 6; break; case PixelFormat.Format64bppArgb: dataType = DataType.GDT_UInt16; bandCount = 4; pixelOffset = 8; break; default: Console.WriteLine("Invalid pixel format " + bmp.PixelFormat.ToString()); break; } // Use GDAL raster reading methods to read the image data directly into the Bitmap BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat); int stride = bitmapData.Stride; IntPtr buf = bitmapData.Scan0; try { Driver drvmem = Gdal.GetDriverByName("MEM"); // create a MEM dataset Dataset ds = drvmem.Create("", bmp.Width, bmp.Height, 0, dataType, null); // add bands in a reverse order for (int i = 1; i <= bandCount; i++) { ds.AddBand(dataType, new string[] { "DATAPOINTER=" + Convert.ToString(buf.ToInt64() + bandCount - i), "PIXELOFFSET=" + pixelOffset, "LINEOFFSET=" + stride }); } // display parameters Console.WriteLine("Raster dataset parameters:"); Console.WriteLine(" RasterCount: " + ds.RasterCount); Console.WriteLine(" RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")"); // write dataset to tif file Driver drv = Gdal.GetDriverByName("GTiff"); if (drv == null) { Console.WriteLine("Can't get driver."); System.Environment.Exit(-1); } drv.CreateCopy("sample2.tif", ds, 0, null, null, null); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { bmp.UnlockBits(bitmapData); } }