public LockedFastImage(Bitmap image) { this.image = image; Rectangle rect = new Rectangle(0, 0, image.Width, image.Height); bmpData = image.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, image.PixelFormat); ptr = bmpData.Scan0; bytes = Math.Abs(bmpData.Stride) * image.Height; rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); }
public void OpenData(System.Drawing.Imaging.ImageLockMode mode, bool flip) { this.data = this.bitmap.LockBits(new System.Drawing.Rectangle(0, 0, this.width, this.height), mode, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); unsafe { this.pixels = (byte*)this.data.Scan0; if (flip) this.pixels += this.height * this.data.Stride; } }
public BitmapData Lock() { SD.Imaging.BitmapData bd = Control.LockBits(new SD.Rectangle(0, 0, Control.Width, Control.Height), SD.Imaging.ImageLockMode.ReadWrite, Control.PixelFormat); return(new BitmapDataHandler(Widget, bd.Scan0, bd.Stride, bd.PixelFormat.BitsPerPixel(), bd)); }
private void WritingFramesWorker(object cState) { string _sWritingFramesFile = "d:/FramesDebugWriting/WritingDebugFrames.txt"; string _sWritingFramesDir = "d:/FramesDebugWriting/FFMPEG/"; int _nFramesCount = 0; System.Drawing.Bitmap cBFrame; System.Drawing.Imaging.BitmapData cFrameBD; string[] aLines; bool bQueueIsNotEmpty = false; byte[] aBytes; try { while (!_bFileEnd && !_bClose) { try { if (System.IO.File.Exists(_sWritingFramesFile)) { aLines = System.IO.File.ReadAllLines(_sWritingFramesFile); if ("ffmpeg" == aLines.FirstOrDefault(o => o.ToLower() == "ffmpeg")) { _bDoWritingFrames = true; if (!System.IO.Directory.Exists(_sWritingFramesDir)) System.IO.Directory.CreateDirectory(_sWritingFramesDir); } else _bDoWritingFrames = false; } else _bDoWritingFrames = false; if (_bDoWritingFrames || 0 < _aqWritingFrames.Count) { while (bQueueIsNotEmpty) { cBFrame = new System.Drawing.Bitmap(_cFormatVideo.nWidth, _cFormatVideo.nHeight); cFrameBD = cBFrame.LockBits(new System.Drawing.Rectangle(0, 0, cBFrame.Width, cBFrame.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); lock (_aqWritingFrames) { aBytes = _aqWritingFrames.Dequeue(); if (0 < _aqWritingFrames.Count) bQueueIsNotEmpty = true; else bQueueIsNotEmpty = false; } System.Runtime.InteropServices.Marshal.Copy(aBytes, 0, cFrameBD.Scan0, (int)_cFormatVideoTarget.nBufferSize); cBFrame.UnlockBits(cFrameBD); cBFrame.Save(_sWritingFramesDir + "frame_" + _nFramesCount.ToString("0000") + ".png"); _nFramesCount++; aLines = System.IO.File.ReadAllLines(_sWritingFramesFile); if (null == aLines.FirstOrDefault(o => o.ToLower() == "ffmpeg")) _bDoWritingFrames = false; if (3000 < _aqWritingFrames.Count) { _bDoWritingFrames = false; System.IO.File.Delete(_sWritingFramesFile); } } System.Threading.Thread.Sleep(40);//FPS if (0 < _aqWritingFrames.Count) bQueueIsNotEmpty = true; else bQueueIsNotEmpty = false; } else { lock (_aqWritingFrames) if (0 == _aqWritingFrames.Count) _nFramesCount = 0; System.Threading.Thread.Sleep(2000); } } catch (System.Threading.ThreadAbortException) { } catch (Exception ex) { (new Logger()).WriteError(ex); } } } catch (System.Threading.ThreadAbortException) { } catch (Exception ex) { (new Logger()).WriteError(ex); } }
static void decodeRle( System.Drawing.Imaging.BitmapData b, int byp, tgaCD cd, System.IO.BinaryReader br, bool bottomUp) { try { int w = b.Width; // make buffer larger, so in case of emergency I can decode // over line ends. byte[] linebuffer = new byte[(w + 128) * byp]; int maxindex = w * byp; int index = 0; for (int j = 0; j < b.Height; ++j) { while (index < maxindex) { byte blocktype = br.ReadByte(); int bytestoread; int bytestocopy; if (blocktype >= 0x80) { bytestoread = byp; bytestocopy = byp * (blocktype - 0x80); } else { bytestoread = byp * (blocktype + 1); bytestocopy = 0; } //if (index + bytestoread > maxindex) // throw new System.ArgumentException ("Corrupt TGA"); br.Read(linebuffer, index, bytestoread); index += bytestoread; for (int i = 0; i != bytestocopy; ++i) { linebuffer[index + i] = linebuffer[index + i - bytestoread]; } index += bytestocopy; } if (!bottomUp) { decodeLine(b, b.Height - j - 1, byp, linebuffer, ref cd); } else { decodeLine(b, j, byp, linebuffer, ref cd); } if (index > maxindex) { Array.Copy(linebuffer, maxindex, linebuffer, 0, index - maxindex); index -= maxindex; } else { index = 0; } } } catch (System.IO.EndOfStreamException) { } }
public static unsafe libsecondlife.Image LoadTGAImage(System.IO.Stream source, bool mask) { byte[] buffer = new byte[source.Length]; source.Read(buffer, 0, buffer.Length); System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); tgaHeader header = new tgaHeader(); header.Read(br); if (header.ImageSpec.PixelDepth != 8 && header.ImageSpec.PixelDepth != 16 && header.ImageSpec.PixelDepth != 24 && header.ImageSpec.PixelDepth != 32) { throw new ArgumentException("Not a supported tga file."); } if (header.ImageSpec.AlphaBits > 8) { throw new ArgumentException("Not a supported tga file."); } if (header.ImageSpec.Width > 4096 || header.ImageSpec.Height > 4096) { throw new ArgumentException("Image too large."); } byte[] decoded = new byte[header.ImageSpec.Width * header.ImageSpec.Height * 4]; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); fixed(byte *pdecoded = &decoded[0]) { bd.Width = header.ImageSpec.Width; bd.Height = header.ImageSpec.Height; bd.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; bd.Stride = header.ImageSpec.Width * 4; bd.Scan0 = (IntPtr)pdecoded; switch (header.ImageSpec.PixelDepth) { case 8: decodeStandard8(bd, header, br); break; case 16: if (header.ImageSpec.AlphaBits > 0) { decodeSpecial16(bd, header, br); } else { decodeStandard16(bd, header, br); } break; case 24: if (header.ImageSpec.AlphaBits > 0) { decodeSpecial24(bd, header, br); } else { decodeStandard24(bd, header, br); } break; case 32: decodeStandard32(bd, header, br); break; default: return(null); } } int n = header.ImageSpec.Width * header.ImageSpec.Height; libsecondlife.Image image; if (mask && header.ImageSpec.AlphaBits == 0 && header.ImageSpec.PixelDepth == 8) { image = new libsecondlife.Image(header.ImageSpec.Width, header.ImageSpec.Height, libsecondlife.ImageChannels.Alpha); int p = 3; for (int i = 0; i < n; i++) { image.Alpha[i] = decoded[p]; p += 4; } } else { image = new libsecondlife.Image(header.ImageSpec.Width, header.ImageSpec.Height, libsecondlife.ImageChannels.Color | libsecondlife.ImageChannels.Alpha); int p = 0; for (int i = 0; i < n; i++) { image.Blue[i] = decoded[p++]; image.Green[i] = decoded[p++]; image.Red[i] = decoded[p++]; image.Alpha[i] = decoded[p++]; } } br.Close(); return(image); }
public void Lock() { if (locked) { throw new Exception("Bitmap already locked."); } Rectangle rect = new Rectangle(0, 0, Width, Height); bmpData = Bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, Bitmap.PixelFormat); bmpPtr = bmpData.Scan0; if (IsAlphaBitmap) { int bytes = (Width * Height) * 4; rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(bmpPtr, rgbValues, 0, rgbValues.Length); } else { int bytes = (Width * Height) * 3; rgbValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(bmpPtr, rgbValues, 0, rgbValues.Length); } locked = true; }
/// <summary> /// Read an image file, covert the data and save it to the native pointer /// </summary> /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam> /// <param name="fileName">The name of the image file</param> /// <param name="dest">The native pointer where the image pixels values will be saved to.</param> /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param> /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param> /// <param name="inputMean">The mean value, it will be substracted from the input image pixel values</param> /// <param name="scale">The scale, after mean is substracted, the scale will be used to multiply the pixel values</param> /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param> /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param> public static void ReadImageFileToTensor <T>( String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { if (!File.Exists(fileName)) { throw new FileNotFoundException(String.Format("File {0} do not exist.", fileName)); } #if __ANDROID__ Android.Graphics.Bitmap bmp = BitmapFactory.DecodeFile(fileName); if (inputHeight > 0 || inputWidth > 0) { Bitmap resized = Bitmap.CreateScaledBitmap(bmp, inputWidth, inputHeight, false); bmp.Dispose(); bmp = resized; } if (flipUpSideDown) { Matrix matrix = new Matrix(); matrix.PostScale(1, -1, bmp.Width / 2, bmp.Height / 2); Bitmap flipped = Bitmap.CreateBitmap(bmp, 0, 0, bmp.Width, bmp.Height, matrix, true); bmp.Dispose(); bmp = flipped; } int[] intValues = new int[bmp.Width * bmp.Height]; float[] floatValues = new float[bmp.Width * bmp.Height * 3]; bmp.GetPixels(intValues, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } #elif __IOS__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } UIImage image = new UIImage(fileName); if (inputHeight > 0 || inputWidth > 0) { UIImage resized = image.Scale(new CGSize(inputWidth, inputHeight)); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif __UNIFIED__ if (flipUpSideDown) { throw new NotImplementedException("Flip Up Side Down is Not implemented"); } //if (swapBR) // throw new NotImplementedException("swapBR is Not implemented"); NSImage image = new NSImage(fileName); if (inputHeight > 0 || inputWidth > 0) { NSImage resized = new NSImage(new CGSize(inputWidth, inputHeight)); resized.LockFocus(); image.DrawInRect(new CGRect(0, 0, inputWidth, inputHeight), CGRect.Empty, NSCompositingOperation.SourceOver, 1.0f); resized.UnlockFocus(); image.Dispose(); image = resized; } int[] intValues = new int[(int)(image.Size.Width * image.Size.Height)]; float[] floatValues = new float[(int)(image.Size.Width * image.Size.Height * 3)]; System.Runtime.InteropServices.GCHandle handle = System.Runtime.InteropServices.GCHandle.Alloc(intValues, System.Runtime.InteropServices.GCHandleType.Pinned); using (CGImage cgimage = image.CGImage) using (CGColorSpace cspace = CGColorSpace.CreateDeviceRGB()) using (CGBitmapContext context = new CGBitmapContext( handle.AddrOfPinnedObject(), (nint)image.Size.Width, (nint)image.Size.Height, 8, (nint)image.Size.Width * 4, cspace, CGImageAlphaInfo.PremultipliedLast )) { context.DrawImage(new CGRect(new CGPoint(), image.Size), cgimage); } handle.Free(); if (swapBR) { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = ((val & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = (((val >> 16) & 0xFF) - inputMean) * scale; } } else { for (int i = 0; i < intValues.Length; ++i) { int val = intValues[i]; floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - inputMean) * scale; floatValues[i * 3 + 2] = ((val & 0xFF) - inputMean) * scale; } } if (typeof(T) == typeof(float)) { Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { //copy float to bytes byte[] byteValues = new byte[floatValues.Length]; for (int i = 0; i < floatValues.Length; i++) { byteValues[i] = (byte)floatValues[i]; } Marshal.Copy(byteValues, 0, dest, byteValues.Length); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } //System.Runtime.InteropServices.Marshal.Copy(floatValues, 0, dest, floatValues.Length); #elif UNITY_EDITOR || UNITY_IOS || UNITY_ANDROID || UNITY_STANDALONE Texture2D texture = ReadTexture2DFromFile(fileName); ReadTensorFromTexture2D <T>(texture, dest, inputHeight, inputWidth, inputMean, scale, flipUpSideDown, false); #else //if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { //Read the file using Bitmap class System.Drawing.Bitmap bmp = new Bitmap(fileName); if (inputHeight > 0 || inputWidth > 0) { //resize bmp System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight); bmp.Dispose(); bmp = newBmp; //bmp.Save("tmp.png"); } if (flipUpSideDown) { bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); } int bmpWidth = bmp.Width; int bmpHeight = bmp.Height; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); bmp.LockBits( new Rectangle(0, 0, bmpWidth, bmpHeight), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd); int stride = bd.Stride; byte[] byteValues = new byte[bmpHeight * stride]; Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length); bmp.UnlockBits(bd); if (typeof(T) == typeof(float)) { int imageSize = bmpWidth * bmpHeight; float[] floatValues = new float[imageSize * 3]; if (swapBR) { int idx = 0; int rowOffset = 0; for (int i = 0; i < bmpHeight; ++i) { int rowPtr = rowOffset; for (int j = 0; j < bmpWidth; ++j) { float b = ((float)byteValues[rowPtr++] - inputMean) * scale; float g = ((float)byteValues[rowPtr++] - inputMean) * scale; float r = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = r; floatValues[idx++] = g; floatValues[idx++] = b; } rowOffset += stride; } } else { int idx = 0; int rowOffset = 0; for (int i = 0; i < bmpHeight; ++i) { int rowPtr = rowOffset; for (int j = 0; j < bmpWidth; ++j) { floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; } rowOffset += stride; } } Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { int imageSize = bmp.Width * bmp.Height; if (swapBR) { int idx = 0; for (int i = 0; i < bmpHeight; ++i) { int offset = i * stride; for (int j = 0; j < bmpWidth; ++j) { byte b = (byte)(((float)byteValues[offset++] - inputMean) * scale); byte g = (byte)(((float)byteValues[offset++] - inputMean) * scale); byte r = (byte)(((float)byteValues[offset++] - inputMean) * scale); byteValues[idx++] = r; byteValues[idx++] = g; byteValues[idx++] = b; } } } else { int idx = 0; for (int i = 0; i < bmpHeight; ++i) { int offset = i * stride; for (int j = 0; j < bmpWidth * 3; ++j) { byteValues[idx++] = (byte)(((float)byteValues[offset++] - inputMean) * scale); } } } Marshal.Copy(byteValues, 0, dest, imageSize * 3); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } } /* * else //Unix * { * //if (flipUpSideDown) * // throw new NotImplementedException("Flip Up Side Down is Not implemented"); * * throw new NotImplementedException("Not implemented"); * }*/ #endif }
/// <summary> /// Locks this instance. /// </summary> public void Lock() { System.Threading.Monitor.Enter(displayform.bitmap); bitmapData = displayform.bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); }
public static unsafe byte[] LoadTGARaw(System.IO.Stream source) { byte[] buffer = new byte[source.Length]; source.Read(buffer, 0, buffer.Length); System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); tgaHeader header = new tgaHeader(); header.Read(br); if (header.ImageSpec.PixelDepth != 8 && header.ImageSpec.PixelDepth != 16 && header.ImageSpec.PixelDepth != 24 && header.ImageSpec.PixelDepth != 32) throw new ArgumentException("Not a supported tga file."); if (header.ImageSpec.AlphaBits > 8) throw new ArgumentException("Not a supported tga file."); if (header.ImageSpec.Width > 4096 || header.ImageSpec.Height > 4096) throw new ArgumentException("Image too large."); byte[] decoded = new byte[header.ImageSpec.Width * header.ImageSpec.Height * 4]; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); fixed (byte* pdecoded = &decoded[0]) { bd.Width = header.ImageSpec.Width; bd.Height = header.ImageSpec.Height; bd.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; bd.Stride = header.ImageSpec.Width * 4; bd.Scan0 = (IntPtr)pdecoded; switch (header.ImageSpec.PixelDepth) { case 8: decodeStandard8(bd, header, br); break; case 16: if (header.ImageSpec.AlphaBits > 0) decodeSpecial16(bd, header, br); else decodeStandard16(bd, header, br); break; case 24: if (header.ImageSpec.AlphaBits > 0) decodeSpecial24(bd, header, br); else decodeStandard24(bd, header, br); break; case 32: decodeStandard32(bd, header, br); break; default: return null; } } // swap red and blue channels (TGA is BGRA) byte tmp; for (int i = 0; i < decoded.Length; i += 4) { tmp = decoded[i]; decoded[i] = decoded[i + 2]; decoded[i + 2] = tmp; } br.Close(); return decoded; }
public static Image NoiseRemove(Image ImageValue) { Bitmap b1 = (Bitmap)ImageValue.Clone(); Bitmap b2 = (Bitmap)ImageValue.Clone(); byte val; System.Drawing.Imaging.BitmapData bmData = b1.LockBits(new Rectangle(0, 0, ImageValue.Width, ImageValue.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb); System.Drawing.Imaging.BitmapData bmData2 = b2.LockBits(new Rectangle(0, 0, b2.Width, b2.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb); int stride = bmData.Stride; System.IntPtr Scan0 = bmData.Scan0; System.IntPtr Scan02 = bmData2.Scan0; unsafe { byte *p = (byte *)(void *)Scan0; byte *p2 = (byte *)(void *)Scan02; int nOffset = stride - ImageValue.Width * 3; int nWidth = ImageValue.Width * 3; p += stride; p2 += stride; //int val; for (int y = 1; y < ImageValue.Height - 1; ++y) { p += 3; p2 += 3; for (int x = 3; x < nWidth - 3; ++x) { val = p2[0]; if (val == 0) { if ((p2 + 3)[0] == 0 || (p2 - 3)[0] == 0 || (p2 + stride)[0] == 0 || (p2 - stride)[0] == 0 || (p2 + stride + 3)[0] == val || (p2 + stride - 3)[0] == 0 || (p2 - stride - 3)[0] == 0 || (p2 + stride + 3)[0] == 0) { p[0] = val; } else { p[0] = 255; } } ++p; ++p2; } p += nOffset + 3; p2 += nOffset + 3; } } b1.UnlockBits(bmData); b2.UnlockBits(bmData2); return(b1 as Image); }
public GpStatus UnlockBits(BitmapData lockedBitmapData) { return SetStatus(NativeMethods.GdipBitmapUnlockBits( (GpBitmap)(IntPtr)nativeImage, lockedBitmapData)); }
/// <summary> /// Drawing cell grid lines (navigation lines) /// </summary> private void DrawCell() { /* * Ниже начинаеться процесс отрисовки линии * Данное решение позволяет отрисовать линии (практически) без потери производительности приложения * На момент запуска приложение использовано общее 200мб и 430мб после загрузки мира */ const int bitmapSize = 2000; const int bitmapLength = cellSize / bitmapSize; const int posCenter = (bitmapLength / 2); var size = new System.Drawing.Rectangle(0, 0, bitmapSize, bitmapSize); //Выделяем место для наших линий дабы потом их отрендерить в UI BitmapSource bsSmallBlack, bsBlackRed, bsBlackGreenHorizontal, bsBlackGreenVertical, bsBlackGreenCenter; //Подготавливаем колажи где будут нарисованы наши линии using (var blackBitmap = new Bitmap(bitmapSize, bitmapSize)) using (var smallBlackBitmap = new Bitmap(bitmapSize, bitmapSize)) using (var greenBitmapVertical = new Bitmap(bitmapSize, bitmapSize)) using (var greenBitmapHorizontal = new Bitmap(bitmapSize, bitmapSize)) using (var redBitmap = new Bitmap(bitmapSize, bitmapSize)) { var mediaColorBrushGreen = (SolidColorBrush)App.Current.Resources["OWLOSSuccess"]; System.Drawing.Color colorGreen = System.Drawing.Color.FromArgb(mediaColorBrushGreen.Color.A, mediaColorBrushGreen.Color.R, mediaColorBrushGreen.Color.G, mediaColorBrushGreen.Color.B); var mediaColorBrushRed = (SolidColorBrush)App.Current.Resources["OWLOSDanger"]; System.Drawing.Color colorRed = System.Drawing.Color.FromArgb(mediaColorBrushRed.Color.A, mediaColorBrushRed.Color.R, mediaColorBrushRed.Color.G, mediaColorBrushRed.Color.B); var mediaColorBrushBlack = (SolidColorBrush)App.Current.Resources["OWLOSInfoAlpha3"]; System.Drawing.Color colorBlack = System.Drawing.Color.FromArgb(mediaColorBrushBlack.Color.A, mediaColorBrushBlack.Color.R, mediaColorBrushBlack.Color.G, mediaColorBrushBlack.Color.B); var penGreen = new System.Drawing.Pen(colorGreen, 10); var penRed = new System.Drawing.Pen(colorRed, 6); var penBlack = new System.Drawing.Pen(colorBlack, 2); var smallPenBlack = new System.Drawing.Pen(colorBlack, .3f); //Подготавливаем почву для рисования линий using (var gSmallBlack = System.Drawing.Graphics.FromImage(smallBlackBitmap)) using (var gBlack = System.Drawing.Graphics.FromImage(blackBitmap)) using (var gRed = System.Drawing.Graphics.FromImage(redBitmap)) //Далее сам процесс отрисовки линий и координат for (int linePosition = 0; linePosition < cellSize; linePosition += cellStep) { System.Drawing.Pen drawingPen = null; System.Drawing.Graphics graphics = null; if (linePosition % 100 == 0) { TextBlock textBlock = new TextBlock(); textBlock.Text = linePosition.ToString(); textBlock.Margin = new Thickness(linePosition, 0, 0, 0); if (linePosition == cellSize / 2) { textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSSuccess"]; drawingPen = penGreen; graphics = gBlack; } else if (linePosition % 1000 == 0) { textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSDanger"]; if (linePosition < bitmapSize) { drawingPen = penRed; graphics = gRed; } } else { textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSInfo"]; if (linePosition < bitmapSize) { drawingPen = penBlack; graphics = gBlack; } } textBlock.VerticalAlignment = VerticalAlignment.Center; horisontalNavigationGrid.Children.Add(textBlock); textBlock = new TextBlock(); textBlock.Text = linePosition.ToString(); textBlock.Margin = new Thickness(0, linePosition, 0, 0); if (linePosition == cellSize / 2) { textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSSuccess"]; } else if (linePosition % 1000 == 0) { textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSDanger"]; } else { textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSInfo"]; } textBlock.HorizontalAlignment = HorizontalAlignment.Center; verticalNavigationGrid.Children.Add(textBlock); } else if (linePosition < bitmapSize) { drawingPen = smallPenBlack; graphics = gSmallBlack; } if (drawingPen != null) { var verticalBegin = new System.Drawing.Point(); var verticalEnd = new System.Drawing.Point(); var horizontalBegin = new System.Drawing.Point(); var horizontalEnd = new System.Drawing.Point(); if (drawingPen == penGreen) { //Для зелёных линий отдельно рисуем verticalBegin.X = verticalEnd.X = cellSize / 10; verticalEnd.Y = bitmapSize; horizontalBegin.Y = horizontalEnd.Y = cellSize / 10; horizontalBegin.X = 0; horizontalEnd.X = bitmapSize; using (var gGreenVertical = System.Drawing.Graphics.FromImage(greenBitmapVertical)) gGreenVertical.DrawLine(drawingPen, verticalBegin, verticalEnd); using (var gGreenHorizontal = System.Drawing.Graphics.FromImage(greenBitmapHorizontal)) gGreenHorizontal.DrawLine(drawingPen, horizontalBegin, horizontalEnd); } else { verticalBegin.X = verticalEnd.X = linePosition; verticalEnd.Y = bitmapSize; horizontalBegin.Y = horizontalEnd.Y = linePosition; horizontalBegin.X = 0; horizontalEnd.X = bitmapSize; graphics.DrawLine(drawingPen, verticalBegin, verticalEnd); graphics.DrawLine(drawingPen, horizontalBegin, horizontalEnd); } } } //Переводим из bitmap в bitmapSource System.Drawing.Imaging.BitmapData bitmapData = smallBlackBitmap.LockBits(size, System.Drawing.Imaging.ImageLockMode.ReadOnly, smallBlackBitmap.PixelFormat); bsSmallBlack = BitmapSource.Create( bitmapData.Width, bitmapData.Height, smallBlackBitmap.HorizontalResolution, smallBlackBitmap.VerticalResolution, PixelFormats.Bgra32, null, bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride); smallBlackBitmap.UnlockBits(bitmapData); //Делаем тоже самое но, предварительно рисуем их друг на друге (комбинируем/накладываем друг на друга) bsBlackRed = CombineBitmaps(size, blackBitmap, redBitmap); bsBlackGreenHorizontal = CombineBitmaps(size, blackBitmap, redBitmap, greenBitmapHorizontal); bsBlackGreenVertical = CombineBitmaps(size, blackBitmap, redBitmap, greenBitmapVertical); bsBlackGreenCenter = CombineBitmaps(size, blackBitmap, redBitmap, greenBitmapHorizontal, greenBitmapVertical); } //Рендерим уже из буфера for (int posY = 0; posY < bitmapLength; posY++) { //Поповоду virtualizingstackpanel - https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.virtualizingstackpanel?view=netframework-4.8 - В самому низу Remarks //Поле для больших линий var horizontalVirtualStackPanel = new VirtualizingStackPanel(); horizontalVirtualStackPanel.Orientation = Orientation.Horizontal; nodeLines.Children.Add(horizontalVirtualStackPanel); //Поле для маленьких линий var smallHorizontalVirtualStackPanel = new VirtualizingStackPanel(); smallHorizontalVirtualStackPanel.Orientation = Orientation.Horizontal; smallNodeLines.Children.Add(smallHorizontalVirtualStackPanel); for (int posX = 0; posX < bitmapLength; posX++) { BitmapSource bitmapSource; //Рисуем в центре if (posX == posCenter && posY == posCenter) { bitmapSource = bsBlackGreenCenter; } else //Вертикаль if (posX == posCenter) { bitmapSource = bsBlackGreenVertical; } else //Горизонталь if (posY == posCenter) { bitmapSource = bsBlackGreenHorizontal; } //Обычная отрисовка в ряд else { bitmapSource = bsBlackRed; } //Создаем UI Image где будем отображать BitmapSource big и small lines System.Windows.Controls.Image image = new System.Windows.Controls.Image { Source = bitmapSource }; horizontalVirtualStackPanel.Children.Add(image); System.Windows.Controls.Image smallImage = new System.Windows.Controls.Image { Source = bsSmallBlack }; smallHorizontalVirtualStackPanel.Children.Add(smallImage); } } horisontalNavigationGrid.Visibility = Visibility.Visible; verticalNavigationGrid.Visibility = Visibility.Visible; }
/// <summary> /// Reads a Sun Raster (.RAS) image from a stream. /// </summary> /// <param name="stream">Stream from which to read the image.</param> /// <returns>Bitmap that contains the image that was read.</returns> public static Bitmap Load(Stream stream) { BinaryReader reader = new BinaryReader(stream); UInt32 tempDword = BigEndian(reader.ReadUInt32()); if (tempDword != 0x59a66a95) { throw new ApplicationException("This is not a valid RAS file."); } int imgWidth = (int)BigEndian(reader.ReadUInt32()); int imgHeight = (int)BigEndian(reader.ReadUInt32()); int imgBpp = (int)BigEndian(reader.ReadUInt32()); UInt32 dataLength = BigEndian(reader.ReadUInt32()); UInt32 rasType = BigEndian(reader.ReadUInt32()); UInt32 mapType = BigEndian(reader.ReadUInt32()); UInt32 mapLength = BigEndian(reader.ReadUInt32()); RleReader rleReader = new RleReader(stream, rasType == 2); if ((imgWidth < 1) || (imgHeight < 1) || (imgWidth > 32767) || (imgHeight > 32767) || (mapLength > 32767)) { throw new ApplicationException("This RAS file appears to have invalid dimensions."); } if ((imgBpp != 32) && (imgBpp != 24) && (imgBpp != 8) && (imgBpp != 4) && (imgBpp != 1)) { throw new ApplicationException("Only 1, 4, 8, 24, and 32 bit images are supported."); } byte[] bmpData = new byte[imgWidth * 4 * imgHeight]; byte[] colorPalette = null; if (mapType > 0) { colorPalette = new byte[mapLength]; stream.Read(colorPalette, 0, (int)mapLength); } try { if (imgBpp == 1) { int dx = 0, dy = 0; int b, bytePtr = 0; byte val; while (dy < imgHeight) { b = rleReader.ReadByte(); if (b == -1) { break; } for (int i = 7; i >= 0; i--) { if ((b & (1 << i)) != 0) { val = 0; } else { val = 255; } bmpData[bytePtr++] = val; bmpData[bytePtr++] = val; bmpData[bytePtr++] = val; bytePtr++; dx++; if (dx == imgWidth) { dx = 0; dy++; break; } } } } else if (imgBpp == 4) { int bytePtr = 0; byte[] scanline = new byte[imgWidth + 1]; for (int dy = 0; dy < imgHeight; dy++) { int tempByte; for (int i = 0; i < imgWidth; i++) { tempByte = rleReader.ReadByte(); scanline[i++] = (byte)((tempByte >> 4) & 0xF); scanline[i] = (byte)(tempByte & 0xF); } if (imgWidth % 2 == 1) { rleReader.ReadByte(); } if ((mapType > 0) && (mapLength == 48)) { for (int dx = 0; dx < imgWidth; dx++) { bmpData[bytePtr++] = colorPalette[scanline[dx] + 32]; bmpData[bytePtr++] = colorPalette[scanline[dx] + 16]; bmpData[bytePtr++] = colorPalette[scanline[dx]]; bytePtr++; } } else { for (int dx = 0; dx < imgWidth; dx++) { bmpData[bytePtr++] = scanline[dx]; bmpData[bytePtr++] = scanline[dx]; bmpData[bytePtr++] = scanline[dx]; bytePtr++; } } } } else if (imgBpp == 8) { int bytePtr = 0; byte[] scanline = new byte[imgWidth]; for (int dy = 0; dy < imgHeight; dy++) { for (int i = 0; i < imgWidth; i++) { scanline[i] = (byte)rleReader.ReadByte(); } if (imgWidth % 2 == 1) { rleReader.ReadByte(); } if ((mapType > 0) && (mapLength == 768)) { for (int dx = 0; dx < imgWidth; dx++) { bmpData[bytePtr++] = colorPalette[scanline[dx] + 512]; bmpData[bytePtr++] = colorPalette[scanline[dx] + 256]; bmpData[bytePtr++] = colorPalette[scanline[dx]]; bytePtr++; } } else { for (int dx = 0; dx < imgWidth; dx++) { bmpData[bytePtr++] = scanline[dx]; bmpData[bytePtr++] = scanline[dx]; bmpData[bytePtr++] = scanline[dx]; bytePtr++; } } } } else if (imgBpp == 24) { int bytePtr = 0; byte[] scanline = new byte[imgWidth * 3]; for (int dy = 0; dy < imgHeight; dy++) { for (int i = 0; i < imgWidth * 3; i++) { scanline[i] = (byte)rleReader.ReadByte(); } if ((imgWidth * 3) % 2 == 1) { stream.ReadByte(); } for (int dx = 0; dx < imgWidth; dx++) { bmpData[bytePtr++] = scanline[dx * 3]; bmpData[bytePtr++] = scanline[dx * 3 + 1]; bmpData[bytePtr++] = scanline[dx * 3 + 2]; bytePtr++; } } } else if (imgBpp == 32) { int bytePtr = 0; byte[] scanline = new byte[imgWidth * 4]; for (int dy = 0; dy < imgHeight; dy++) { for (int i = 0; i < imgWidth * 4; i++) { scanline[i] = (byte)rleReader.ReadByte(); } for (int dx = 0; dx < imgWidth; dx++) { bmpData[bytePtr++] = scanline[dx * 4]; bmpData[bytePtr++] = scanline[dx * 4 + 1]; bmpData[bytePtr++] = scanline[dx * 4 + 2]; bmpData[bytePtr++] = scanline[dx * 4 + 3]; } } } } catch (Exception e) { //give a partial image in case of unexpected end-of-file System.Diagnostics.Debug.WriteLine("Error while processing RAS file: " + e.Message); } Bitmap theBitmap = new Bitmap((int)imgWidth, (int)imgHeight, System.Drawing.Imaging.PixelFormat.Format32bppRgb); System.Drawing.Imaging.BitmapData bmpBits = theBitmap.LockBits(new Rectangle(0, 0, theBitmap.Width, theBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb); System.Runtime.InteropServices.Marshal.Copy(bmpData, 0, bmpBits.Scan0, bmpData.Length); theBitmap.UnlockBits(bmpBits); return(theBitmap); }
/// <summary> /// This is a high speed rountine that converts the given jagged array of single percision floating point numbers to a .NET bitmap image object. /// </summary> /// <param name="sourceImage">A three dimensional jagged array of float with values between 0.0 and 1.0. The first dimension represents /// color plane (red, green, blue), second dimension height, and third dimension is a vector of values across the image row.</param> /// <returns>.NET bitmap image object of format 32 bit ARGB.</returns> public unsafe static Bitmap FromFloat(float[][][] sourceImage) { int h, w; byte *ptr; // the use of pointers is what makes this "unsafe" code. System.Drawing.Imaging.BitmapData bmpData = null; Bitmap destination = null; Rectangle rect; try { // create an empty bitmap of the correct size and format. destination = new Bitmap(sourceImage[0][0].GetLength(0), sourceImage[0].GetLength(0), System.Drawing.Imaging.PixelFormat.Format32bppArgb); // Lock the image in managed memory rect = new Rectangle(0, 0, destination.Width, destination.Height); bmpData = destination.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);; ptr = (byte *)bmpData.Scan0.ToPointer(); // Fill byte image from jagged array of normalized singles for (h = 0; h < destination.Height; h++) { for (w = 0; w < destination.Width; w++) { if (sourceImage.GetLength(0) >= 3) // RGB Image { *ptr++ = (byte)(sourceImage[RGBPLANE_BLUE][h][w] * 255.0F); *ptr++ = (byte)(sourceImage[RGBPLANE_GREEN][h][w] * 255.0F); *ptr++ = (byte)(sourceImage[RGBPLANE_RED][h][w] * 255.0F); *ptr++ = 255; // default for transparency number; } else if (sourceImage.GetLength(0) == 1) // Gray Scale Image { *ptr++ = (byte)(sourceImage[0][h][w] * 255.0F); *ptr++ = (byte)(sourceImage[0][h][w] * 255.0F); *ptr++ = (byte)(sourceImage[0][h][w] * 255.0F); *ptr++ = 255; } else { // Undefined Image *ptr++ = 0; *ptr++ = 0; *ptr++ = 0; *ptr++ = 255; } } } } catch (Exception ex) { throw ex; } finally { if (bmpData != null) { destination.UnlockBits(bmpData); // Unlock managed bitmap memory } } return(destination); }
/// <summary> /// This is a high speed rountine that converts the given bitmap image to a jagged array of single percision floating point numbers. /// </summary> /// <returns>Returns a three dimensional jagged array of float with values between 0.0 and 1.0. The first dimension represents /// color plane (red, green, blue), second dimension height, and third dimension is a vector of values across the image row</returns> /// <remarks></remarks> public unsafe static float[][][] ToFloat(Bitmap sourceImage) { const int colorCount = 3; float[][][] destination; int c, h, w; Rectangle rect; byte * ptr; // the use of pointers is what makes this "unsafe" code. System.Drawing.Imaging.BitmapData bmpData = null; // will hold the data about the bitmap image stored in managed memory. try { // Force the image to 32 bit ARGB memory bitmap format, lock it in manage memory, and validate that it is the type of image data expected. rect = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height); bmpData = sourceImage.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // lock it and get it's descriptor if (bmpData.Stride < 0) { throw new ApplicationException("ToSingle only works on images with a positive stride."); } if (bmpData.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb) { throw new ApplicationException("Wrong Pixel Format. ToSingle only works on 32 bit ARGB pixels."); } // Get a C style pointer to the image data ptr = (byte *)bmpData.Scan0.ToPointer(); // Create destination array (jagged array of singles) destination = new float[RGBPLANE_LENGTH][][]; // a plane for each color: red, green, blue for (c = 0; c < colorCount; c++) { destination[c] = new float[sourceImage.Height][]; for (h = 0; h < sourceImage.Height; h++) { destination[c][h] = new float[sourceImage.Width]; } } // Fill array of floating point with normalized image data. // 32 bit Memory Bitmap image data is ordered blue byte, green byte, red byte, and Alpha channel byte (transparancy). for (h = 0; h < sourceImage.Height; h++) // cross the image rows { for (w = 0; w < sourceImage.Width; w++) // cross the image columns { destination[RGBPLANE_BLUE][h][w] = *ptr++ / 255.0F; destination[RGBPLANE_GREEN][h][w] = *ptr++ / 255.0F; destination[RGBPLANE_RED][h][w] = *ptr++ / 255.0F; ptr++; // skip the transparency byte } } } catch (Exception ex) { throw ex; } finally { if (bmpData != null) { sourceImage.UnlockBits(bmpData); // Unlock the image data in managed code } } return(destination); }
private void GlControl_Load(object sender, EventArgs e) { System.Diagnostics.Debug.WriteLine("OpenGL Version " + GL.GetString(StringName.Version)); System.Diagnostics.Debug.WriteLine("Remove " + GL.GetError().ToString()); VAO = GL.GenVertexArray(); GL.BindVertexArray(VAO); // VBO = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, VBO); GL.BufferData(BufferTarget.ArrayBuffer, 6 * points.Length * sizeof(float), points, BufferUsageHint.StaticDraw); // GL.EnableVertexAttribArray(0); GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 6 * sizeof(float), 0); GL.EnableVertexAttribArray(1); GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 6 * sizeof(float), 3 * sizeof(float)); IBO = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ElementArrayBuffer, IBO); GL.BufferData(BufferTarget.ElementArrayBuffer, indices.Length * sizeof(uint), indices, BufferUsageHint.StaticDraw); _program = CompileShaders(); Bitmap bmp = new Bitmap(256, 1); int[,] defaultColors = new int[256, 3] { { 1, 0, 255 }, { 0, 4, 255 }, { 0, 4, 255 }, { 0, 9, 255 }, { 0, 14, 255 }, { 0, 19, 255 }, { 0, 24, 255 }, { 0, 24, 255 }, { 0, 29, 255 }, { 0, 34, 255 }, { 0, 39, 255 }, { 0, 44, 255 }, { 0, 44, 255 }, { 0, 49, 255 }, { 0, 54, 255 }, { 0, 59, 255 }, { 0, 64, 255 }, { 0, 64, 255 }, { 0, 69, 255 }, { 0, 74, 255 }, { 0, 79, 255 }, { 0, 84, 255 }, { 0, 84, 255 }, { 0, 89, 255 }, { 0, 94, 255 }, { 0, 99, 255 }, { 0, 104, 255 }, { 0, 104, 255 }, { 0, 109, 255 }, { 0, 114, 255 }, { 0, 119, 255 }, { 0, 124, 255 }, { 0, 124, 255 }, { 0, 128, 255 }, { 0, 133, 255 }, { 0, 138, 255 }, { 0, 143, 255 }, { 0, 143, 255 }, { 0, 148, 255 }, { 0, 153, 255 }, { 0, 158, 255 }, { 0, 163, 255 }, { 0, 163, 255 }, { 0, 168, 255 }, { 0, 173, 255 }, { 0, 178, 255 }, { 0, 183, 255 }, { 0, 183, 255 }, { 0, 188, 255 }, { 0, 193, 255 }, { 0, 198, 255 }, { 0, 203, 255 }, { 0, 203, 255 }, { 0, 208, 255 }, { 0, 213, 255 }, { 0, 218, 255 }, { 0, 223, 255 }, { 0, 223, 255 }, { 0, 228, 255 }, { 0, 233, 255 }, { 0, 238, 255 }, { 0, 243, 255 }, { 0, 243, 255 }, { 0, 248, 255 }, { 0, 253, 255 }, { 0, 255, 252 }, { 0, 255, 247 }, { 0, 255, 247 }, { 0, 255, 242 }, { 0, 255, 237 }, { 0, 255, 232 }, { 0, 255, 227 }, { 0, 255, 227 }, { 0, 255, 222 }, { 0, 255, 217 }, { 0, 255, 212 }, { 0, 255, 207 }, { 0, 255, 207 }, { 0, 255, 202 }, { 0, 255, 197 }, { 0, 255, 192 }, { 0, 255, 187 }, { 0, 255, 187 }, { 0, 255, 182 }, { 0, 255, 177 }, { 0, 255, 172 }, { 0, 255, 167 }, { 0, 255, 167 }, { 0, 255, 162 }, { 0, 255, 157 }, { 0, 255, 152 }, { 0, 255, 147 }, { 0, 255, 147 }, { 0, 255, 142 }, { 0, 255, 137 }, { 0, 255, 132 }, { 0, 255, 128 }, { 0, 255, 128 }, { 0, 255, 123 }, { 0, 255, 118 }, { 0, 255, 113 }, { 0, 255, 108 }, { 0, 255, 108 }, { 0, 255, 103 }, { 0, 255, 98 }, { 0, 255, 93 }, { 0, 255, 88 }, { 0, 255, 88 }, { 0, 255, 83 }, { 0, 255, 78 }, { 0, 255, 73 }, { 0, 255, 68 }, { 0, 255, 68 }, { 0, 255, 63 }, { 0, 255, 58 }, { 0, 255, 53 }, { 0, 255, 48 }, { 0, 255, 48 }, { 0, 255, 43 }, { 0, 255, 38 }, { 0, 255, 33 }, { 0, 255, 28 }, { 0, 255, 28 }, { 0, 255, 23 }, { 0, 255, 18 }, { 0, 255, 13 }, { 0, 255, 8 }, { 0, 255, 8 }, { 0, 255, 3 }, { 2, 255, 0 }, { 7, 255, 0 }, { 12, 255, 0 }, { 12, 255, 0 }, { 17, 255, 0 }, { 22, 255, 0 }, { 27, 255, 0 }, { 32, 255, 0 }, { 32, 255, 0 }, { 37, 255, 0 }, { 42, 255, 0 }, { 47, 255, 0 }, { 52, 255, 0 }, { 52, 255, 0 }, { 57, 255, 0 }, { 62, 255, 0 }, { 67, 255, 0 }, { 72, 255, 0 }, { 72, 255, 0 }, { 77, 255, 0 }, { 82, 255, 0 }, { 87, 255, 0 }, { 92, 255, 0 }, { 92, 255, 0 }, { 97, 255, 0 }, { 102, 255, 0 }, { 107, 255, 0 }, { 112, 255, 0 }, { 112, 255, 0 }, { 117, 255, 0 }, { 122, 255, 0 }, { 127, 255, 0 }, { 131, 255, 0 }, { 131, 255, 0 }, { 136, 255, 0 }, { 141, 255, 0 }, { 146, 255, 0 }, { 151, 255, 0 }, { 151, 255, 0 }, { 156, 255, 0 }, { 161, 255, 0 }, { 166, 255, 0 }, { 171, 255, 0 }, { 171, 255, 0 }, { 176, 255, 0 }, { 181, 255, 0 }, { 186, 255, 0 }, { 191, 255, 0 }, { 191, 255, 0 }, { 196, 255, 0 }, { 201, 255, 0 }, { 206, 255, 0 }, { 211, 255, 0 }, { 211, 255, 0 }, { 216, 255, 0 }, { 221, 255, 0 }, { 226, 255, 0 }, { 231, 255, 0 }, { 231, 255, 0 }, { 236, 255, 0 }, { 241, 255, 0 }, { 246, 255, 0 }, { 251, 255, 0 }, { 251, 255, 0 }, { 255, 254, 0 }, { 255, 249, 0 }, { 255, 244, 0 }, { 255, 239, 0 }, { 255, 239, 0 }, { 255, 234, 0 }, { 255, 229, 0 }, { 255, 224, 0 }, { 255, 219, 0 }, { 255, 219, 0 }, { 255, 214, 0 }, { 255, 209, 0 }, { 255, 204, 0 }, { 255, 199, 0 }, { 255, 199, 0 }, { 255, 194, 0 }, { 255, 189, 0 }, { 255, 184, 0 }, { 255, 179, 0 }, { 255, 179, 0 }, { 255, 174, 0 }, { 255, 169, 0 }, { 255, 164, 0 }, { 255, 159, 0 }, { 255, 159, 0 }, { 255, 154, 0 }, { 255, 149, 0 }, { 255, 144, 0 }, { 255, 139, 0 }, { 255, 139, 0 }, { 255, 134, 0 }, { 255, 129, 0 }, { 255, 125, 0 }, { 255, 120, 0 }, { 255, 120, 0 }, { 255, 115, 0 }, { 255, 110, 0 }, { 255, 105, 0 }, { 255, 100, 0 }, { 255, 100, 0 }, { 255, 95, 0 }, { 255, 90, 0 }, { 255, 85, 0 }, { 255, 80, 0 }, { 255, 80, 0 }, { 255, 75, 0 }, { 255, 70, 0 }, { 255, 65, 0 }, { 255, 60, 0 }, { 255, 60, 0 }, { 255, 55, 0 }, { 255, 50, 0 }, { 255, 45, 0 }, { 255, 40, 0 }, { 255, 40, 0 }, { 255, 35, 0 }, { 255, 30, 0 }, { 255, 25, 0 }, { 255, 20, 0 }, { 255, 20, 0 }, { 255, 15, 0 }, { 255, 10, 0 }, { 255, 5, 0 } }; for (int istep = 0; istep < 256; ++istep) { bmp.SetPixel(istep, 0, System.Drawing.Color.FromArgb(255, defaultColors[istep, 0], defaultColors[istep, 1], defaultColors[istep, 2])); } texture = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture1D, texture); GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1); GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest); GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest); GL.TexImage1D(TextureTarget.Texture1D, 0, PixelInternalFormat.Rgba, 255, 0, PixelFormat.Rgba, PixelType.UnsignedByte, IntPtr.Zero); System.Drawing.Imaging.BitmapData data = bmp.LockBits(new Rectangle(0, 0, 255, 1), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexSubImage1D(TextureTarget.Texture1D, 0, 0, 255, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); bmp.UnlockBits(data); GL.ActiveTexture(TextureUnit.Texture0); GlControl_Resize(null, null); }
public unsafe GdiVideo(Panel panel) { _panel = panel; _bitmapData = _bitmap.LockBits(_bitmapRect, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb); _bitmapPtr = (uint*)_bitmapData.Scan0.ToPointer(); _bitmap.UnlockBits(_bitmapData); for (int i = Video.VIC.X_RESOLUTION * Video.VIC.Y_RESOLUTION - 1; i >= 0; i--) { _bitmapPtr[i] = 0xffffff; } for (int i = 0; i < Video.Pallete.CvtColors.Length; i++) { byte[] c = Video.Pallete.Colors[i]; Video.Pallete.CvtColors[i] = (uint)((c[0] << 16) | (c[1] << 8) | c[2]); } }
public static Bitmap MakeBitmapFromImageRaw(AvigilonDotNet.IFrameImageRaw rawFrame) { Rectangle imageRect = new Rectangle(0, 0, rawFrame.Size.Width, rawFrame.Size.Height); switch (rawFrame.DefaultPixelFormat) { case AvigilonDotNet.PixelFormat.Gray8: { Bitmap retVal = new Bitmap( rawFrame.Size.Width, rawFrame.Size.Height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); // Define palette for 8bit grayscale System.Drawing.Imaging.ColorPalette pal = retVal.Palette; for (int ix = 0; ix < pal.Entries.Length; ++ix) { pal.Entries[ix] = System.Drawing.Color.FromArgb(ix, ix, ix); } retVal.Palette = pal; System.Drawing.Imaging.BitmapData bitmapData = retVal.LockBits( imageRect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); byte[] byteArray = rawFrame.GetAsArray( AvigilonDotNet.PixelFormat.Gray8, (ushort)bitmapData.Stride); System.Runtime.InteropServices.Marshal.Copy( byteArray, 0, bitmapData.Scan0, byteArray.Length); retVal.UnlockBits(bitmapData); return(retVal); } case AvigilonDotNet.PixelFormat.RGB24: { Bitmap retVal = new Bitmap( rawFrame.Size.Width, rawFrame.Size.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); System.Drawing.Imaging.BitmapData bitmapData = retVal.LockBits( imageRect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); byte[] byteArray = rawFrame.GetAsArray( AvigilonDotNet.PixelFormat.RGB24, (ushort)bitmapData.Stride); System.Runtime.InteropServices.Marshal.Copy( byteArray, 0, bitmapData.Scan0, byteArray.Length); retVal.UnlockBits(bitmapData); return(retVal); } case AvigilonDotNet.PixelFormat.RGB32: { Bitmap retVal = new Bitmap( rawFrame.Size.Width, rawFrame.Size.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb); System.Drawing.Imaging.BitmapData bitmapData = retVal.LockBits( imageRect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); byte[] byteArray = rawFrame.GetAsArray( AvigilonDotNet.PixelFormat.RGB32, (ushort)bitmapData.Stride); System.Runtime.InteropServices.Marshal.Copy( byteArray, 0, bitmapData.Scan0, byteArray.Length); retVal.UnlockBits(bitmapData); return(retVal); } default: return(null); } }
public void LockBits(Rectangle rect, uint flags, PixelFormat format, BitmapData lockedBitmapData) { SetStatus(GdiPlus.GdipBitmapLockBits( (GpBitmap)(IntPtr)nativeImage, rect, flags, format, lockedBitmapData)); }
/// <summary> /// /// </summary> /// <returns></returns> public IntPtr LockData() { this.bmpData = this.bitmap.LockBits(new Rectangle(0, 0, this.bitmap.Width, this.bitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); return(bmpData.Scan0); }
// --- functions --- /// <summary>Initializes the screen. A call to SDL_Init must have been made before calling this function. A call to Deinitialize must be made when terminating the program.</summary> /// <returns>Whether initializing the screen was successful.</returns> internal static bool Initialize() { if (SDL.SDL_InitSubSystem(SDL.SDL_INIT_VIDEO) != 0) { return false; } SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_RED_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_GREEN_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_BLUE_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_ALPHA_SIZE, 0); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DEPTH_SIZE, 24); SDL.SDL_GL_SetSwapInterval(Options.Current.VerticalSynchronization ? 1 : 0); if (Options.Current.AntiAliasingLevel != 0) { SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_MULTISAMPLESAMPLES, Options.Current.AntiAliasingLevel); } // --- video mode --- Width = Options.Current.FullscreenMode ? Options.Current.FullscreenWidth : Options.Current.WindowWidth; Height = Options.Current.FullscreenMode ? Options.Current.FullscreenHeight : Options.Current.WindowHeight; Fullscreen = Options.Current.FullscreenMode; SDL.SDL_WindowFlags flags = SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL/*| SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE*/ | SDL.SDL_WindowFlags.SDL_WINDOW_HIDDEN | SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE; if (Fullscreen) { flags |= SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN; } SDL.SDL_SetHint(SDL.SDL_HINT_RENDER_VSYNC, "true"); SDL.SDL_SetHint(SDL.SDL_HINT_VIDEO_ALLOW_SCREENSAVER, "false"); Window = SDL.SDL_CreateWindow(Application.ProductName, SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, Width, Height, flags); if (Window == IntPtr.Zero) { // --- not successful --- SDL.SDL_QuitSubSystem(SDL.SDL_INIT_VIDEO); return false; } GLContext = SDL.SDL_GL_CreateContext(Window); // --- set up OpenTK context tkContext = new GraphicsContext(new ContextHandle(GLContext), SDL.SDL_GL_GetProcAddress, () => new ContextHandle(SDL.SDL_GL_GetCurrentContext())); // --- set up icon --- string bitmapFile = OpenBveApi.Path.CombineFile(Program.FileSystem.DataFolder, "icon.png"); if (System.IO.File.Exists(bitmapFile)) { iconBmp = new System.Drawing.Bitmap(bitmapFile); // load file iconData = iconBmp.LockBits(new System.Drawing.Rectangle(0, 0, iconBmp.Width, iconBmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // lock data iconSurface = SDL.SDL_CreateRGBSurfaceFrom(iconData.Scan0, iconBmp.Width, iconBmp.Height, 32, iconData.Stride, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); // upload to sdl SDL.SDL_SetWindowIcon(Window, iconSurface); // use icon // free in Deinitialize() } // --- set up anisotropic filtering --- Options.Current.AnisotropicFilteringMaximum = 0; string[] extensions = GL.GetString(StringName.Extensions).Split(new []{ ' ' }); for (int i = 0; i < extensions.Length; i++) { if (extensions[i] == "GL_EXT_texture_filter_anisotropic") { float n; GL.GetFloat((GetPName)ExtTextureFilterAnisotropic.MaxTextureMaxAnisotropyExt, out n); int m = (int)Math.Round(n); Options.Current.AnisotropicFilteringMaximum = Math.Max(0, m); break; } } if (Options.Current.AnisotropicFilteringLevel <= 0) { Options.Current.AnisotropicFilteringLevel = Options.Current.AnisotropicFilteringMaximum; } else if (Options.Current.AnisotropicFilteringLevel > Options.Current.AnisotropicFilteringMaximum) { Options.Current.AnisotropicFilteringLevel = Options.Current.AnisotropicFilteringMaximum; } // --- done --- Initialized = true; return true; }
private void drawHistogramImage(int color) { // 创建bitmap等,并获得参数 long maxr = 0; long maxg = 0; long maxb = 0; long maxgray = 0; Rectangle rec = new Rectangle(0, 0, currentpic.Width, currentpic.Height); Bitmap bp = new Bitmap(currentpic.Image); System.Drawing.Imaging.BitmapData bmdata = bp.LockBits(rec, System.Drawing.Imaging.ImageLockMode.ReadOnly, bp.PixelFormat); IntPtr ptr = bmdata.Scan0;// bitmap内存起始位置 // 获得数据存储数组 byte[] pixeldata = new Byte[bmdata.Stride * bmdata.Height]; System.Runtime.InteropServices.Marshal.Copy(ptr, pixeldata, 0, bmdata.Stride * bmdata.Height); bp.UnlockBits(bmdata); // 绘制好red、green、blue、gray的色阶图 long[] Rhistodata = new long[256]; long[] Ghistodata = new long[256]; long[] Bhistodata = new long[256]; long[] Grayhistodata = new long[256]; // 得到rgb和灰色色阶图的数据 for (int i = 0; i < bp.Width; i++) { for (int j = 0; j < bp.Height; j++) { Point p = new Point(i, j); if (null == Region || Region.IsVisible(p)) { Color c = bp.GetPixel(i, j); Rhistodata[c.R]++; Ghistodata[c.G]++; Bhistodata[c.B]++; Grayhistodata[(int)(c.R + c.G + c.B) / 3]++; if (maxr < Rhistodata[c.R]) { maxr = Rhistodata[c.R]; } if (maxg < Ghistodata[c.G]) { maxg = Ghistodata[c.G]; } if (maxb < Bhistodata[c.B]) { maxb = Bhistodata[c.B]; } if (maxgray < Grayhistodata[(int)(c.R + c.G + c.B) / 3]) { maxgray = Grayhistodata[(int)(c.R + c.G + c.B) / 3]; } } } } // 根据不同模式绘图 Pen curPen = new Pen(Brushes.Black, 1); Graphics g = pictureBox1.CreateGraphics(); g.Clear(Color.White); if (color == 0) { for (int k = 0; k < 256; k++) { g.DrawLine(curPen, 20 + k, 180, 20 + k, 180 - Rhistodata[k] * 180 / maxr); } } else if (color == 1) { for (int k = 0; k < 256; k++) { g.DrawLine(curPen, 20 + k, 180, 20 + k, 180 - Ghistodata[k] * 180 / maxg); } } else if (color == 2) { for (int k = 0; k < 256; k++) { g.DrawLine(curPen, 20 + k, 180, 20 + k, 180 - Bhistodata[k] * 180 / maxb); } } else if (color == 3) { for (int k = 0; k < 256; k++) { g.DrawLine(curPen, 20 + k, 180, 20 + k, 180 - Grayhistodata[k] * 180 / maxgray); } } g.Flush(); }
/// <summary> /// Constructor /// </summary> /// <param name="maskFile">Optional mask file, use "" for no mask</param> public ScreenCapture(string maskFile) { // capture the screen capture = CaptureWindow(User32.GetDesktopWindow()); // if there is a mask file, load it and apply it to the capture if (maskFile != "") { string maskfilename = maskFile + ".png"; System.Drawing.Bitmap maskImage = System.Drawing.Image.FromFile(maskfilename) as Bitmap; // ensure mask is same dim as capture... if ((capture.Width != maskImage.Width) || (capture.Height != maskImage.Height)) { throw new System.Exception("Mask image is required to be " + capture.Width + " x " + capture.Height + " RGBA for this screen capture"); } Rectangle rectCapture = new Rectangle(0, 0, capture.Width, capture.Height); Rectangle rectMask = new Rectangle(0, 0, maskImage.Width, maskImage.Height); System.Drawing.Imaging.BitmapData dataCapture = capture.LockBits(rectCapture, System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Drawing.Imaging.BitmapData dataMask = maskImage.LockBits(rectCapture, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); IntPtr ptrCapture = dataCapture.Scan0; IntPtr ptrMask = dataMask.Scan0; int size = Math.Abs(dataCapture.Stride) * capture.Height; byte[] bitsCapture = new byte[size]; byte[] bitsMask = new byte[size]; System.Runtime.InteropServices.Marshal.Copy(ptrCapture, bitsCapture, 0, size); System.Runtime.InteropServices.Marshal.Copy(ptrMask, bitsMask, 0, size); // check each pixel of the image... if the mask is 0 for each channel, set the capture pixel to 0. for (int n = 0; n < size; n += 4) { bool clearPixel = true; for (int c = 0; c < 4; ++c) { // if any pixel of the mask is not black, do not clear the capture pixel if (bitsMask[n + c] != 0) { clearPixel = false; break; } } if (clearPixel) { bitsCapture[n] = 0; bitsCapture[n + 1] = 0; bitsCapture[n + 2] = 0; bitsCapture[n + 3] = 0; } } System.Runtime.InteropServices.Marshal.Copy(bitsCapture, 0, ptrCapture, size); System.Runtime.InteropServices.Marshal.Copy(bitsMask, 0, ptrMask, size); capture_.UnlockBits(dataCapture); maskImage.UnlockBits(dataMask); } }
/// <summary> /// Reads a Targa (.TGA) image from a stream. /// </summary> /// <param name="stream">Stream from which to read the image.</param> /// <returns>Bitmap that contains the image that was read.</returns> /// public static Bitmap Load(Stream stream) { Bitmap theBitmap = null; BinaryReader reader = new BinaryReader(stream); UInt32[] palette = null; byte[] scanline = null; byte idFieldLength = (byte)stream.ReadByte(); byte colorMap = (byte)stream.ReadByte(); byte imageType = (byte)stream.ReadByte(); UInt16 colorMapOffset = Util.LittleEndian(reader.ReadUInt16()); UInt16 colorsUsed = Util.LittleEndian(reader.ReadUInt16()); byte bitsPerColorMap = (byte)stream.ReadByte(); UInt16 xCoord = Util.LittleEndian(reader.ReadUInt16()); UInt16 yCoord = Util.LittleEndian(reader.ReadUInt16()); UInt16 imgWidth = Util.LittleEndian(reader.ReadUInt16()); UInt16 imgHeight = Util.LittleEndian(reader.ReadUInt16()); byte bitsPerPixel = (byte)stream.ReadByte(); byte imgFlags = (byte)stream.ReadByte(); if (colorMap > 1) { throw new ApplicationException("This is not a valid TGA file."); } if (idFieldLength > 0) { byte[] idBytes = new byte[idFieldLength]; stream.Read(idBytes, 0, idFieldLength); string idStr = System.Text.Encoding.ASCII.GetString(idBytes); //do something with the ID string... System.Diagnostics.Debug.WriteLine("Targa image ID: " + idStr); } //image types: //0 - No Image Data Available //1 - Uncompressed Color Image //2 - Uncompressed RGB Image //3 - Uncompressed Black & White Image //9 - Compressed Color Image //10 - Compressed RGB Image //11 - Compressed Black & White Image if ((imageType > 11) || ((imageType > 3) && (imageType < 9))) { throw new ApplicationException("This image type (" + imageType + ") is not supported."); } else if (bitsPerPixel != 8 && bitsPerPixel != 15 && bitsPerPixel != 16 && bitsPerPixel != 24 && bitsPerPixel != 32) { throw new ApplicationException("Number of bits per pixel (" + bitsPerPixel + ") is not supported."); } if (colorMap > 0) { if (bitsPerColorMap != 15 && bitsPerColorMap != 16 && bitsPerColorMap != 24 && bitsPerColorMap != 32) { throw new ApplicationException("Number of bits per color map (" + bitsPerPixel + ") is not supported."); } } byte[] bmpData = new byte[imgWidth * 4 * imgHeight]; try { if (colorMap > 0) { int paletteEntries = colorMapOffset + colorsUsed; palette = new UInt32[paletteEntries]; if (bitsPerColorMap == 24) { for (int i = colorMapOffset; i < paletteEntries; i++) { palette[i] = 0xFF000000; palette[i] |= (UInt32)(stream.ReadByte() << 16); palette[i] |= (UInt32)(stream.ReadByte() << 8); palette[i] |= (UInt32)(stream.ReadByte()); } } else if (bitsPerColorMap == 32) { for (int i = colorMapOffset; i < paletteEntries; i++) { palette[i] = 0xFF000000; palette[i] |= (UInt32)(stream.ReadByte() << 16); palette[i] |= (UInt32)(stream.ReadByte() << 8); palette[i] |= (UInt32)(stream.ReadByte()); palette[i] |= (UInt32)(stream.ReadByte() << 24); } } else if ((bitsPerColorMap == 15) || (bitsPerColorMap == 16)) { int hi, lo; for (int i = colorMapOffset; i < paletteEntries; i++) { hi = stream.ReadByte(); lo = stream.ReadByte(); palette[i] = 0xFF000000; palette[i] |= (UInt32)((hi & 0x1F) << 3) << 16; palette[i] |= (UInt32)((((lo & 0x3) << 3) + ((hi & 0xE0) >> 5)) << 3) << 8; palette[i] |= (UInt32)(((lo & 0x7F) >> 2) << 3); } } } if (imageType == 1 || imageType == 2 || imageType == 3) { scanline = new byte[imgWidth * (bitsPerPixel / 8)]; for (int y = imgHeight - 1; y >= 0; y--) { switch (bitsPerPixel) { case 8: stream.Read(scanline, 0, scanline.Length); if (imageType == 1) { for (int x = 0; x < imgWidth; x++) { bmpData[4 * (y * imgWidth + x)] = (byte)((palette[scanline[x]] >> 16) & 0XFF); bmpData[4 * (y * imgWidth + x) + 1] = (byte)((palette[scanline[x]] >> 8) & 0XFF); bmpData[4 * (y * imgWidth + x) + 2] = (byte)((palette[scanline[x]]) & 0XFF); bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; } } else if (imageType == 3) { for (int x = 0; x < imgWidth; x++) { bmpData[4 * (y * imgWidth + x)] = scanline[x]; bmpData[4 * (y * imgWidth + x) + 1] = scanline[x]; bmpData[4 * (y * imgWidth + x) + 2] = scanline[x]; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; } } break; case 15: case 16: int hi, lo; for (int x = 0; x < imgWidth; x++) { hi = stream.ReadByte(); lo = stream.ReadByte(); bmpData[4 * (y * imgWidth + x)] = (byte)((hi & 0x1F) << 3); bmpData[4 * (y * imgWidth + x) + 1] = (byte)((((lo & 0x3) << 3) + ((hi & 0xE0) >> 5)) << 3); bmpData[4 * (y * imgWidth + x) + 2] = (byte)(((lo & 0x7F) >> 2) << 3); bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; } break; case 24: stream.Read(scanline, 0, scanline.Length); for (int x = 0; x < imgWidth; x++) { bmpData[4 * (y * imgWidth + x)] = scanline[x * 3]; bmpData[4 * (y * imgWidth + x) + 1] = scanline[x * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = scanline[x * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; } break; case 32: stream.Read(scanline, 0, scanline.Length); for (int x = 0; x < imgWidth; x++) { bmpData[4 * (y * imgWidth + x)] = scanline[x * 4]; bmpData[4 * (y * imgWidth + x) + 1] = scanline[x * 4 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = scanline[x * 4 + 2]; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; // scanline[x * 4 + 3]; } break; } } } else if (imageType == 9 || imageType == 10 || imageType == 11) { int y = imgHeight - 1, x = 0, i; int bytesPerPixel = bitsPerPixel / 8; scanline = new byte[imgWidth * 4]; while (y >= 0 && stream.Position < stream.Length) { i = stream.ReadByte(); if (i < 128) { i++; switch (bitsPerPixel) { case 8: stream.Read(scanline, 0, i * bytesPerPixel); if (imageType == 9) { for (int j = 0; j < i; j++) { bmpData[4 * (y * imgWidth + x)] = (byte)((palette[scanline[j]] >> 16) & 0XFF); bmpData[4 * (y * imgWidth + x) + 1] = (byte)((palette[scanline[j]] >> 8) & 0XFF); bmpData[4 * (y * imgWidth + x) + 2] = (byte)((palette[scanline[j]]) & 0XFF); bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; x++; if (x >= imgWidth) { x = 0; y--; } } } else if (imageType == 11) { for (int j = 0; j < i; j++) { bmpData[4 * (y * imgWidth + x)] = scanline[j]; bmpData[4 * (y * imgWidth + x) + 1] = scanline[j]; bmpData[4 * (y * imgWidth + x) + 2] = scanline[j]; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; x++; if (x >= imgWidth) { x = 0; y--; } } } break; case 15: case 16: int hi, lo; for (int j = 0; j < i; j++) { hi = stream.ReadByte(); lo = stream.ReadByte(); bmpData[4 * (y * imgWidth + x)] = (byte)((hi & 0x1F) << 3); bmpData[4 * (y * imgWidth + x) + 1] = (byte)((((lo & 0x3) << 3) + ((hi & 0xE0) >> 5)) << 3); bmpData[4 * (y * imgWidth + x) + 2] = (byte)(((lo & 0x7F) >> 2) << 3); bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; x++; if (x >= imgWidth) { x = 0; y--; } } break; case 24: stream.Read(scanline, 0, i * bytesPerPixel); for (int j = 0; j < i; j++) { bmpData[4 * (y * imgWidth + x)] = scanline[j * 3]; bmpData[4 * (y * imgWidth + x) + 1] = scanline[j * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = scanline[j * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; x++; if (x >= imgWidth) { x = 0; y--; } } break; case 32: stream.Read(scanline, 0, i * bytesPerPixel); for (int j = 0; j < i; j++) { bmpData[4 * (y * imgWidth + x)] = scanline[j * 4]; bmpData[4 * (y * imgWidth + x) + 1] = scanline[j * 4 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = scanline[j * 4 + 2]; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; // scanline[j * 4 + 3]; x++; if (x >= imgWidth) { x = 0; y--; } } break; } } else { i = (i & 0x7F) + 1; int r, g, b, a; switch (bitsPerPixel) { case 8: int p = stream.ReadByte(); if (imageType == 9) { for (int j = 0; j < i; j++) { bmpData[4 * (y * imgWidth + x)] = (byte)((palette[p] >> 16) & 0XFF); bmpData[4 * (y * imgWidth + x) + 1] = (byte)((palette[p] >> 8) & 0XFF); bmpData[4 * (y * imgWidth + x) + 2] = (byte)((palette[p]) & 0XFF); bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; x++; if (x >= imgWidth) { x = 0; y--; } } } else if (imageType == 11) { for (int j = 0; j < i; j++) { bmpData[4 * (y * imgWidth + x)] = (byte)p; bmpData[4 * (y * imgWidth + x) + 1] = (byte)p; bmpData[4 * (y * imgWidth + x) + 2] = (byte)p; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; x++; if (x >= imgWidth) { x = 0; y--; } } } break; case 15: case 16: int hi = stream.ReadByte(); int lo = stream.ReadByte(); for (int j = 0; j < i; j++) { bmpData[4 * (y * imgWidth + x)] = (byte)((hi & 0x1F) << 3); bmpData[4 * (y * imgWidth + x) + 1] = (byte)((((lo & 0x3) << 3) + ((hi & 0xE0) >> 5)) << 3); bmpData[4 * (y * imgWidth + x) + 2] = (byte)(((lo & 0x7F) >> 2) << 3); bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; x++; if (x >= imgWidth) { x = 0; y--; } } break; case 24: r = stream.ReadByte(); g = stream.ReadByte(); b = stream.ReadByte(); for (int j = 0; j < i; j++) { bmpData[4 * (y * imgWidth + x)] = (byte)r; bmpData[4 * (y * imgWidth + x) + 1] = (byte)g; bmpData[4 * (y * imgWidth + x) + 2] = (byte)b; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; x++; if (x >= imgWidth) { x = 0; y--; } } break; case 32: r = stream.ReadByte(); g = stream.ReadByte(); b = stream.ReadByte(); a = stream.ReadByte(); for (int j = 0; j < i; j++) { bmpData[4 * (y * imgWidth + x)] = (byte)r; bmpData[4 * (y * imgWidth + x) + 1] = (byte)g; bmpData[4 * (y * imgWidth + x) + 2] = (byte)b; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; // (byte)a; x++; if (x >= imgWidth) { x = 0; y--; } } break; } } } } } catch (Exception e) { //give a partial image in case of unexpected end-of-file System.Diagnostics.Debug.WriteLine("Error while processing TGA file: " + e.Message); } theBitmap = new Bitmap((int)imgWidth, (int)imgHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Drawing.Imaging.BitmapData bmpBits = theBitmap.LockBits(new Rectangle(0, 0, theBitmap.Width, theBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Runtime.InteropServices.Marshal.Copy(bmpData, 0, bmpBits.Scan0, imgWidth * 4 * imgHeight); theBitmap.UnlockBits(bmpBits); int imgOrientation = (imgFlags >> 4) & 0x3; if (imgOrientation == 1) { theBitmap.RotateFlip(RotateFlipType.RotateNoneFlipX); } else if (imgOrientation == 2) { theBitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); } else if (imgOrientation == 3) { theBitmap.RotateFlip(RotateFlipType.RotateNoneFlipXY); } return(theBitmap); }
public void UnlockBits(BitmapData lockedBitmapData) { SetStatus(GdiPlus.GdipBitmapUnlockBits( (GpBitmap)(IntPtr)nativeImage, lockedBitmapData)); }
/// <summary> /// Reads a PCX image from a stream. /// </summary> /// <param name="stream">Stream from which to read the image.</param> /// <returns>Bitmap that contains the image that was read.</returns> public static Bitmap Load(Stream stream) { BinaryReader reader = new BinaryReader(stream); byte tempByte = (byte)stream.ReadByte(); if (tempByte != 10) { throw new ApplicationException("This is not a valid PCX file."); } tempByte = (byte)stream.ReadByte(); if (tempByte < 3 || tempByte > 5) { throw new ApplicationException("Only Version 3, 4, and 5 PCX files are supported."); } tempByte = (byte)stream.ReadByte(); if (tempByte != 1) { throw new ApplicationException("Invalid PCX compression type."); } int imgBpp = stream.ReadByte(); if (imgBpp != 8 && imgBpp != 4 && imgBpp != 2 && imgBpp != 1) { throw new ApplicationException("Only 8, 4, 2, and 1-bit PCX samples are supported."); } UInt16 xmin = Util.LittleEndian(reader.ReadUInt16()); UInt16 ymin = Util.LittleEndian(reader.ReadUInt16()); UInt16 xmax = Util.LittleEndian(reader.ReadUInt16()); UInt16 ymax = Util.LittleEndian(reader.ReadUInt16()); int imgWidth = xmax - xmin + 1; int imgHeight = ymax - ymin + 1; if ((imgWidth < 1) || (imgHeight < 1) || (imgWidth > 32767) || (imgHeight > 32767)) { throw new ApplicationException("This PCX file appears to have invalid dimensions."); } Util.LittleEndian(reader.ReadUInt16()); //hdpi Util.LittleEndian(reader.ReadUInt16()); //vdpi byte[] colorPalette = new byte[48]; stream.Read(colorPalette, 0, 48); stream.ReadByte(); int numPlanes = stream.ReadByte(); int bytesPerLine = Util.LittleEndian(reader.ReadUInt16()); if (bytesPerLine == 0) { bytesPerLine = xmax - xmin + 1; } /* * HACK: Set the following parameter to true if you want to interpret the bit plane data as literal color states, * instead of indices into the palette. This was done by certain older versions of PaintBrush in EGA mode. * If the colors in your decoded picture look weird, try tweaking this setting. */ bool bitPlanesLiteral = false; // TODO: use this for something? It doesn't seem to be consistent or meaningful between different versions. Util.LittleEndian(reader.ReadUInt16()); if (imgBpp == 8 && numPlanes == 1) { colorPalette = new byte[768]; stream.Seek(-768, SeekOrigin.End); stream.Read(colorPalette, 0, 768); } //fix color palette if it's a 1-bit image, and there's no palette information if (imgBpp == 1) { if ((colorPalette[0] == colorPalette[3]) && (colorPalette[1] == colorPalette[4]) && (colorPalette[2] == colorPalette[5])) { colorPalette[0] = colorPalette[1] = colorPalette[2] = 0; colorPalette[3] = colorPalette[4] = colorPalette[5] = 0xFF; } } byte[] bmpData = new byte[(imgWidth + 1) * 4 * imgHeight]; stream.Seek(128, SeekOrigin.Begin); int x, y, i; RleReader rleReader = new RleReader(stream); try { if (imgBpp == 1) { int b, p; byte val; byte[] scanline = new byte[bytesPerLine]; byte[] realscanline = new byte[bytesPerLine * 8]; for (y = 0; y < imgHeight; y++) { //add together all the planes... Array.Clear(realscanline, 0, realscanline.Length); for (p = 0; p < numPlanes; p++) { x = 0; for (i = 0; i < bytesPerLine; i++) { scanline[i] = (byte)rleReader.ReadByte(); for (b = 7; b >= 0; b--) { if ((scanline[i] & (1 << b)) != 0) { val = 1; } else { val = 0; } realscanline[x] |= (byte)(val << p); x++; } } } for (x = 0; x < imgWidth; x++) { i = realscanline[x]; if (numPlanes == 1) { bmpData[4 * (y * imgWidth + x)] = (byte)((i & 1) != 0 ? 0xFF : 0); bmpData[4 * (y * imgWidth + x) + 1] = (byte)((i & 1) != 0 ? 0xFF : 0); bmpData[4 * (y * imgWidth + x) + 2] = (byte)((i & 1) != 0 ? 0xFF : 0); } else { if (bitPlanesLiteral) { bmpData[4 * (y * imgWidth + x)] = (byte)((i & 1) != 0 ? 0xFF : 0); bmpData[4 * (y * imgWidth + x) + 1] = (byte)((i & 2) != 0 ? 0xFF : 0); bmpData[4 * (y * imgWidth + x) + 2] = (byte)((i & 4) != 0 ? 0xFF : 0); } else { bmpData[4 * (y * imgWidth + x)] = colorPalette[i * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 1] = colorPalette[i * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = colorPalette[i * 3]; } } } } } else { if (numPlanes == 1) { if (imgBpp == 8) { byte[] scanline = new byte[bytesPerLine]; for (y = 0; y < imgHeight; y++) { for (i = 0; i < bytesPerLine; i++) { scanline[i] = (byte)rleReader.ReadByte(); } for (x = 0; x < imgWidth; x++) { i = scanline[x]; bmpData[4 * (y * imgWidth + x)] = colorPalette[i * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 1] = colorPalette[i * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = colorPalette[i * 3]; } } } else if (imgBpp == 4) { byte[] scanline = new byte[bytesPerLine]; for (y = 0; y < imgHeight; y++) { for (i = 0; i < bytesPerLine; i++) { scanline[i] = (byte)rleReader.ReadByte(); } for (x = 0; x < imgWidth; x++) { i = scanline[x / 2]; bmpData[4 * (y * imgWidth + x)] = colorPalette[((i >> 4) & 0xF) * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 1] = colorPalette[((i >> 4) & 0xF) * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = colorPalette[((i >> 4) & 0xF) * 3]; x++; bmpData[4 * (y * imgWidth + x)] = colorPalette[(i & 0xF) * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 1] = colorPalette[(i & 0xF) * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = colorPalette[(i & 0xF) * 3]; } } } else if (imgBpp == 2) { byte[] scanline = new byte[bytesPerLine]; for (y = 0; y < imgHeight; y++) { for (i = 0; i < bytesPerLine; i++) { scanline[i] = (byte)rleReader.ReadByte(); } for (x = 0; x < imgWidth; x++) { i = scanline[x / 4]; bmpData[4 * (y * imgWidth + x)] = colorPalette[((i >> 6) & 0x3) * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 1] = colorPalette[((i >> 6) & 0x3) * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = colorPalette[((i >> 6) & 0x3) * 3]; x++; bmpData[4 * (y * imgWidth + x)] = colorPalette[((i >> 4) & 0x3) * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 1] = colorPalette[((i >> 4) & 0x3) * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = colorPalette[((i >> 4) & 0x3) * 3]; x++; bmpData[4 * (y * imgWidth + x)] = colorPalette[((i >> 2) & 0x3) * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 1] = colorPalette[((i >> 2) & 0x3) * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = colorPalette[((i >> 2) & 0x3) * 3]; x++; bmpData[4 * (y * imgWidth + x)] = colorPalette[(i & 0x3) * 3 + 2]; bmpData[4 * (y * imgWidth + x) + 1] = colorPalette[(i & 0x3) * 3 + 1]; bmpData[4 * (y * imgWidth + x) + 2] = colorPalette[(i & 0x3) * 3]; } } } } else if (numPlanes == 3) { byte[] scanlineR = new byte[bytesPerLine]; byte[] scanlineG = new byte[bytesPerLine]; byte[] scanlineB = new byte[bytesPerLine]; int bytePtr = 0; for (y = 0; y < imgHeight; y++) { for (i = 0; i < bytesPerLine; i++) { scanlineR[i] = (byte)rleReader.ReadByte(); } for (i = 0; i < bytesPerLine; i++) { scanlineG[i] = (byte)rleReader.ReadByte(); } for (i = 0; i < bytesPerLine; i++) { scanlineB[i] = (byte)rleReader.ReadByte(); } for (int n = 0; n < imgWidth; n++) { bmpData[bytePtr++] = scanlineB[n]; bmpData[bytePtr++] = scanlineG[n]; bmpData[bytePtr++] = scanlineR[n]; bytePtr++; } } } }//bpp } catch (Exception e) { //give a partial image in case of unexpected end-of-file System.Diagnostics.Debug.WriteLine("Error while processing PCX file: " + e.Message); } var bmp = new Bitmap(imgWidth, imgHeight, System.Drawing.Imaging.PixelFormat.Format32bppRgb); System.Drawing.Imaging.BitmapData bmpBits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb); System.Runtime.InteropServices.Marshal.Copy(bmpData, 0, bmpBits.Scan0, imgWidth * 4 * imgHeight); bmp.UnlockBits(bmpBits); return(bmp); }
public static System.Drawing.Bitmap LoadTGA(System.IO.Stream source) { byte[] buffer = new byte[source.Length]; source.Read(buffer, 0, buffer.Length); System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); tgaHeader header = new tgaHeader(); header.Read(br); if (header.ImageSpec.PixelDepth != 8 && header.ImageSpec.PixelDepth != 16 && header.ImageSpec.PixelDepth != 24 && header.ImageSpec.PixelDepth != 32) { throw new ArgumentException("Not a supported tga file."); } if (header.ImageSpec.AlphaBits > 8) { throw new ArgumentException("Not a supported tga file."); } if (header.ImageSpec.Width > 4096 || header.ImageSpec.Height > 4096) { throw new ArgumentException("Image too large."); } System.Drawing.Bitmap b = new System.Drawing.Bitmap( header.ImageSpec.Width, header.ImageSpec.Height); System.Drawing.Imaging.BitmapData bd = b.LockBits(new System.Drawing.Rectangle(0, 0, b.Width, b.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); switch (header.ImageSpec.PixelDepth) { case 8: decodeStandard8(bd, header, br); break; case 16: if (header.ImageSpec.AlphaBits > 0) { decodeSpecial16(bd, header, br); } else { decodeStandard16(bd, header, br); } break; case 24: if (header.ImageSpec.AlphaBits > 0) { decodeSpecial24(bd, header, br); } else { decodeStandard24(bd, header, br); } break; case 32: decodeStandard32(bd, header, br); break; default: b.UnlockBits(bd); b.Dispose(); return(null); } b.UnlockBits(bd); br.Close(); return(b); }
/// <summary> /// Covert the Bitmap data and save it to the native pointer /// </summary> /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam> /// <param name="bmp">The Bitmap to convert to tensor</param> /// <param name="dest">The native pointer where the image pixels values will be saved to.</param> /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param> /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param> /// <param name="inputMean">The mean value, it will be subtracted from the input image pixel values</param> /// <param name="scale">The scale, after mean is subtracted, the scale will be used to multiply the pixel values</param> /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param> /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param> public static int ReadBitmapToTensor <T>( Bitmap bmp, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { if (inputHeight > 0 && inputWidth > 0 && ((inputHeight != bmp.Height) || (inputWidth != bmp.Width))) { //resize bmp System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight); bmp.Dispose(); bmp = newBmp; } int bmpWidth = bmp.Width; int bmpHeight = bmp.Height; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); bmp.LockBits( new Rectangle(0, 0, bmpWidth, bmpHeight), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd); try { if (typeof(T) == typeof(float)) { return(Emgu.TF.Util.Toolbox.Pixel24ToPixelFloat( bd.Scan0, bmpWidth, bmpHeight, inputMean, scale, flipUpSideDown, swapBR, dest )); } else if (typeof(T) == typeof(byte)) { return(Emgu.TF.Util.Toolbox.Pixel24ToPixelByte( bd.Scan0, bmpWidth, bmpHeight, inputMean, scale, flipUpSideDown, swapBR, dest )); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } } finally { bmp.UnlockBits(bd); } }
/// <summary> /// /// </summary> /// <param name="bitmap"></param> public ManagedImage(System.Drawing.Bitmap bitmap) { Width = bitmap.Width; Height = bitmap.Height; int pixelCount = Width * Height; if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) { Channels = ImageChannels.Alpha | ImageChannels.Color; Red = new byte[pixelCount]; Green = new byte[pixelCount]; Blue = new byte[pixelCount]; Alpha = new byte[pixelCount]; System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); unsafe { byte *pixel = (byte *)bd.Scan0; for (int i = 0; i < pixelCount; i++) { // GDI+ gives us BGRA and we need to turn that in to RGBA Blue[i] = *(pixel++); Green[i] = *(pixel++); Red[i] = *(pixel++); Alpha[i] = *(pixel++); } } bitmap.UnlockBits(bd); } else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format16bppGrayScale) { Channels = ImageChannels.Gray; Red = new byte[pixelCount]; throw new NotImplementedException("16bpp grayscale image support is incomplete"); } else if (bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb) { Channels = ImageChannels.Color; Red = new byte[pixelCount]; Green = new byte[pixelCount]; Blue = new byte[pixelCount]; System.Drawing.Imaging.BitmapData bd = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, Width, Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); unsafe { byte *pixel = (byte *)bd.Scan0; for (int i = 0; i < pixelCount; i++) { // GDI+ gives us BGR and we need to turn that in to RGB Blue[i] = *(pixel++); Green[i] = *(pixel++); Red[i] = *(pixel++); } } bitmap.UnlockBits(bd); } else { throw new NotSupportedException("Unrecognized pixel format: " + bitmap.PixelFormat.ToString()); } }
protected override void OnPaint(PaintEventArgs e) { if (useDirectX && directXAvailable) { surfRect = displaySurface.LockRectangle(screenRect, LockFlags.None); lock (ziggyWin.zx) { surfRect.Data.WriteRange <int>(ziggyWin.zx.ScreenBuffer, 0, (ScreenWidth) * (ScreenHeight)); } displaySurface.UnlockRectangle(); dxDevice.BeginScene(); sprite.Begin(SpriteFlags.None); if (!pixelSmoothing) { dxDevice.SetSamplerState(0, SamplerState.MinFilter, 0); dxDevice.SetSamplerState(0, SamplerState.MagFilter, 0); } sprite.Draw(dxDisplay, displayRect, System.Drawing.Color.White); sprite.End(); if (showScanlines) { interlaceSprite.Begin(SpriteFlags.AlphaBlend); dxDevice.SetSamplerState(0, SamplerState.AddressU, TextureAddress.Wrap); dxDevice.SetSamplerState(0, SamplerState.AddressV, TextureAddress.Wrap); interlaceSprite.Draw(interlaceOverlay2, displayRect, System.Drawing.Color.White); interlaceSprite.End(); } dxDevice.EndScene(); SlimDX.Result deviceState = dxDevice.TestCooperativeLevel(); if (deviceState == ResultCode.DeviceLost) { System.Threading.Thread.Sleep(1); return; } else if (deviceState == ResultCode.DeviceNotReset) { SetSize(Width, Height); return; } dxDevice.Present(); } else { System.Drawing.Imaging.BitmapData bmpData = gdiDisplay.LockBits( screenRect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb); //Copy the data from the byte array into BitmapData.Scan0 lock (ziggyWin.zx) { System.Runtime.InteropServices.Marshal.Copy(ziggyWin.zx.ScreenBuffer, 0, bmpData.Scan0, (ScreenWidth) * (ScreenHeight)); } //Unlock the pixels gdiDisplay.UnlockBits(bmpData); System.IntPtr hdc = e.Graphics.GetHdc(); System.IntPtr hbmp = gdiDisplay.GetHbitmap(); System.IntPtr memdc = CreateCompatibleDC(hdc); SelectObject(memdc, hbmp); StretchBlt(hdc, 0, 0, this.Width, this.Height, memdc, 0, 0, ScreenWidth, ScreenHeight, 0xCC0020); e.Graphics.ReleaseHdc(hdc); DeleteObject(hbmp); DeleteDC(memdc); } if (ziggyWin.config.ShowOnscreenIndicators) { if (ziggyWin.showTapeIndicator) { e.Graphics.DrawImage(tapeIcon, ledIndicatorPos.X - tapeIcon.Width - 10, ledIndicatorPos.Y - tapeIcon.Height - 10, tapeIcon.Width, tapeIcon.Height); } if (ziggyWin.showDiskIndicator) { e.Graphics.DrawImage(diskIcon, ledIndicatorPos.X - diskIcon.Width - 10, ledIndicatorPos.Y - diskIcon.Height - 10, diskIcon.Width, diskIcon.Height); } if (ziggyWin.showDownloadIndicator) { e.Graphics.DrawImage(downloadIcon, ledIndicatorPos.X - downloadIcon.Width - 32, ledIndicatorPos.Y - downloadIcon.Height - 10, downloadIcon.Width, downloadIcon.Height); } } isRendering = false; }
/// <summary> /// Convert GVM to PVM. /// </summary> static void GVM2PVM(string[] args) { filePath = args[1]; if (args.Length > 2 && args[2] == "-prs") { compressPRS = true; } Console.WriteLine("Converting GVM to PVM: {0}", filePath); directoryName = Path.GetDirectoryName(filePath); extension = Path.GetExtension(filePath).ToLowerInvariant(); if (!File.Exists(filePath)) { Console.WriteLine("Supplied GVM archive does not exist!"); Console.WriteLine("Press ENTER to exit."); Console.ReadLine(); return; } if (extension != ".gvm") { Console.WriteLine("GVM2PVM mode can only be used with GVM files."); Console.WriteLine("Press ENTER to exit."); Console.ReadLine(); return; } fileNameFromFolder = Path.Combine(directoryName, Path.GetFileNameWithoutExtension(filePath)); Directory.CreateDirectory(fileNameFromFolder); using (TextWriter texList = File.CreateText(Path.Combine(fileNameFromFolder, Path.GetFileName(fileNameFromFolder) + ".txt"))) { try { PuyoFile gvmFile = new PuyoFile(File.ReadAllBytes(filePath)); PuyoFile pvmFile = new PuyoFile(); outputPath = Path.ChangeExtension(filePath, ".pvm"); foreach (GVMEntry file in gvmFile.Entries) { if (!File.Exists(Path.Combine(fileNameFromFolder, file.Name))) { File.WriteAllBytes(Path.Combine(fileNameFromFolder, file.Name), file.Data); } Stream data = File.Open(Path.Combine(fileNameFromFolder, file.Name), FileMode.Open); VrTexture vrfile = new GvrTexture(data); Bitmap tempTexture = vrfile.ToBitmap(); System.Drawing.Imaging.BitmapData bmpd = tempTexture.LockBits(new Rectangle(Point.Empty, tempTexture.Size), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); int stride = bmpd.Stride; byte[] bits = new byte[Math.Abs(stride) * bmpd.Height]; System.Runtime.InteropServices.Marshal.Copy(bmpd.Scan0, bits, 0, bits.Length); tempTexture.UnlockBits(bmpd); int tlevels = 0; for (int y = 0; y < tempTexture.Height; y++) { int srcaddr = y * Math.Abs(stride); for (int x = 0; x < tempTexture.Width; x++) { Color c = Color.FromArgb(BitConverter.ToInt32(bits, srcaddr + (x * 4))); if (c.A == 0) { tlevels = 1; } else if (c.A < 255) { tlevels = 2; break; } } if (tlevels == 2) { break; } } PvrPixelFormat ppf = PvrPixelFormat.Rgb565; if (tlevels == 1) { ppf = PvrPixelFormat.Argb1555; } else if (tlevels == 2) { ppf = PvrPixelFormat.Argb4444; } PvrDataFormat pdf; if (!vrfile.HasMipmaps) { if (tempTexture.Width == tempTexture.Height) { pdf = PvrDataFormat.SquareTwiddled; } else { pdf = PvrDataFormat.Rectangle; } } else { if (tempTexture.Width == tempTexture.Height) { pdf = PvrDataFormat.SquareTwiddledMipmaps; } else { pdf = PvrDataFormat.RectangleTwiddled; } } PvrTextureEncoder encoder = new PvrTextureEncoder(tempTexture, ppf, pdf); encoder.GlobalIndex = vrfile.GlobalIndex; string pvrPath = Path.ChangeExtension(Path.Combine(fileNameFromFolder, file.Name), ".pvr"); if (!File.Exists(pvrPath)) { encoder.Save(pvrPath); } data.Close(); File.Delete(Path.Combine(fileNameFromFolder, file.Name)); MemoryStream readfile = new MemoryStream(File.ReadAllBytes(pvrPath)); pvmFile.Entries.Add(new PVMEntry(pvrPath)); texList.WriteLine(Path.GetFileName(pvrPath)); Console.WriteLine("Adding texture {0}", pvrPath); } File.WriteAllBytes(outputPath, pvmFile.GetBytes()); texList.Flush(); texList.Close(); } catch (Exception ex) { Console.WriteLine("Exception thrown: {0}", ex.ToString()); Console.WriteLine("Press ENTER to exit."); Console.ReadLine(); return; } } if (compressPRS) { outputPath = Path.ChangeExtension(filePath, ".PVM.PRS"); Console.WriteLine("Compressing to PRS..."); byte[] pvmdata = File.ReadAllBytes(Path.ChangeExtension(filePath, ".pvm")); pvmdata = FraGag.Compression.Prs.Compress(pvmdata); File.WriteAllBytes(outputPath, pvmdata); File.Delete(Path.ChangeExtension(filePath, ".PVM")); } Console.WriteLine("Output file: {0}", Path.GetFullPath(outputPath)); Console.WriteLine("Archive converted!"); Directory.Delete(fileNameFromFolder, true); }
private Renderable.ImageLayer CreateImageLayer(double north, double south, double west, double east, DrawArgs drawArgs, string imagePath) { Bitmap b = null; Graphics g = null; Renderable.ImageLayer imageLayer = null; GeographicBoundingBox geoBB = new GeographicBoundingBox(north, south, west, east); int numberPolygonsInTile = 0; FileInfo imageFile = new FileInfo(imagePath); if (!m_parentProjectedLayer.EnableCaching || !imageFile.Exists ) { if (m_parentProjectedLayer.LineStrings != null) { for (int i = 0; i < m_parentProjectedLayer.LineStrings.Length; i++) { if (!m_parentProjectedLayer.LineStrings[i].Visible) { continue; } GeographicBoundingBox currentBoundingBox = m_parentProjectedLayer.LineStrings[i].GetGeographicBoundingBox(); if (currentBoundingBox != null && !currentBoundingBox.Intersects(geoBB)) { continue; } else { if (b == null) { b = new Bitmap( m_parentProjectedLayer.TileSize.Width, m_parentProjectedLayer.TileSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); } if (g == null) { g = Graphics.FromImage(b); } drawLineString( m_parentProjectedLayer.LineStrings[i], g, geoBB, b.Size ); numberPolygonsInTile++; } } } if (m_parentProjectedLayer.Polygons != null) { for (int i = 0; i < m_parentProjectedLayer.Polygons.Length; i++) { if (!m_parentProjectedLayer.Polygons[i].Visible) { continue; } GeographicBoundingBox currentBoundingBox = m_parentProjectedLayer.Polygons[i].GetGeographicBoundingBox(); if (currentBoundingBox != null && !currentBoundingBox.Intersects(geoBB)) { continue; } else { if (b == null) { b = new Bitmap( m_parentProjectedLayer.TileSize.Width, m_parentProjectedLayer.TileSize.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); } if (g == null) { g = Graphics.FromImage(b); } drawPolygon( m_parentProjectedLayer.Polygons[i], g, geoBB, b.Size); numberPolygonsInTile++; } } } } if (b != null) { System.Drawing.Imaging.BitmapData srcInfo = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); bool isBlank = true; unsafe { int *srcPointer = (int *)srcInfo.Scan0; for (int i = 0; i < b.Height; i++) { for (int j = 0; j < b.Width; j++) { int color = *srcPointer++; if (((color >> 24) & 0xff) > 0) { isBlank = false; break; } } srcPointer += (srcInfo.Stride >> 2) - b.Width; } } b.UnlockBits(srcInfo); if (isBlank) { numberPolygonsInTile = 0; } } // if(!m_parentProjectedLayer.EnableCaching) // { string id = System.DateTime.Now.Ticks.ToString(); if (b != null && numberPolygonsInTile > 0) { MemoryStream ms = new MemoryStream(); b.Save(ms, System.Drawing.Imaging.ImageFormat.Png); //must copy original stream into new stream, if not, error occurs, not sure why m_ImageStream = new MemoryStream(ms.GetBuffer()); imageLayer = new MFW3D.Renderable.ImageLayer( id, m_parentProjectedLayer.World, 0, m_ImageStream, System.Drawing.Color.Black.ToArgb(), (float)south, (float)north, (float)west, (float)east, 1.0f //(float)m_parentProjectedLayer.Opacity / 255.0f , m_parentProjectedLayer.World.TerrainAccessor); ms.Close(); } /* } * else if(imageFile.Exists || numberPolygonsInTile > 0) * { * string id = System.DateTime.Now.Ticks.ToString(); * * if(b != null) * { * MemoryStream ms = new MemoryStream(); * b.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); * if(!imageFile.Directory.Exists) * imageFile.Directory.Create(); * * //must copy original stream into new stream, if not, error occurs, not sure why * m_ImageStream = new MemoryStream(ms.GetBuffer()); * ImageHelper.ConvertToDxt3(m_ImageStream, imageFile.FullName); * * ms.Close(); * } * * imageLayer = new WorldWind.Renderable.ImageLayer( * id, * m_parentProjectedLayer.World, * 0, * imageFile.FullName, * //System.Drawing.Color.Black.ToArgb(), * (float)south, * (float)north, * (float)west, * (float)east, * 1.0f,//(float)m_parentProjectedLayer.Opacity / 255.0f, * m_parentProjectedLayer.World.TerrainAccessor); * * imageLayer.TransparentColor = System.Drawing.Color.Black.ToArgb(); * } */ if (b != null) { b.Dispose(); } if (g != null) { g.Dispose(); } b = null; g = null; //might not be necessary //GC.Collect(); return(imageLayer); }
public GpStatus LockBits( GpRect rect, uint flags, PixelFormat format, BitmapData lockedBitmapData ) { return SetStatus(NativeMethods.GdipBitmapLockBits( (GpBitmap)(IntPtr)nativeImage, rect, flags, format, lockedBitmapData)); }
public static bool ConvertToTGA(Bitmap image, string outputFileName) { if (image.Width > 0xFFFF || image.Height > 0xFFFF) { return(false); } byte[] header = { 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, (byte)(image.Width & 0xFF), (byte)((image.Width >> 8) & 0xFF), (byte)(image.Height & 0xFF), (byte)((image.Height >> 8) & 0xFF), 0x00, 0x00 }; byte[] footer = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x52, 0x55, 0x45, 0x56, 0x49, 0x53, 0x49, 0x4F, 0x4E, 0x2D, 0x58, 0x46, 0x49, 0x4C, 0x45, 0x2E, 0x00 }; int bytesPerPixel = 0; if (image.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb) { header[0x10] = 0x20; header[0x11] = 0x08; bytesPerPixel = 4; } else if (image.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb) { header[0x10] = 0x18; bytesPerPixel = 3; } else { return(false); } Bitmap bmp = new Bitmap(image.Width, image.Height, image.PixelFormat); Graphics g = Graphics.FromImage(bmp); g.DrawImage(image, new Rectangle(0, 0, bmp.Width, bmp.Height)); g.Dispose(); bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height); System.Drawing.Imaging.BitmapData data = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat); int length = data.Width * data.Height * bytesPerPixel; byte[] bmpBytes = new byte[length]; for (int y = 0; y < data.Height; ++y) { IntPtr ptr = (IntPtr)((long)data.Scan0 + y * data.Stride); System.Runtime.InteropServices.Marshal.Copy( ptr, bmpBytes, y * data.Width * bytesPerPixel, data.Width * bytesPerPixel); } bmp.UnlockBits(data); bmp.Dispose(); FileStream fs = File.Open(outputFileName, FileMode.Create); fs.Write(header, 0, header.Length); fs.Write(bmpBytes, 0, bmpBytes.Length); fs.Write(footer, 0, footer.Length); fs.Close(); return(true); }
/// <summary> /// Handles the paint. /// </summary> internal unsafe void HandlePaintEvent(IntPtr sourceBuffer, Rect rect, int dx, int dy, Rect scrollRect) { System.Drawing.Imaging.BitmapData sourceData; var clientRect = new Rectangle(rect.Left, rect.Top, rect.Width, rect.Height); byte[] TemporaryBuffer = null; if (dx != 0 || dy != 0) { var sourceRect = new Rectangle(scrollRect.Left, scrollRect.Top, scrollRect.Width, scrollRect.Height); var destRect = sourceRect; destRect.X += dx; destRect.Y += dy; // We want to only draw the overlapping portion of the scrolled and unscrolled // rectangles, since the scrolled rectangle is probably partially offscreen var overlap = Rectangle.Intersect(destRect, sourceRect); // We need to handle scrolling to the left if (destRect.Left < 0) { sourceRect.X -= destRect.Left; destRect.X = 0; } // And upward if (destRect.Top < 0) { sourceRect.Y -= destRect.Top; destRect.Y = 0; } destRect.Width = sourceRect.Width = overlap.Width; destRect.Height = sourceRect.Height = overlap.Height; // If the clipping calculations resulted in a rect that contains zero pixels, // don't bother trying to do the blit. if ((sourceRect.Width > 0) && (sourceRect.Height > 0)) { sourceData = WindowBitmap.LockBits( sourceRect, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb ); int totalSize = sourceData.Stride * sourceData.Height; if ((TemporaryBuffer == null) || (totalSize > TemporaryBuffer.Length)) TemporaryBuffer = new byte[totalSize]; Marshal.Copy(sourceData.Scan0, TemporaryBuffer, 0, totalSize); WindowBitmap.UnlockBits(sourceData); fixed (byte* ptr = &(TemporaryBuffer[0])) { sourceData.Scan0 = new IntPtr(ptr); var destData = WindowBitmap.LockBits( destRect, System.Drawing.Imaging.ImageLockMode.WriteOnly | System.Drawing.Imaging.ImageLockMode.UserInputBuffer, System.Drawing.Imaging.PixelFormat.Format32bppRgb, sourceData ); WindowBitmap.UnlockBits(destData); } InvalidateBerkelium(); } } // If we get a paint event after a resize, the rect can be larger than the buffer. if ((clientRect.Right > WindowBitmap.Width) || (clientRect.Bottom > WindowBitmap.Height)) return; sourceData = new System.Drawing.Imaging.BitmapData(); sourceData.Width = clientRect.Width; sourceData.Height = clientRect.Height; sourceData.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppRgb; sourceData.Stride = clientRect.Width * 4; sourceData.Scan0 = sourceBuffer; // Sometimes this can fail if we process an old paint event after we // request a resize, so we just eat the exception in that case. // Yes, this is terrible. //Bitmap windowBitmap = new Bitmap(clientRect.Width, clientRect.Height); try { // This oddball form of LockBits performs a write to the bitmap's // internal buffer by copying from another BitmapData you pass in. // In this case we're passing in the source buffer. var bd = WindowBitmap.LockBits( clientRect, System.Drawing.Imaging.ImageLockMode.WriteOnly | System.Drawing.Imaging.ImageLockMode.UserInputBuffer, System.Drawing.Imaging.PixelFormat.Format32bppRgb, sourceData ); // For some reason we still have to unlock the bits afterward. WindowBitmap.UnlockBits(bd); InvalidateBerkelium(); } catch { } }
private void freGran_Click(object sender, EventArgs e) { if (curBitmap != null) { granularity granForm = new granularity(); if (granForm.ShowDialog() == DialogResult.OK) { Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height); System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat); IntPtr ptr = bmpData.Scan0; int bytes = curBitmap.Width * curBitmap.Height; byte[] grayValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes); Complex[] freDom = new Complex[bytes]; Complex[] tempDD = new Complex[bytes]; byte[] tempArray = new byte[bytes]; byte[] tempRadius = new byte[6]; tempRadius = granForm.GetRadius; byte flag = granForm.GetFlag; int minLen = Math.Min(curBitmap.Width, curBitmap.Height); double[] radius = new double[6]; for (int i = 0; i < 6; i++) { radius[i] = tempRadius[i] * minLen / 100; } freDom = fft2(grayValues, curBitmap.Width, curBitmap.Height, true); for (int i = 0; i < curBitmap.Height; i++) { for (int j = 0; j < curBitmap.Width; j++) { double distance = (double)((j - curBitmap.Width / 2) * (j - curBitmap.Width / 2) + (i - curBitmap.Height / 2) * (i - curBitmap.Height / 2)); distance = Math.Sqrt(distance); switch (flag) { case 0: if (distance > radius[0]) { tempDD[i * curBitmap.Width + j] = new Complex(0.0, 0.0); } else { tempDD[i * curBitmap.Width + j] = new Complex(1.0, 1.0); } break; case 1: if (distance < radius[1] && distance > radius[2]) { tempDD[i * curBitmap.Width + j] = new Complex(0.0, 0.0); } else { tempDD[i * curBitmap.Width + j] = new Complex(1.0, 1.0); } break; case 2: if (distance > radius[3] || distance < radius[4]) { tempDD[i * curBitmap.Width + j] = new Complex(0.0, 0.0); } else { tempDD[i * curBitmap.Width + j] = new Complex(1.0, 1.0); } break; case 3: if (distance < radius[5]) { tempDD[i * curBitmap.Width + j] = new Complex(0.0, 0.0); } else { tempDD[i * curBitmap.Width + j] = new Complex(1.0, 1.0); } break; default: MessageBox.Show("无效!"); break; } } } for (int i = 0; i < bytes; i++) { freDom[i] *= tempDD[i]; } tempArray = ifft2(freDom, curBitmap.Width, curBitmap.Height, true); grayValues = (byte[])tempArray.Clone(); System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes); curBitmap.UnlockBits(bmpData); } Invalidate(); } }
unsafe void handleBitmap(int* binfo, byte* image, int cindex, int frameIndex) { try { if (m_Stop) return; // compose a managed bitmap from the bitmap parts being delivered System.Drawing.Imaging.BitmapData srcBmpHeader = new System.Drawing.Imaging.BitmapData(); Marshal.PtrToStructure((IntPtr)binfo, srcBmpHeader); //pDoc->m_buf[idx].lpbmi[frm_idx]->bmiHeader.biSizeImage // for some reason stride and width a swapped in position between the 2255 definition and the windows bitmpa definition int width = srcBmpHeader.Height; int height = srcBmpHeader.Stride; Rectangle rect = new Rectangle(0, 0, width, height); // Bitmap nBmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); Bitmap nBmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format8bppIndexed); System.Drawing.Imaging.BitmapData bmpData = nBmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, nBmp.PixelFormat); // Get the address of the first line. // int byteCount = width * height * 3; int byteCount = width * height; //byte[] byteArray = new byte[byteCount]; //Marshal.Copy(new IntPtr(image), byteArray, 0, byteCount); //Marshal.Copy(byteArray, 0, bmpData.Scan0, byteCount); bool detectedNoVideoPresent = false; LPROCR_Lib.MemCopyByte((int*)image, bmpData.Scan0, byteCount, ref detectedNoVideoPresent); // LPROCR_Lib.MemCopyInt((int*)image, bmpData.Scan0, byteCount ); nBmp.UnlockBits(bmpData); // nBmp.RotateFlip(RotateFlipType.RotateNoneFlipY); // if there is no video connected, the 2255 device sends frames at 30fps, but they are solid blue-screen. if (!detectedNoVideoPresent) { SetHaveVideo(cindex); SendImageToConsumer(nBmp, S2255Controller.COMPRESSION_MODE.BITMAP, cindex); } else { SetDontHaveVideo(cindex); } } catch (Exception ex) { m_Log.Log("handleBitmap ex: " + ex.Message, ErrorLog.LOG_TYPE.FATAL); } }
private void freOri_Click(object sender, EventArgs e) { if (curBitmap != null) { orientation orieForm = new orientation(); if (orieForm.ShowDialog() == DialogResult.OK) { Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height); System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat); IntPtr ptr = bmpData.Scan0; int bytes = curBitmap.Width * curBitmap.Height; byte[] grayValues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, grayValues, 0, bytes); Complex[] freDom = new Complex[bytes]; byte[] tempArray = new byte[bytes]; int[] tempOrient = new int[2]; tempOrient = orieForm.GetOrient; byte flag = 1; if (tempOrient[1] <= 0) { flag = 1; } if (tempOrient[0] <= 0 && tempOrient[1] > 0) { flag = 2; } if (tempOrient[0] > 0 && tempOrient[1] < 180) { flag = 3; } if (tempOrient[1] > 180) { flag = 4; } freDom = fft2(grayValues, curBitmap.Width, curBitmap.Height, true); double tempD; for (int i = 0; i < curBitmap.Height; i++) { for (int j = 0; j < curBitmap.Width; j++) { tempD = (Math.Atan2(curBitmap.Height / 2 - i, j - curBitmap.Width / 2)) * 180 / Math.PI; switch (flag) { case 1: if ((tempD <= tempOrient[1] && tempD >= tempOrient[0]) || (tempD <= (tempOrient[1] + 180) && tempD >= (tempOrient[0] + 180))) { freDom[i * curBitmap.Width + j] = new Complex(0.0, 0.0); } break; case 2: if ((tempD <= tempOrient[1] && tempD >= tempOrient[0] /*&& tempD != 0*/) || (tempD <= tempOrient[1] - 180 && tempD > -180) || (tempD > tempOrient[0] + 180 && tempD <= 180)) { freDom[i * curBitmap.Width + j] = new Complex(0.0, 0.0); } break; case 3: if ((tempD <= tempOrient[1] && tempD >= tempOrient[0]) || (tempD <= tempOrient[1] - 180 && tempD >= tempOrient[0] - 180)) { freDom[i * curBitmap.Width + j] = new Complex(0.0, 0.0); } break; case 4: if (((tempD <= tempOrient[1] - 180) && (tempD >= tempOrient[0] - 180)) || (tempD <= tempOrient[1] - 360 && tempD >= -180) || (tempD >= tempOrient[0] && tempD <= 180)) { freDom[i * curBitmap.Width + j] = new Complex(0.0, 0.0); } break; default: MessageBox.Show("无效!"); break; } } } tempArray = ifft2(freDom, curBitmap.Width, curBitmap.Height, true); grayValues = (byte[])tempArray.Clone(); System.Runtime.InteropServices.Marshal.Copy(grayValues, 0, ptr, bytes); curBitmap.UnlockBits(bmpData); } Invalidate(); } }
internal static void Main(string[] args) { Interface.CurrentOptions.UseSound = true; Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000; Interface.CurrentOptions.ObjectOptimizationFullThreshold = 250; // platform and mono int p = (int)Environment.OSVersion.Platform; if (p == 4 | p == 128) { // general Unix CurrentPlatform = Platform.Linux; } else if (p == 6) { // Mac CurrentPlatform = Platform.Mac; } else { // non-Unix CurrentPlatform = Platform.Windows; } CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null; // file system FileSystem = FileSystem.FromCommandLineArgs(args); FileSystem.CreateFileSystem(); SetPackageLookupDirectories(); // command line arguments bool[] SkipArgs = new bool[args.Length]; if (args.Length != 0) { string File = System.IO.Path.Combine(Application.StartupPath, "ObjectViewer.exe"); if (System.IO.File.Exists(File)) { int Skips = 0; System.Text.StringBuilder NewArgs = new System.Text.StringBuilder(); for (int i = 0; i < args.Length; i++) { if (System.IO.File.Exists(args[i])) { if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase)) { string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8); if (Text.Length == 0 || Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) >= 0) { if (NewArgs.Length != 0) NewArgs.Append(" "); NewArgs.Append("\"" + args[i] + "\""); SkipArgs[i] = true; Skips++; } } } else { SkipArgs[i] = true; Skips++; } } if (NewArgs.Length != 0) { System.Diagnostics.Process.Start(File, NewArgs.ToString()); } if (Skips == args.Length) return; } } // application Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) != 0) { MessageBox.Show("SDL failed to initialize the video subsystem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } // initialize sdl window SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DEPTH_SIZE, 16); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_RED_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_GREEN_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_BLUE_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_ALPHA_SIZE, 8); SDL.SDL_ShowCursor(1); // initialize camera ResetCamera(); World.BackgroundImageDistance = 600.0; World.ForwardViewingDistance = 600.0; World.BackwardViewingDistance = 0.0; World.ExtraViewingDistance = 50.0; // create window Renderer.ScreenWidth = 960; Renderer.ScreenHeight = 600; //int Bits = 32; //IntPtr video = Sdl.SDL_SetVideoMode(Renderer.ScreenWidth, Renderer.ScreenHeight, Bits, Sdl.SDL_OPENGL | Sdl.SDL_DOUBLEBUF); Window = SDL.SDL_CreateWindow(Application.ProductName, SDL.SDL_WINDOWPOS_UNDEFINED, SDL.SDL_WINDOWPOS_UNDEFINED, Renderer.ScreenWidth, Renderer.ScreenHeight, SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL | SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE); if (Window == IntPtr.Zero) { MessageBox.Show("SDL failed to create the window.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } // icon string iconFile = OpenBveApi.Path.CombineFile(Program.FileSystem.GetDataFolder(), "icon.png"); if (System.IO.File.Exists(iconFile)) { iconBmp = new Bitmap(iconFile); // load file iconData = iconBmp.LockBits(new Rectangle(0, 0, iconBmp.Width, iconBmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // lock data iconSurface = SDL.SDL_CreateRGBSurfaceFrom(iconData.Scan0, iconBmp.Width, iconBmp.Height, 32, iconData.Stride, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000); // upload to sdl SDL.SDL_SetWindowIcon(Window, iconSurface); // use icon } GLContext = SDL.SDL_GL_CreateContext(Window); GraphicsContext tkContext = new GraphicsContext(new ContextHandle(GLContext), SDL.SDL_GL_GetProcAddress, SDLGetCurrentContext); // anisotropic filtering string[] extensions = GL.GetString(StringName.Extensions).Split(new []{ ' ' }, StringSplitOptions.RemoveEmptyEntries); Interface.CurrentOptions.AnisotropicFilteringMaximum = 0; for (int i = 0; i < extensions.Length; i++) { if (extensions[i] == "GL_EXT_texture_filter_anisotropic") { float n; GL.GetFloat((GetPName)ExtTextureFilterAnisotropic.MaxTextureMaxAnisotropyExt, out n); Interface.CurrentOptions.AnisotropicFilteringMaximum = (int)Math.Round((double)n); break; } } if (Interface.CurrentOptions.AnisotropicFilteringMaximum <= 0) { Interface.CurrentOptions.AnisotropicFilteringMaximum = 0; Interface.CurrentOptions.AnisotropicFilteringLevel = 0; Interface.CurrentOptions.Interpolation = TextureManager.InterpolationMode.AnisotropicFiltering; } else { Interface.CurrentOptions.AnisotropicFilteringLevel = Interface.CurrentOptions.AnisotropicFilteringMaximum; Interface.CurrentOptions.Interpolation = TextureManager.InterpolationMode.TrilinearMipmapped; } Interface.CurrentOptions.TransparencyMode = Renderer.TransparencyMode.Sharp; // module initialization Renderer.Initialize(); Renderer.InitializeLighting(); SoundManager.Initialize(); GL.ClearColor(0.75f, 0.75f, 0.75f, 1.0f); SwapBuffers(); Fonts.Initialize(); UpdateViewport(); // loop bool processCommandLineArgs = true; timer = new System.Diagnostics.Stopwatch(); timer.Start(); while (!Quit) { ProcessEvents(); int a = (int)timer.ElapsedMilliseconds; double TimeElapsed = 0.001 * (double)(a - LastTicks); if (CpuReducedMode) { System.Threading.Thread.Sleep(250); } else { System.Threading.Thread.Sleep(1); if (ReducedModeEnteringTime == 0) { ReducedModeEnteringTime = a + 2500; } if (World.CameraAlignmentDirection.Position.X != 0.0 | World.CameraAlignmentDirection.Position.Y != 0.0 | World.CameraAlignmentDirection.Position.Z != 0.0 | World.CameraAlignmentDirection.Pitch != 0.0 | World.CameraAlignmentDirection.Yaw != 0.0 | World.CameraAlignmentDirection.Roll != 0.0 | World.CameraAlignmentDirection.TrackPosition != 0.0 | World.CameraAlignmentDirection.Zoom != 0.0) { ReducedModeEnteringTime = a + 2500; } else if (a > ReducedModeEnteringTime & CpuAutomaticMode) { ReducedModeEnteringTime = 0; CpuReducedMode = true; } } DateTime d = DateTime.Now; Game.SecondsSinceMidnight = (double)(3600 * d.Hour + 60 * d.Minute + d.Second) + 0.001 * (double)d.Millisecond; ObjectManager.UpdateAnimatedWorldObjects(TimeElapsed, false); World.UpdateAbsoluteCamera(TimeElapsed); ObjectManager.UpdateVisibility(World.CameraTrackFollower.TrackPosition + World.CameraCurrentAlignment.Position.Z); TextureManager.Update(TimeElapsed); SoundManager.Update(TimeElapsed); Renderer.RenderScene(TimeElapsed); SwapBuffers(); LastTicks = a; // command line arguments if (processCommandLineArgs) { processCommandLineArgs = false; for (int i = 0; i < args.Length; i++) { if (!SkipArgs[i] && System.IO.File.Exists(args[i])) { CurrentlyLoading = true; Renderer.RenderScene(0.0); SwapBuffers(); CurrentRoute = args[i]; LoadRoute(); CurrentlyLoading = false; UpdateCaption(); break; } } } } // quit TextureManager.UnuseAllTextures(); SoundManager.Deinitialize(); if (iconSurface != IntPtr.Zero) SDL.SDL_FreeSurface(iconSurface); // free surface if (iconBmp != null && iconData != null) { iconBmp.UnlockBits(iconData); // free pixels iconBmp.Dispose(); } SDL.SDL_GL_DeleteContext(GLContext); SDL.SDL_DestroyWindow(Window); SDL.SDL_Quit(); }
/// <summary> /// Load an XPM icon into a Bitmap object. /// </summary> /// <param name="stream">Stream from which the picture will be loaded.</param> /// <returns>Bitmap that contains the picture, or null if loading failed.</returns> public static Bitmap Load(Stream stream) { var colorDict = new Dictionary <string, UInt32>(); string str; string[] strArray; str = ReadUntil(stream, '"'); str = ReadUntil(stream, '"'); strArray = str.Split(whitespacequote, StringSplitOptions.RemoveEmptyEntries); if (strArray.Length < 4) { throw new ApplicationException("Invalid file format."); } int bmpWidth = Convert.ToInt32(strArray[0]); int bmpHeight = Convert.ToInt32(strArray[1]); int numColors = Convert.ToInt32(strArray[2]); int charsPerPixel = Convert.ToInt32(strArray[3]); //check for nonsensical dimensions if ((bmpWidth <= 0) || (bmpHeight <= 0) || (numColors <= 0) || (charsPerPixel <= 0)) { throw new ApplicationException("Invalid image dimensions."); } string sampleChar, sampleValue; uint intColor; ulong longColor; for (int i = 0; i < numColors; i++) { str = ReadUntil(stream, '"'); str = ReadUntil(stream, '"'); sampleChar = str.Substring(0, charsPerPixel); strArray = str.Split(whitespacequote, StringSplitOptions.RemoveEmptyEntries); sampleValue = strArray[strArray.Length - 1]; if (sampleValue.ToLower().Contains("none")) { intColor = 0x0; } else if (sampleValue.StartsWith("#")) { sampleValue = sampleValue.Replace("#", ""); longColor = Convert.ToUInt64(sampleValue, 16); if (sampleValue.Length > 6) { intColor = 0xFF000000; intColor |= (UInt32)((longColor & 0xFF0000000000) >> 24); intColor |= (UInt32)((longColor & 0xFF000000) >> 16); intColor |= (UInt32)((longColor & 0xFF00) >> 8); } else { intColor = (UInt32)longColor | 0xFF000000; } } else { intColor = (uint)Color.FromName(sampleValue).ToArgb(); } colorDict.Add(sampleChar, intColor); } int numPixels = bmpWidth * bmpHeight; int elementCount = 0, strIndex; int maxElementCount = numPixels * 4; var bmpData = new byte[maxElementCount]; try { while (stream.Position < stream.Length) { str = ReadUntil(stream, '"'); str = ReadUntil(stream, '"'); strIndex = 0; while (strIndex < str.Length - 1) { intColor = colorDict[str.Substring(strIndex, charsPerPixel)]; strIndex += charsPerPixel; bmpData[elementCount++] = (byte)(intColor & 0xFF); bmpData[elementCount++] = (byte)((intColor & 0xFF00) >> 8); bmpData[elementCount++] = (byte)((intColor & 0xFF0000) >> 16); bmpData[elementCount++] = (byte)((intColor & 0xFF000000) >> 24); if (elementCount >= maxElementCount) { break; } } if (elementCount >= maxElementCount) { break; } } } catch (Exception e) { //give a partial image in case of unexpected end-of-file System.Diagnostics.Debug.WriteLine("Error while processing XPM file: " + e.Message); } var bmp = new Bitmap(bmpWidth, bmpHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Drawing.Imaging.BitmapData bmpBits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppArgb); System.Runtime.InteropServices.Marshal.Copy(bmpData, 0, bmpBits.Scan0, bmpData.Length); bmp.UnlockBits(bmpBits); return(bmp); }
/// <summary> /// Reads a DICOM image from a stream. /// </summary> /// <param name="stream">Stream from which to read the image.</param> /// <returns>Bitmap that contains the image that was read.</returns> /// public static Bitmap Load(Stream stream) { BinaryReader reader = new BinaryReader(stream); byte[] tempBytes = new byte[256]; stream.Seek(0x80, SeekOrigin.Current); stream.Read(tempBytes, 0, 0x10); //check signature... string signature = System.Text.Encoding.ASCII.GetString(tempBytes, 0, 4); if (!signature.Equals("DICM")) { throw new ApplicationException("Not a valid DICOM file."); } int imgWidth = 0, imgHeight = 0; int samplesPerPixel = 0, numFrames = 0, bitsPerSample = 0, bitsStored = 0; int dataLength = 0; bool bigEndian = false, explicitVR = true; bool isJPEG = false, isRLE = false; //read the meta-group, and determine stuff from it int metaGroupLen = (int)Util.LittleEndian(BitConverter.ToUInt32(tempBytes, 0xC)); if (metaGroupLen > 10000) { throw new ApplicationException("Meta group is a bit too long. May not be a valid DICOM file."); } tempBytes = new byte[metaGroupLen]; stream.Read(tempBytes, 0, metaGroupLen); //convert the whole thing to a string, and search it for clues string metaGroupStr = System.Text.Encoding.ASCII.GetString(tempBytes); if (metaGroupStr.Contains("1.2.840.10008.1.2\0")) { explicitVR = false; } if (metaGroupStr.Contains("1.2.840.10008.1.2.2\0")) { bigEndian = true; } if (metaGroupStr.Contains("1.2.840.10008.1.2.5\0")) { isRLE = true; } if (metaGroupStr.Contains("1.2.840.10008.1.2.4.")) { isJPEG = true; } if (isRLE) { throw new ApplicationException("RLE-encoded DICOM images are not supported."); } if (isJPEG) { throw new ApplicationException("JPEG-encoded DICOM images are not supported."); } //get header information: bool reachedData = false; int groupNumber, elementNumber; while (!reachedData && (stream.Position < stream.Length)) { groupNumber = getGroupNumber(reader, bigEndian); elementNumber = getShort(reader, groupNumber, bigEndian); if (groupNumber == 0x28) { if (elementNumber == 0x2) { samplesPerPixel = (int)getNumeric(reader, groupNumber, bigEndian, explicitVR); } else if (elementNumber == 0x8) { numFrames = (int)getNumeric(reader, groupNumber, bigEndian, explicitVR); } else if (elementNumber == 0x10) { imgHeight = (int)getNumeric(reader, groupNumber, bigEndian, explicitVR); } else if (elementNumber == 0x11) { imgWidth = (int)getNumeric(reader, groupNumber, bigEndian, explicitVR); } else if (elementNumber == 0x100) { bitsPerSample = (int)getNumeric(reader, groupNumber, bigEndian, explicitVR); } else if (elementNumber == 0x101) { bitsStored = (int)getNumeric(reader, groupNumber, bigEndian, explicitVR); } else { skipElement(reader, groupNumber, elementNumber, bigEndian, explicitVR); } } else if (groupNumber == 0x7FE0) { if (elementNumber == 0x10) { //we've reached the data! if (explicitVR) { int v1 = stream.ReadByte(); int v2 = stream.ReadByte(); getShort(reader, groupNumber, false); dataLength = (int)getInt(reader, groupNumber, bigEndian); } else { dataLength = (int)getInt(reader, groupNumber, bigEndian); } reachedData = true; } else { skipElement(reader, groupNumber, elementNumber, bigEndian, explicitVR); } } else { skipElement(reader, groupNumber, elementNumber, bigEndian, explicitVR); } } byte[] data = null; if (dataLength > 0) { data = new byte[dataLength]; stream.Read(data, 0, dataLength); } else if (dataLength == -1) { //we'll have to read the data by sequential packets List <byte[]> dataSegments = new List <byte[]>(); UInt16 tempShort; int segmentLen = 0; while (stream.Position < stream.Length) { tempShort = getShort(reader, 0, bigEndian); if (tempShort != 0xFFFE) { break; } tempShort = getShort(reader, 0, bigEndian); if ((tempShort != 0xE000) && (tempShort != 0xE00D) && (tempShort != 0xE0DD)) { break; } segmentLen = (int)getInt(reader, 0, bigEndian); if (segmentLen < 0 || segmentLen > 100000000) { break; } if (segmentLen > 0) { byte[] segment = new byte[segmentLen]; stream.Read(segment, 0, segmentLen); dataSegments.Add(segment); } } dataLength = 0; foreach (var i in dataSegments) { dataLength += i.Length; } data = new byte[dataLength]; int dataPtr = 0; for (int i = 0; i < dataSegments.Count; i++) { Array.Copy(dataSegments[i], 0, data, dataPtr, dataSegments[i].Length); dataPtr += dataSegments[i].Length; } } if (dataLength == 0) { throw new ApplicationException("DICOM file does not appear to have any image data."); } MemoryStream dataStream = new MemoryStream(data); reader = new BinaryReader(dataStream); //detect whether the data is really a JPG image if ((data[0] == 0xFF) && (data[1] == 0xD8) && (data[2] == 0xFF)) { return((Bitmap)Image.FromStream(dataStream)); } if (numFrames == 0) { numFrames = 1; } if (samplesPerPixel > 4) { throw new ApplicationException("Do not support greater than 4 samples per pixel."); } if ((bitsPerSample != 8) && (bitsPerSample != 16) && (bitsPerSample != 32)) { throw new ApplicationException("Invalid bits per sample."); } byte[] bmpData = new byte[imgWidth * 4 * imgHeight]; try { if (samplesPerPixel == 1) { if (bitsPerSample == 8) { byte b; for (int y = 0; y < imgHeight; y++) { for (int x = 0; x < imgWidth; x++) { b = (byte)dataStream.ReadByte(); bmpData[4 * (y * imgWidth + x)] = b; bmpData[4 * (y * imgWidth + x) + 1] = b; bmpData[4 * (y * imgWidth + x) + 2] = b; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; } } } else if (bitsPerSample == 16) { //pre-read all the samples, so we can normalize UInt16[] samples = new UInt16[imgHeight * imgWidth]; try { for (int i = 0; i < samples.Length; i++) { samples[i] = getShort(reader, 0, bigEndian); } } catch { } //normalize UInt16 maxVal = 0; for (int i = 0; i < samples.Length; i++) { if (samples[i] > maxVal) { maxVal = samples[i]; } } int multiplier = maxVal == 0 ? 1 : 65536 / maxVal; byte b; int sampPtr = 0; for (int y = 0; y < imgHeight; y++) { for (int x = 0; x < imgWidth; x++) { b = (byte)((samples[sampPtr++] * multiplier) >> 8); //b = (byte)(getShort(reader, 0, bigEndian) & 0xFF); bmpData[4 * (y * imgWidth + x)] = b; bmpData[4 * (y * imgWidth + x) + 1] = b; bmpData[4 * (y * imgWidth + x) + 2] = b; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; } } } else if (bitsPerSample == 32) { byte b; for (int y = 0; y < imgHeight; y++) { for (int x = 0; x < imgWidth; x++) { b = (byte)(getFloat(reader, 0, bigEndian) * 255); bmpData[4 * (y * imgWidth + x)] = b; bmpData[4 * (y * imgWidth + x) + 1] = b; bmpData[4 * (y * imgWidth + x) + 2] = b; bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; } } } } else if (samplesPerPixel == 3) { if (bitsPerSample == 8) { for (int y = 0; y < imgHeight; y++) { for (int x = 0; x < imgWidth; x++) { bmpData[4 * (y * imgWidth + x) + 2] = (byte)dataStream.ReadByte(); bmpData[4 * (y * imgWidth + x) + 1] = (byte)dataStream.ReadByte(); bmpData[4 * (y * imgWidth + x)] = (byte)dataStream.ReadByte(); bmpData[4 * (y * imgWidth + x) + 3] = 0xFF; } } } else if (bitsPerSample == 16) { } else if (bitsPerSample == 32) { } } } catch (Exception e) { //give a partial image in case of unexpected end-of-file System.Diagnostics.Debug.WriteLine("Error while processing DICOM file: " + e.Message); } var bmp = new Bitmap(imgWidth, imgHeight, System.Drawing.Imaging.PixelFormat.Format32bppRgb); System.Drawing.Imaging.BitmapData bmpBits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format32bppRgb); System.Runtime.InteropServices.Marshal.Copy(bmpData, 0, bmpBits.Scan0, imgWidth * 4 * imgHeight); bmp.UnlockBits(bmpBits); return(bmp); }
internal static void Main(string[] args) { // platform and mono int p = (int)Environment.OSVersion.Platform; if (p == 4 | p == 128) { // general Unix CurrentPlatform = Platform.Linux; } else if (p == 6) { // Mac CurrentPlatform = Platform.Mac; } else { // non-Unix CurrentPlatform = Platform.Windows; } CurrentlyRunOnMono = Type.GetType("Mono.Runtime") != null; // file system FileSystem = FileSystem.FromCommandLineArgs(args); FileSystem.CreateFileSystem(); SetPackageLookupDirectories(); // command line arguments bool[] SkipArgs = new bool[args.Length]; if (args.Length != 0) { string File = System.IO.Path.Combine(Application.StartupPath, "RouteViewer.exe"); if (System.IO.File.Exists(File)) { int Skips = 0; System.Text.StringBuilder NewArgs = new System.Text.StringBuilder(); for (int i = 0; i < args.Length; i++) { if (System.IO.File.Exists(args[i])) { if (System.IO.Path.GetExtension(args[i]).Equals(".csv", StringComparison.OrdinalIgnoreCase)) { string Text = System.IO.File.ReadAllText(args[i], System.Text.Encoding.UTF8); if (Text.Length != -1 && Text.IndexOf("CreateMeshBuilder", StringComparison.OrdinalIgnoreCase) == -1) { if (NewArgs.Length != 0) NewArgs.Append(" "); NewArgs.Append("\"" + args[i] + "\""); SkipArgs[i] = true; Skips++; } } } else { SkipArgs[i] = true; Skips++; } } if (NewArgs.Length != 0) { System.Diagnostics.Process.Start(File, NewArgs.ToString()); } if (Skips == args.Length) return; } } // application Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) != 0) { MessageBox.Show("SDL failed to initialize the video subsystem.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } Interface.CurrentOptions.ObjectOptimizationBasicThreshold = 1000; Interface.CurrentOptions.ObjectOptimizationFullThreshold = 250; // initialize sdl window SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DEPTH_SIZE, 16); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_RED_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_GREEN_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_BLUE_SIZE, 8); SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_ALPHA_SIZE, 8); SDL.SDL_ShowCursor(1); // initialize camera ResetCamera(); // create window Renderer.ScreenWidth = 960; Renderer.ScreenHeight = 600; int Bits = 32; //Sdl.SDL_SetVideoMode(Renderer.ScreenWidth, Renderer.ScreenHeight, Bits, Sdl.SDL_OPENGL | Sdl.SDL_DOUBLEBUF); SDLWindow = SDL.SDL_CreateWindow(Application.ProductName, SDL.SDL_WINDOWPOS_UNDEFINED,SDL.SDL_WINDOWPOS_UNDEFINED, Renderer.ScreenWidth,Renderer.ScreenHeight, SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL | SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE); if (SDLWindow != IntPtr.Zero) { // create window string File = OpenBveApi.Path.CombineFile(Program.FileSystem.GetDataFolder(), "icon.png"); if (System.IO.File.Exists(File)) { // set up icon iconBmp = new Bitmap(File); // load file iconData = iconBmp.LockBits(new Rectangle(0,0,iconBmp.Width,iconBmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); // lock data iconSurface = SDL.SDL_CreateRGBSurfaceFrom(iconData.Scan0,iconBmp.Width,iconBmp.Height,32,iconData.Stride, 0x00FF0000,0x0000FF00,0x000000FF,0xFF000000); // upload to sdl SDL.SDL_SetWindowIcon(SDLWindow,iconSurface); // use icon // free is on the end of the program /* IntPtr bitmap = SDL.SDL_LoadBMP(File); if (bitmap != IntPtr.Zero) { SDL.SDL_Surface Surface = (SDL.SDL_Surface)System.Runtime.InteropServices.Marshal.PtrToStructure(bitmap, typeof(SDL.SDL_Surface)); uint ColorKey = SDL.SDL_MapRGB(Surface.format, 0, 0, 255); SDL.SDL_SetColorKey(bitmap, 1, ColorKey); SDL.SDL_SetWindowIcon(SDLWindow,bitmap); } */ } GLContext = SDL.SDL_GL_CreateContext(SDLWindow); GraphicsContext tkContext = new GraphicsContext(new ContextHandle(GLContext), SDL.SDL_GL_GetProcAddress, () => new ContextHandle(SDL.SDL_GL_GetCurrentContext())); // anisotropic filtering string[] extensions = GL.GetString(StringName.Extensions).Split(new []{' '},StringSplitOptions.RemoveEmptyEntries); Interface.CurrentOptions.AnisotropicFilteringMaximum = 0; for (int i = 0; i < extensions.Length; i++) { if (extensions[i] == "GL_EXT_texture_filter_anisotropic") { float n; GL.GetFloat((GetPName)ExtTextureFilterAnisotropic.MaxTextureMaxAnisotropyExt, out n); Interface.CurrentOptions.AnisotropicFilteringMaximum = (int)Math.Round((double)n); break; } } if (Interface.CurrentOptions.AnisotropicFilteringMaximum <= 0) { Interface.CurrentOptions.AnisotropicFilteringMaximum = 0; Interface.CurrentOptions.AnisotropicFilteringLevel = 0; Interface.CurrentOptions.Interpolation = TextureManager.InterpolationMode.AnisotropicFiltering; } else { Interface.CurrentOptions.AnisotropicFilteringLevel = Interface.CurrentOptions.AnisotropicFilteringMaximum; Interface.CurrentOptions.Interpolation = TextureManager.InterpolationMode.TrilinearMipmapped; } // module initialization Renderer.Initialize(); Renderer.InitializeLighting(); SDL.SDL_GL_SwapWindow(SDLWindow); Fonts.Initialize(); UpdateViewport(); // command line arguments for (int i = 0; i < args.Length; i++) { if (!SkipArgs[i] && System.IO.File.Exists(args[i])) { try { ObjectManager.UnifiedObject o = ObjectManager.LoadObject(args[i], System.Text.Encoding.UTF8, ObjectManager.ObjectLoadMode.Normal, false, false, false); ObjectManager.CreateObject(o, new World.Vector3D(0.0, 0.0, 0.0), new World.Transformation(0.0, 0.0, 0.0), new World.Transformation(0.0, 0.0, 0.0), true, 0.0, 0.0, 25.0, 0.0); } catch (Exception ex) { Interface.AddMessage(Interface.MessageType.Critical, false, "Unhandled error (" + ex.Message + ") encountered while processing the file " + args[i] + "."); } Array.Resize<string>(ref Files, Files.Length + 1); Files[Files.Length - 1] = args[i]; } } ObjectManager.InitializeVisibility(); ObjectManager.FinishCreatingObjects(); ObjectManager.UpdateVisibility(0.0, true); ObjectManager.UpdateAnimatedWorldObjects(0.01, true); UpdateCaption(); Stopwatch timer = new Stopwatch(); timer.Start(); LastTicks = timer.ElapsedMilliseconds; // loop while (!Quit) { long ticks = timer.ElapsedMilliseconds; double timeElapsed = 0.001 * (double)(ticks - LastTicks); if (timeElapsed < 0.0001) { timeElapsed = 0.0001; } LastTicks = ticks; DateTime time = DateTime.Now; Game.SecondsSinceMidnight = (double)(3600 * time.Hour + 60 * time.Minute + time.Second) + 0.001 * (double)time.Millisecond; ObjectManager.UpdateAnimatedWorldObjects(timeElapsed, false); ProcessEvents(); if (ReducedMode) { System.Threading.Thread.Sleep(125); } else { System.Threading.Thread.Sleep(1); } bool updatelight = false; bool keep = false; // rotate x if (RotateX == 0) { double d = (1.0 + Math.Abs(RotateXSpeed)) * timeElapsed; if (RotateXSpeed >= -d & RotateXSpeed <= d) { RotateXSpeed = 0.0; } else { RotateXSpeed -= (double)Math.Sign(RotateXSpeed) * d; } } else { double d = (1.0 + 1.0 - 1.0 / (1.0 + RotateXSpeed * RotateXSpeed)) * timeElapsed; double m = 1.0; RotateXSpeed += (double)RotateX * d; if (RotateXSpeed < -m) { RotateXSpeed = -m; } else if (RotateXSpeed > m) { RotateXSpeed = m; } } if (RotateXSpeed != 0.0) { double cosa = Math.Cos(RotateXSpeed * timeElapsed); double sina = Math.Sin(RotateXSpeed * timeElapsed); World.Rotate(ref World.AbsoluteCameraDirection.X, ref World.AbsoluteCameraDirection.Y, ref World.AbsoluteCameraDirection.Z, 0.0, 1.0, 0.0, cosa, sina); World.Rotate(ref World.AbsoluteCameraUp.X, ref World.AbsoluteCameraUp.Y, ref World.AbsoluteCameraUp.Z, 0.0, 1.0, 0.0, cosa, sina); World.Rotate(ref World.AbsoluteCameraSide.X, ref World.AbsoluteCameraSide.Y, ref World.AbsoluteCameraSide.Z, 0.0, 1.0, 0.0, cosa, sina); keep = true; } // rotate y if (RotateY == 0) { double d = (1.0 + Math.Abs(RotateYSpeed)) * timeElapsed; if (RotateYSpeed >= -d & RotateYSpeed <= d) { RotateYSpeed = 0.0; } else { RotateYSpeed -= (double)Math.Sign(RotateYSpeed) * d; } } else { double d = (1.0 + 1.0 - 1.0 / (1.0 + RotateYSpeed * RotateYSpeed)) * timeElapsed; double m = 1.0; RotateYSpeed += (double)RotateY * d; if (RotateYSpeed < -m) { RotateYSpeed = -m; } else if (RotateYSpeed > m) { RotateYSpeed = m; } } if (RotateYSpeed != 0.0) { double cosa = Math.Cos(RotateYSpeed * timeElapsed); double sina = Math.Sin(RotateYSpeed * timeElapsed); World.Rotate(ref World.AbsoluteCameraDirection.X, ref World.AbsoluteCameraDirection.Y, ref World.AbsoluteCameraDirection.Z, World.AbsoluteCameraSide.X, World.AbsoluteCameraSide.Y, World.AbsoluteCameraSide.Z, cosa, sina); World.Rotate(ref World.AbsoluteCameraUp.X, ref World.AbsoluteCameraUp.Y, ref World.AbsoluteCameraUp.Z, World.AbsoluteCameraSide.X, World.AbsoluteCameraSide.Y, World.AbsoluteCameraSide.Z, cosa, sina); keep = true; } // move x if (MoveX == 0) { double d = (2.5 + Math.Abs(MoveXSpeed)) * timeElapsed; if (MoveXSpeed >= -d & MoveXSpeed <= d) { MoveXSpeed = 0.0; } else { MoveXSpeed -= (double)Math.Sign(MoveXSpeed) * d; } } else { double d = (5.0 + 10.0 - 10.0 / (1.0 + MoveXSpeed * MoveXSpeed)) * timeElapsed; double m = 25.0; MoveXSpeed += (double)MoveX * d; if (MoveXSpeed < -m) { MoveXSpeed = -m; } else if (MoveXSpeed > m) { MoveXSpeed = m; } } if (MoveXSpeed != 0.0) { World.AbsoluteCameraPosition.X += MoveXSpeed * timeElapsed * World.AbsoluteCameraSide.X; World.AbsoluteCameraPosition.Y += MoveXSpeed * timeElapsed * World.AbsoluteCameraSide.Y; World.AbsoluteCameraPosition.Z += MoveXSpeed * timeElapsed * World.AbsoluteCameraSide.Z; keep = true; } // move y if (MoveY == 0) { double d = (2.5 + Math.Abs(MoveYSpeed)) * timeElapsed; if (MoveYSpeed >= -d & MoveYSpeed <= d) { MoveYSpeed = 0.0; } else { MoveYSpeed -= (double)Math.Sign(MoveYSpeed) * d; } } else { double d = (5.0 + 10.0 - 10.0 / (1.0 + MoveYSpeed * MoveYSpeed)) * timeElapsed; double m = 25.0; MoveYSpeed += (double)MoveY * d; if (MoveYSpeed < -m) { MoveYSpeed = -m; } else if (MoveYSpeed > m) { MoveYSpeed = m; } } if (MoveYSpeed != 0.0) { World.AbsoluteCameraPosition.X += MoveYSpeed * timeElapsed * World.AbsoluteCameraUp.X; World.AbsoluteCameraPosition.Y += MoveYSpeed * timeElapsed * World.AbsoluteCameraUp.Y; World.AbsoluteCameraPosition.Z += MoveYSpeed * timeElapsed * World.AbsoluteCameraUp.Z; keep = true; } // move z if (MoveZ == 0) { double d = (2.5 + Math.Abs(MoveZSpeed)) * timeElapsed; if (MoveZSpeed >= -d & MoveZSpeed <= d) { MoveZSpeed = 0.0; } else { MoveZSpeed -= (double)Math.Sign(MoveZSpeed) * d; } } else { double d = (5.0 + 10.0 - 10.0 / (1.0 + MoveZSpeed * MoveZSpeed)) * timeElapsed; double m = 25.0; MoveZSpeed += (double)MoveZ * d; if (MoveZSpeed < -m) { MoveZSpeed = -m; } else if (MoveZSpeed > m) { MoveZSpeed = m; } } if (MoveZSpeed != 0.0) { World.AbsoluteCameraPosition.X += MoveZSpeed * timeElapsed * World.AbsoluteCameraDirection.X; World.AbsoluteCameraPosition.Y += MoveZSpeed * timeElapsed * World.AbsoluteCameraDirection.Y; World.AbsoluteCameraPosition.Z += MoveZSpeed * timeElapsed * World.AbsoluteCameraDirection.Z; keep = true; } // lighting if (LightingRelative == -1) { LightingRelative = (double)LightingTarget; updatelight = true; } if (LightingTarget == 0) { if (LightingRelative != 0.0) { LightingRelative -= 0.5 * timeElapsed; if (LightingRelative < 0.0) LightingRelative = 0.0; updatelight = true; keep = true; } } else { if (LightingRelative != 1.0) { LightingRelative += 0.5 * timeElapsed; if (LightingRelative > 1.0) LightingRelative = 1.0; updatelight = true; keep = true; } } // continue if (ReducedMode) { ReducedModeEnteringTime = (int)(ticks + 3000); } else { if (keep) { ReducedModeEnteringTime = (int)(ticks + 3000); } else if (ticks > ReducedModeEnteringTime) { ReducedMode = true; World.AbsoluteCameraSide.Y = 0.0; World.Normalize(ref World.AbsoluteCameraSide.X, ref World.AbsoluteCameraSide.Y, ref World.AbsoluteCameraSide.Z); World.Normalize(ref World.AbsoluteCameraDirection.X, ref World.AbsoluteCameraDirection.Y, ref World.AbsoluteCameraDirection.Z); World.AbsoluteCameraUp = World.Cross(World.AbsoluteCameraDirection, World.AbsoluteCameraSide); } } if (updatelight) { Renderer.OptionAmbientColor.R = (byte)Math.Round(32.0 + 128.0 * LightingRelative * (2.0 - LightingRelative)); Renderer.OptionAmbientColor.G = (byte)Math.Round(32.0 + 128.0 * 0.5 * (LightingRelative + LightingRelative * (2.0 - LightingRelative))); Renderer.OptionAmbientColor.B = (byte)Math.Round(32.0 + 128.0 * LightingRelative); Renderer.OptionDiffuseColor.R = (byte)Math.Round(32.0 + 128.0 * LightingRelative); Renderer.OptionDiffuseColor.G = (byte)Math.Round(32.0 + 128.0 * LightingRelative); Renderer.OptionDiffuseColor.B = (byte)Math.Round(32.0 + 128.0 * Math.Sqrt(LightingRelative)); Renderer.InitializeLighting(); } Renderer.RenderScene(); SDL.SDL_GL_SwapWindow(SDLWindow); } // quit TextureManager.UnuseAllTextures(); if (iconSurface != IntPtr.Zero) SDL.SDL_FreeSurface(iconSurface); // free surface if (iconBmp != null && iconData != null) { iconBmp.UnlockBits(iconData); // free pixels iconBmp.Dispose(); } SDL.SDL_GL_DeleteContext(GLContext); SDL.SDL_DestroyWindow(SDLWindow); SDL.SDL_Quit(); } else { MessageBox.Show("SDL failed to create the window.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand); } }
public Bitmap GetLiveOverlay(Bitmap old_img = null) { if (old_img != null) { if (old_img.PixelFormat != System.Drawing.Imaging.PixelFormat.Format32bppArgb) { throw new Exception("cannot reuse Bitmap: PixelFormat is not Format32bppArgb"); } if (old_img.Width != bm_max_width || old_img.Height != bm_max_height) { throw new Exception("cannot reuse Bitmap; dimensions are incorrect"); } } GetImageInfoFromData(chdk_live_buffer); byte[] img = chdk_live_buffer; int image_start = bm_buf_start; int image_end = chdk_live_buffer.Length; // TODO: make static and only fill when palette actually changed int[] palette = new int[256]; byte[] alpha = { 128, 171, 214, 255 }; int pal_start = palette_data_start; int pal_end = palette_data_start + palette_size; switch (palette_type) { case 1: // 16 AYUV values case 2: // 16 AYUV values with A in 0-3 range for (int i = 0; i < 256; i++) { int off_a = 4 * (i & 0xf); int off_b = 4 * (i >> 4); int v = (sbyte)img[pal_start + off_a] + (sbyte)img[pal_start + off_b]; if (v > 127) { v = 127; } else if (v < -128) { v = -128; } int u = (sbyte)img[pal_start + off_a + 1] + (sbyte)img[pal_start + off_b + 1]; if (u > 127) { u = 127; } else if (u < -128) { u = -128; } int y = img[pal_start + off_a + 2] + img[pal_start + off_b + 2]; if (y > 255) { y = 255; } int a = (img[pal_start + off_a + 3] + img[pal_start + off_b + 3]) / 2; if (palette_type == 2) { a = alpha[a & 3]; } palette[i] = ayuv2argb((byte)a, (byte)y, (sbyte)u, (sbyte)v); } break; case 3: // 256 AYUV values with A in 0-3 range palette[0] = ayuv2argb(0, img[pal_start + 2], (sbyte)img[pal_start + 1], (sbyte)img[pal_start + 0]); // Force color 0 to be fully transparent for (int i = 4; i < palette_size; i += 4) { palette[i >> 2] = ayuv2argb(alpha[img[pal_start + i + 3] & 3], img[pal_start + i + 2], (sbyte)img[pal_start + i + 1], (sbyte)img[pal_start + i + 0]); } break; default: // Create a 'gray scale' palette; palette[0] = 0; // color 0 is fully transparent for (int i = 1; i < 256; i++) { palette[i] = ayuv2argb(255, (byte)i, 0, 0); } break; } // convert index to argb int[] pixels = new int[bm_max_width * bm_max_height]; for (int img_idx = image_start, pxls_idx = 0; img_idx < image_end; img_idx += bm_buffer_width - bm_max_width) { for (int x = 0; x < bm_max_width; x++, img_idx++, pxls_idx++) { pixels[pxls_idx] = palette[img[img_idx]]; } } // copy pixels to bitmap if (old_img == null) { old_img = new Bitmap(bm_max_width, bm_max_height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); } System.Drawing.Imaging.BitmapData bmpd = old_img.LockBits(new Rectangle(0, 0, bm_max_width, bm_max_height), System.Drawing.Imaging.ImageLockMode.WriteOnly, old_img.PixelFormat); System.Runtime.InteropServices.Marshal.Copy(pixels, 0, bmpd.Scan0, pixels.Length); old_img.UnlockBits(bmpd); return(old_img); }
public static unsafe ManagedImage LoadTGAImage(System.IO.Stream source, bool mask) { byte[] buffer = new byte[source.Length]; source.Read(buffer, 0, buffer.Length); System.IO.MemoryStream ms = new System.IO.MemoryStream(buffer); System.IO.BinaryReader br = new System.IO.BinaryReader(ms); tgaHeader header = new tgaHeader(); header.Read(br); if (header.ImageSpec.PixelDepth != 8 && header.ImageSpec.PixelDepth != 16 && header.ImageSpec.PixelDepth != 24 && header.ImageSpec.PixelDepth != 32) throw new ArgumentException("Not a supported tga file."); if (header.ImageSpec.AlphaBits > 8) throw new ArgumentException("Not a supported tga file."); if (header.ImageSpec.Width > 4096 || header.ImageSpec.Height > 4096) throw new ArgumentException("Image too large."); byte[] decoded = new byte[header.ImageSpec.Width * header.ImageSpec.Height * 4]; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); fixed (byte* pdecoded = &decoded[0]) { bd.Width = header.ImageSpec.Width; bd.Height = header.ImageSpec.Height; bd.PixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppPArgb; bd.Stride = header.ImageSpec.Width * 4; bd.Scan0 = (IntPtr)pdecoded; switch (header.ImageSpec.PixelDepth) { case 8: decodeStandard8(bd, header, br); break; case 16: if (header.ImageSpec.AlphaBits > 0) decodeSpecial16(bd, header, br); else decodeStandard16(bd, header, br); break; case 24: if (header.ImageSpec.AlphaBits > 0) decodeSpecial24(bd, header, br); else decodeStandard24(bd, header, br); break; case 32: decodeStandard32(bd, header, br); break; default: return null; } } int n = header.ImageSpec.Width * header.ImageSpec.Height; ManagedImage image; if (mask && header.ImageSpec.AlphaBits == 0 && header.ImageSpec.PixelDepth == 8) { image = new ManagedImage(header.ImageSpec.Width, header.ImageSpec.Height, ManagedImage.ImageChannels.Alpha); int p = 3; for (int i = 0; i < n; i++) { image.Alpha[i] = decoded[p]; p += 4; } } else { image = new ManagedImage(header.ImageSpec.Width, header.ImageSpec.Height, ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha); int p = 0; for (int i = 0; i < n; i++) { image.Blue[i] = decoded[p++]; image.Green[i] = decoded[p++]; image.Red[i] = decoded[p++]; image.Alpha[i] = decoded[p++]; } } br.Close(); return image; }
/// <summary> /// Read an image file, covert the data and save it to the native pointer /// </summary> /// <typeparam name="T">The type of the data to covert the image pixel values to. e.g. "float" or "byte"</typeparam> /// <param name="fileName">The name of the image file</param> /// <param name="dest">The native pointer where the image pixels values will be saved to.</param> /// <param name="inputHeight">The height of the image, must match the height requirement for the tensor</param> /// <param name="inputWidth">The width of the image, must match the width requirement for the tensor</param> /// <param name="inputMean">The mean value, it will be subtracted from the input image pixel values</param> /// <param name="scale">The scale, after mean is subtracted, the scale will be used to multiply the pixel values</param> /// <param name="flipUpSideDown">If true, the image needs to be flipped up side down</param> /// <param name="swapBR">If true, will flip the Blue channel with the Red. e.g. If false, the tensor's color channel order will be RGB. If true, the tensor's color channle order will be BGR </param> public static void ReadImageFileToTensor <T>( String fileName, IntPtr dest, int inputHeight = -1, int inputWidth = -1, float inputMean = 0.0f, float scale = 1.0f, bool flipUpSideDown = false, bool swapBR = false) where T : struct { if (!File.Exists(fileName)) { throw new FileNotFoundException(String.Format("File {0} do not exist.", fileName)); } //if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) { //Read the file using Bitmap class System.Drawing.Bitmap bmp = new Bitmap(fileName); if (inputHeight > 0 || inputWidth > 0) { //resize bmp System.Drawing.Bitmap newBmp = new Bitmap(bmp, inputWidth, inputHeight); bmp.Dispose(); bmp = newBmp; //bmp.Save("tmp.png"); } if (flipUpSideDown) { bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); } int bmpWidth = bmp.Width; int bmpHeight = bmp.Height; System.Drawing.Imaging.BitmapData bd = new System.Drawing.Imaging.BitmapData(); bmp.LockBits( new Rectangle(0, 0, bmpWidth, bmpHeight), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb, bd); int stride = bd.Stride; byte[] byteValues = new byte[bmpHeight * stride]; Marshal.Copy(bd.Scan0, byteValues, 0, byteValues.Length); bmp.UnlockBits(bd); if (typeof(T) == typeof(float)) { int imageSize = bmpWidth * bmpHeight; float[] floatValues = new float[imageSize * 3]; if (swapBR) { int idx = 0; int rowOffset = 0; for (int i = 0; i < bmpHeight; ++i) { int rowPtr = rowOffset; for (int j = 0; j < bmpWidth; ++j) { float b = ((float)byteValues[rowPtr++] - inputMean) * scale; float g = ((float)byteValues[rowPtr++] - inputMean) * scale; float r = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = r; floatValues[idx++] = g; floatValues[idx++] = b; } rowOffset += stride; } } else { int idx = 0; int rowOffset = 0; for (int i = 0; i < bmpHeight; ++i) { int rowPtr = rowOffset; for (int j = 0; j < bmpWidth; ++j) { floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; floatValues[idx++] = ((float)byteValues[rowPtr++] - inputMean) * scale; } rowOffset += stride; } } Marshal.Copy(floatValues, 0, dest, floatValues.Length); } else if (typeof(T) == typeof(byte)) { int imageSize = bmp.Width * bmp.Height; if (swapBR) { int idx = 0; for (int i = 0; i < bmpHeight; ++i) { int offset = i * stride; for (int j = 0; j < bmpWidth; ++j) { byte b = (byte)(((float)byteValues[offset++] - inputMean) * scale); byte g = (byte)(((float)byteValues[offset++] - inputMean) * scale); byte r = (byte)(((float)byteValues[offset++] - inputMean) * scale); byteValues[idx++] = r; byteValues[idx++] = g; byteValues[idx++] = b; } } } else { int idx = 0; for (int i = 0; i < bmpHeight; ++i) { int offset = i * stride; for (int j = 0; j < bmpWidth * 3; ++j) { byteValues[idx++] = (byte)(((float)byteValues[offset++] - inputMean) * scale); } } } Marshal.Copy(byteValues, 0, dest, imageSize * 3); } else { throw new NotImplementedException(String.Format("Destination data type {0} is not supported.", typeof(T).ToString())); } } /* * else //Unix * { * //if (flipUpSideDown) * // throw new NotImplementedException("Flip Up Side Down is Not implemented"); * * throw new NotImplementedException("Not implemented"); * }*/ }