/// <summary> /// Converts the pixel data to a bitmap image /// </summary> /// <param name="pixels"></param> /// <returns></returns> internal static unsafe System.Drawing.Bitmap ConvertDataToImage(int[] pixels, int width, int height) { if (width <= 0 || height <= 0) { return(null); } System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height, PixelFormat.Format24bppRgb); BitmapData bits = bmp.LockBits(new System.Drawing.Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, bmp.PixelFormat); // Value of 4 is the size of PixelFormat.Format32bppArgb // keep it synchronized with used Bitmap PixelFormat int bytesPerRow = width * 4; fixed(int *pixelsPtr = pixels) { byte *pixelsNativePtr = (byte *)pixelsPtr; for (int y = 0; y < height; y++) { var rowPtr = (int *)((byte *)bits.Scan0 + (y * bits.Stride)); pixelsNativePtr += (y * bytesPerRow); MemoryUtilities.MoveMemory(rowPtr, pixelsNativePtr, bytesPerRow); } } bmp.UnlockBits(bits); return(bmp); }
private System.Drawing.Bitmap InvertImage(System.Drawing.Bitmap invertImage) { return(null); //if (invertImage == null) //{ // return null; //} //var image = (System.Drawing.Bitmap)invertImage.Clone(); //BitmapData imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), // ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); //int height = image.Height; //int width = image.Width; //Parallel.For( // 0, // height, // y => // { // uint* imageRow = (uint*)(imageData.Scan0 + (y * imageData.Stride)); // for (int x = 0; x < width; x++) // { // // Check if the mask byte is set // imageRow[x] = InvertColor(imageRow[x]); // } // }); //image.UnlockBits(imageData); //return image; }
private unsafe System.Drawing.Bitmap InvertImage(System.Drawing.Bitmap invertImage) { if (invertImage == null) { return(null); } var image = (System.Drawing.Bitmap)invertImage.Clone(); BitmapData imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int height = image.Height; int width = image.Width; Parallel.For( 0, height, y => { uint *imageRow = (uint *)(imageData.Scan0 + (y * imageData.Stride)); for (int x = 0; x < width; x++) { // Check if the mask byte is set imageRow[x] = InvertColor(imageRow[x]); } }); image.UnlockBits(imageData); return(image); }
internal static unsafe System.Drawing.Bitmap InvertImage(System.Drawing.Bitmap sourceBitmap) { if (sourceBitmap == null) { return(null); } Bitmap invertedBitmap = Unsafe.As <System.Drawing.Bitmap>(sourceBitmap.Clone()); BitmapData imageData = invertedBitmap.LockBits(new System.Drawing.Rectangle(0, 0, invertedBitmap.Width, invertedBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int height = invertedBitmap.Height; int width = invertedBitmap.Width; for (int y = 0; y < height; y++) //Parallel.For( // 0, // height, // y => { uint *imageRow = (uint *)(imageData.Scan0 + (y * imageData.Stride)); for (int x = 0; x < width; x++) { imageRow[x] = InvertColor(imageRow[x]); } //}); } invertedBitmap.UnlockBits(imageData); return(invertedBitmap); }
/// <summary> /// Resizes the image to the new dimensions /// </summary> /// <param name="srcImage"></param> /// <param name="newWidth"></param> /// <param name="newHeight"></param> /// <returns></returns> public static System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap srcImage, int newWidth, int newHeight) { if (srcImage == null) { throw new DjvuArgumentNullException(nameof(srcImage)); } // Check if the image needs resizing if (srcImage.Width == newWidth && srcImage.Height == newHeight) { return(srcImage); } if (newWidth <= 0 || newHeight <= 0) { throw new DjvuArgumentException( $"Invalid new image dimensions width: {newWidth}, height: {newHeight}", nameof(newWidth) + " " + nameof(newHeight)); } // Resize the image System.Drawing.Bitmap newImage = new System.Drawing.Bitmap(newWidth, newHeight, srcImage.PixelFormat); using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(newImage)) { gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.DrawImage(srcImage, new System.Drawing.Rectangle(0, 0, newWidth, newHeight)); } srcImage.Dispose(); return(newImage); }
static bool AlreadyAdded(int x, int y, ref System.Drawing.Bitmap bmp) { if ((x < 0) || (y < 0) || (x >= bmpSize.Width) || (y >= bmpSize.Height)) { return(true); } return(alreadyAdded[x, y]); }
public static Image PieceToImage(Piece piece) { string imagePath = string.Format(@"images\{0}.png", NotationParser.GetNotationForPiece(piece)); var bitmap = new System.Drawing.Bitmap(imagePath); Image image = new Image(); image.Source = BitmapToImageSource(bitmap); return(image); }
/// <summary> /// Creates a blank image with the given color /// </summary> /// <param name="imageColor"></param> /// <returns></returns> public static System.Drawing.Bitmap CreateBlankImage(Brush imageColor, int width, int height) { System.Drawing.Bitmap newBackground = new System.Drawing.Bitmap(width, height); // Fill the whole image with white using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newBackground)) g.FillRegion(imageColor, new Region(new System.Drawing.Rectangle(0, 0, width, height))); return(newBackground); }
/// <summary> /// Makes a copy of a bitmap as a Cairo.ImageSurface. No need to unlock the bitmap later. /// I don't know why, but this seems to have caused segfaults, so don't use it I guess... /// </summary> public static Cairo.Surface CopyBitmap(System.Drawing.Bitmap bitmap) { throw new Exception("This function caused segfaults, don't use it..."); byte[] data; using (Cairo.ImageSurface surface = new BitmapSurface(bitmap)) { data = new byte[surface.Height * surface.Stride]; System.Runtime.InteropServices.Marshal.Copy(surface.DataPtr, data, 0, data.Length); return(new Cairo.ImageSurface(data, surface.Format, surface.Width, surface.Height, surface.Stride)); } }
/// <summary> /// Clears the stored image from memory /// </summary> public void ClearImage() { IsPageImageCached = false; if (_image != null) { _image.Dispose(); _image = null; } }
public static Texture2D ConvertToTexture(System.Drawing.Bitmap b, GraphicsDevice graphicsDevice) { Texture2D tx = null; using (MemoryStream s = new MemoryStream()) { b.Save(s, System.Drawing.Imaging.ImageFormat.Png); s.Seek(0, SeekOrigin.Begin); tx = Texture2D.FromStream(graphicsDevice, s); } return(tx); }
// Converts BitmapImages to Bitmaps private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage) { using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapImage)); enc.Save(outStream); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream); return(new Bitmap(bitmap)); } }
public BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap bitmap) { IntPtr hBitmap = bitmap.GetHbitmap(); BitmapSource source; try { source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(hBitmap); } return(source); }
protected virtual void Dispose(bool disposing) { if (Disposed) { return; } if (disposing) { } _Image?.Dispose(); _Image = null; _ThumbnailImage?.Dispose(); _ThumbnailImage = null; _Disposed = true; }
internal static void LoadTextureInternal(Texture t, System.Drawing.Bitmap bmp) { System.Drawing.Imaging.PixelFormat lock_format; switch (bmp.PixelFormat) { case System.Drawing.Imaging.PixelFormat.Format32bppArgb: lock_format = System.Drawing.Imaging.PixelFormat.Format32bppArgb; break; case System.Drawing.Imaging.PixelFormat.Format24bppRgb: lock_format = System.Drawing.Imaging.PixelFormat.Format32bppArgb; break; default: t.Failed = true; return; } int glTex; // Create the opengl texture GL.GenTextures(1, out glTex); GL.BindTexture(TextureTarget.Texture2D, glTex); lastTextureID = glTex; GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); // Sort out our GWEN texture t.RendererData = glTex; t.Width = bmp.Width; t.Height = bmp.Height; var data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, lock_format); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, t.Width, t.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); bmp.UnlockBits(data); bmp.Dispose(); }
/// <summary> /// Converts the pixel data to a bitmap image /// </summary> /// <param name="pixels"></param> /// <returns></returns> private unsafe System.Drawing.Bitmap ConvertDataToImage(int[] pixels) { // create a bitmap and manipulate it System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Info.Width, Info.Height, PixelFormat.Format32bppArgb); BitmapData bits = bmp.LockBits(new System.Drawing.Rectangle(0, 0, Info.Width, Info.Height), ImageLockMode.ReadWrite, bmp.PixelFormat); for (int y = 0; y < Info.Height; y++) { var row = (int *)((byte *)bits.Scan0 + (y * bits.Stride)); for (int x = 0; x < Info.Width; x++) { row[x] = pixels[y * Info.Width + x]; } } bmp.UnlockBits(bits); return(bmp); }
static bool IsBlack(int x, int y, ref System.Drawing.Bitmap bmp) { if ((x < 0) || (y < 0) || (x >= bmpSize.Width) || (y >= bmpSize.Height)) { return(false); } if (isBlack[x, y]) { return(true); } int threshold = 50; //System.Drawing.Color clr = bmp.GetPixel(x, y); Color clr = pixels[x, y]; if ((clr.R < threshold) && (clr.G < threshold) && (clr.B < threshold)) { return(true); } return(false); }
static Point GetBlackNextToChecked(ref System.Drawing.Bitmap bmp) { for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { if (!wasChecked[x, y]) { if (isCheckedAndBlack(x, y - 1) || isCheckedAndBlack(x + 1, y) || isCheckedAndBlack(x, y + 1) || (isCheckedAndBlack(x - 1, y))) { if (IsBlack(x, y, ref bmp)) { return(new Point(x, y)); } } } } } return(new Point(-1, -1)); }
/// <summary> /// Resizes the image to the new dimensions /// </summary> /// <param name="srcImage"></param> /// <param name="newWidth"></param> /// <param name="newHeight"></param> /// <returns></returns> public System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap srcImage, int newWidth, int newHeight) { // Check if the image needs resizing if (srcImage.Width == newWidth && srcImage.Height == newHeight) { return(srcImage); } // Resize the image System.Drawing.Bitmap newImage = new System.Drawing.Bitmap(newWidth, newHeight); using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(newImage)) { gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.DrawImage(srcImage, new System.Drawing.Rectangle(0, 0, newWidth, newHeight)); } srcImage.Dispose(); return(newImage); }
/// <summary> /// Converts the pixel data to a bitmap image /// </summary> /// <param name="pixels"></param> /// <returns></returns> internal static unsafe System.Drawing.Bitmap ConvertDataToImage(int[] pixels, int width, int height) { if (width <= 0 || height <= 0) { return(null); } System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height, PixelFormat.Format32bppArgb); BitmapData bits = bmp.LockBits(new System.Drawing.Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, bmp.PixelFormat); for (int y = 0; y < height; y++) { var row = (int *)((byte *)bits.Scan0 + (y * bits.Stride)); for (int x = 0; x < width; x++) { row[x] = pixels[y * width + x]; } } bmp.UnlockBits(bits); return(bmp); }
internal static BitmapSource ConvertToBitmapSource(System.Drawing.Bitmap wfBitmap) { /*var hBitmap = gdiPlusBitmap.GetHbitmap(); * return Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());*/ // WPF version of Image var bi3 = new BitmapImage(); bi3.BeginInit(); // Save to a memory stream... var ms = new MemoryStream(); wfBitmap.Save(ms, ImageFormat.Png); // Rewind the stream... ms.Seek(0, SeekOrigin.Begin); // Tell the WPF image to use this stream... bi3.StreamSource = ms; bi3.EndInit(); return(bi3); }
protected Bitmap LoadBitmapFromResourceWithScaling(string name) { var assembly = Assembly.GetExecutingAssembly(); bool needsScaling = false; Bitmap bmp; if (windowScaling == 1.5f && assembly.GetManifestResourceInfo($"FamiStudio.Resources.{name}@15x.png") != null) { bmp = PlatformUtils.LoadBitmapFromResource($"FamiStudio.Resources.{name}@15x.png"); } else if (windowScaling > 1.0f && assembly.GetManifestResourceInfo($"FamiStudio.Resources.{name}@2x.png") != null) { bmp = PlatformUtils.LoadBitmapFromResource($"FamiStudio.Resources.{name}@2x.png"); needsScaling = windowScaling != 2.0f; } else { bmp = PlatformUtils.LoadBitmapFromResource($"FamiStudio.Resources.{name}.png"); } // Pre-resize all images so we dont have to deal with scaling later. if (needsScaling) { var newWidth = Math.Max(1, (int)(bmp.Width * (windowScaling / 2.0f))); var newHeight = Math.Max(1, (int)(bmp.Height * (windowScaling / 2.0f))); #if FAMISTUDIO_WINDOWS bmp = new System.Drawing.Bitmap(bmp, newWidth, newHeight); #else bmp = bmp.ScaleSimple(newWidth, newHeight, Gdk.InterpType.Bilinear); #endif } return(bmp); }
private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage) { using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(bitmapImage)); enc.Save(outStream); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream); return new Bitmap(bitmap); } }
/// <summary> /// Gets the image for the page /// </summary> /// <returns> /// <see cref="System.Drawing.Bitmap"/>Bitmap image. /// </returns> public unsafe System.Drawing.Bitmap BuildImage(int subsample = 1) { // // TODO Fix image skew // Verify.SubsampleRange(subsample); lock (_LoadingLock) { Stopwatch stopWatch = Stopwatch.StartNew(); System.Drawing.Bitmap background = GetBackgroundImage(subsample, false); stopWatch.Stop(); // TODO ETW logging goes here stopWatch.Restart(); using (System.Drawing.Bitmap foreground = GetForegroundImage(subsample, false)) { stopWatch.Stop(); // TODO ETW logging goes here stopWatch.Restart(); using (System.Drawing.Bitmap mask = GetTextImage(subsample, false)) { stopWatch.Stop(); // TODO ETW logging goes here stopWatch.Restart(); _HasLoaded = true; BitmapData backgroundData = background.LockBits(new System.Drawing.Rectangle(0, 0, background.Width, background.Height), ImageLockMode.ReadWrite, background.PixelFormat); int backgroundPixelSize = DjvuImage.GetPixelSize(backgroundData.PixelFormat); BitmapData foregroundData = foreground.LockBits(new System.Drawing.Rectangle(0, 0, foreground.Width, foreground.Height), ImageLockMode.ReadOnly, foreground.PixelFormat); int foregroundPixelSize = DjvuImage.GetPixelSize(foregroundData.PixelFormat); BitmapData maskData = mask.LockBits(new System.Drawing.Rectangle(0, 0, mask.Width, mask.Height), ImageLockMode.ReadOnly, mask.PixelFormat); //int maskPixelSize = GetPixelSize(maskData); int bgndHeight = background.Height; int bgndWidth = background.Width; int fgndHeight = foreground.Height; int fgndWidth = foreground.Width; int maskHeight = mask.Height; int maskWidth = mask.Width; int maskbgnH = maskHeight / bgndHeight; int maskfgnH = maskHeight / fgndHeight; int maskbgnW = maskWidth / bgndWidth; int maskfgnW = maskWidth / fgndWidth; //Parallel.For( // 0, // height, // y => // { ; for (int y = 0, yf = 0, yb = 0; y < maskHeight && yb < bgndHeight && yf < fgndHeight; y++) { byte *maskRow = (byte *)maskData.Scan0 + (y * maskData.Stride); uint *backgroundRow = (uint *)(backgroundData.Scan0 + (yb * backgroundData.Stride)); uint *foregroundRow = (uint *)(foregroundData.Scan0 + (yf * foregroundData.Stride)); for (int x = 0, xf = 0, xb = 0; x < bgndWidth && xb < maskWidth && xf < fgndWidth; x++) { // Check if the mask byte is set if (maskRow[x] > 0) { uint xF = foregroundRow[xf]; if (_IsInverted) { backgroundRow[xb] = InvertColor(xF); } else { backgroundRow[xb] = xF; } } else if (_IsInverted == true) { uint xB = backgroundRow[xb]; backgroundRow[xb] = InvertColor(xB); } if (x > 0) { if (x % maskbgnW == 0) { xb++; } if (x % maskfgnW == 0) { xf++; } } } if (y > 0) { if (y % maskbgnH == 0) { yb++; } if (y % maskfgnH == 0) { yf++; } } } //}); mask.UnlockBits(maskData); foreground.UnlockBits(foregroundData); background.UnlockBits(backgroundData); stopWatch.Stop(); // TODO ETW logging goes here return(background); } } } }
internal PageImage GetPageImage(Report rpt, Row row) { string mtype = null; Stream strm = null; System.Drawing.Bitmap im = null; PageImage pi = null; WorkClass wc = GetWC(rpt); if (wc.PgImage != null) { // have we already generated this one // reuse most of the work; only position will likely change pi = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH); pi.Name = wc.PgImage.Name; // this is name it will be shared under return(pi); } try { strm = GetImageStream(rpt, row, out mtype); if (strm == null) { rpt.rl.LogError(4, string.Format("Unable to load image {0}.", this._Value == null?"": this._Value.EvaluateString(rpt, row))); return(null); } im = Bitmap.FromStream(strm); int height = im.Height; int width = im.Width; MemoryStream ostrm = new MemoryStream(); ImageFormat imf; // if (mtype.ToLower() == "image/jpeg") //TODO: how do we get png to work // imf = ImageFormatType.Jpeg; // else imf = ImageFormat.Jpeg; System.Drawing.Imaging.ImageCodecInfo[] info; info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQualityManager.EmbeddedImageQuality); System.Drawing.Imaging.ImageCodecInfo codec = null; for (int i = 0; i < info.Length; i++) { if (info[i].FormatDescription == "JPEG") { codec = info[i]; break; } } im.Save(ostrm, codec, encoderParameters); byte[] ba = ostrm.ToArray(); ostrm.Close(); pi = new PageImage(imf, ba, width, height); pi.SI = new StyleInfo(); // this will just default everything if (_BackgroundRepeat != null) { string r = _BackgroundRepeat.EvaluateString(rpt, row).ToLower(); switch (r) { case "repeat": pi.Repeat = ImageRepeat.Repeat; break; case "repeatx": pi.Repeat = ImageRepeat.RepeatX; break; case "repeaty": pi.Repeat = ImageRepeat.RepeatY; break; case "norepeat": default: pi.Repeat = ImageRepeat.NoRepeat; break; } } else { pi.Repeat = ImageRepeat.Repeat; } if (_ConstantImage) { wc.PgImage = pi; // create unique name; PDF generation uses this to optimize the saving of the image only once pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString(); // create unique name } } finally { if (strm != null) { strm.Close(); } if (im != null) { im.Dispose(); } } return(pi); }
public static Bitmap ToWhiteBorder(System.Drawing.Bitmap bmpOriginal, System.Drawing.KnownColor knownColor) { System.Drawing.Color subColor = GetCompatibleColor(knownColor); Bitmap untouchedImage = CreateNonIndexedImage(bmpOriginal); Bitmap bmp = CreateNonIndexedImage(bmpOriginal); System.Drawing.Size size = bmp.Size; isBlack = new bool[bmp.Width, bmp.Height]; wasChecked = new bool[bmp.Width, bmp.Height]; alreadyAdded = new bool[bmp.Width, bmp.Height]; bool[,] isContiguous = new bool[bmp.Width, bmp.Height]; pixels = new Color[bmp.Width, bmp.Height]; for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { isBlack[x, y] = false; wasChecked[x, y] = false; alreadyAdded[x, y] = false; pixels[x, y] = bmp.GetPixel(x, y); } } bmpSize = bmp.Size; List <Point> continguousEdges = new List <Point>(); Point startPoint = new Point(5, 5); continguousEdges.Add(startPoint); Point topRight = new Point(bmp.Width - 5, 5); continguousEdges.Add(topRight); Point bottomRight = new Point(bmp.Width - 5, bmp.Height - 5); continguousEdges.Add(bottomRight); bool pointAdded = true; while (continguousEdges.Count > 0) { pointAdded = false; if (continguousEdges.Count > 0) { Point point = continguousEdges[0]; // Check in each direction //left if (!AlreadyAdded(point.X - 1, point.Y, ref bmp) && IsBlack(point.X - 1, point.Y, ref bmp)) { alreadyAdded[point.X - 1, point.Y] = true; continguousEdges.Add(new Point(point.X - 1, point.Y)); pointAdded = true; } //right if (!AlreadyAdded(point.X + 1, point.Y, ref bmp) && IsBlack(point.X + 1, point.Y, ref bmp)) { alreadyAdded[point.X + 1, point.Y] = true; continguousEdges.Add(new Point(point.X + 1, point.Y)); pointAdded = true; } //Up if (!AlreadyAdded(point.X, point.Y - 1, ref bmp) && IsBlack(point.X, point.Y - 1, ref bmp)) { alreadyAdded[point.X, point.Y - 1] = true; continguousEdges.Add(new Point(point.X, point.Y - 1)); pointAdded = true; } //Down if (!AlreadyAdded(point.X, point.Y + 1, ref bmp) && IsBlack(point.X, point.Y + 1, ref bmp)) { alreadyAdded[point.X, point.Y + 1] = true; continguousEdges.Add(new Point(point.X, point.Y + 1)); pointAdded = true; } foreach (var pt in continguousEdges) { if ((pt.X == point.X) && (pt.Y == point.Y)) { continguousEdges.Remove(pt); break; } } } } for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { if (alreadyAdded[x, y]) { isBlack[x, y] = true; } } } int xMiddle = bmp.Width / 2 + 50; // Find top of bottom border (we want to invert the bottom) int innerBottomBorder = bmp.Height; for (int y = bmp.Height - 1; y > bmp.Height / 2; y--) { if (isBlack[xMiddle, y]) { innerBottomBorder = y; } else { //break; } } int innerTopBorder = 0; for (int y = 1; y < bmp.Height / 2; y++) { if (isBlack[xMiddle, y]) { innerTopBorder = y; } else { //break; } } int innerLeft = 0; int innerRight = bmp.Width; // Find the inner-left and inner-right border for (int x = 2; x < bmp.Width / 2; x++) { if (isBlack[x, 25]) { innerLeft = x; } else { //break; } } // Find the inner-left and inner-right border for (int x = bmp.Width - 1; x > bmp.Width / 2; x--) { if (isBlack[x, 25]) { innerRight = x; } else { //break; } } System.Drawing.Color drawingColor = subColor; System.Drawing.Bitmap whitedOut = bmp; // Detect system cards and force a 15-pixel border if ((innerBottomBorder < bmp.Height - 1) && (innerTopBorder > 0) && (innerLeft > 0) && (innerRight < bmp.Width)) { int defaultBorder = 15; int maxBorder = 25; if ((innerBottomBorder < (bmp.Height - maxBorder)) || (innerTopBorder > maxBorder) || (innerLeft > maxBorder) || (innerRight < bmp.Width - maxBorder)) { // System card detected! Add 4 borders of 15 pixels each! innerBottomBorder = bmp.Height - defaultBorder; innerTopBorder = defaultBorder; innerLeft = defaultBorder; innerRight = bmp.Width - defaultBorder; } } /* * // Invert the bottom-border and then sub-out all of the other pixels * for (int x = 0; x < whitedOut.Width; x++) * { * for (int y = 0; y < whitedOut.Height; y++) * { * if (y >= innerBottomBorder) * { * Color oldPixel = whitedOut.GetPixel(x, y); * whitedOut.SetPixel(x, y, Color.FromArgb(255 - oldPixel.R, 255 - oldPixel.G, 255 - oldPixel.B)); * } * * * if ((x <= innerLeft) || (x >= innerRight) || (y <= innerTopBorder) || (y >= innerBottomBorder)) * { * if (isBlack[x, y]) * { * whitedOut.SetPixel(x, y, drawingColor); * } * } * } * } */ /* * // If not turning white, remove any white pixels * if (subColor != System.Drawing.Color.White) * { * // Remove any white pixels * for (int x = 0; x < whitedOut.Width; x++) * { * for (int y = 0; y < whitedOut.Height; y++) * { * if (y >= innerBottomBorder) * { * int whiteThreshold = 150; * Color oldPixel = whitedOut.GetPixel(x, y); * if ((oldPixel.R > whiteThreshold) && (oldPixel.G > whiteThreshold) && (oldPixel.B > whiteThreshold)) * { * whitedOut.SetPixel(x, y, drawingColor); * } * } * } * } * } */ // Blank out the entire inside of the card for (int x = innerLeft - 1; x <= innerRight + 1; x++) { for (int y = innerTopBorder; y <= innerBottomBorder; y++) { whitedOut.SetPixel(x, y, drawingColor); } } System.Drawing.Rectangle innerImageRect = new System.Drawing.Rectangle(innerLeft, innerTopBorder, innerRight - innerLeft, innerBottomBorder - innerTopBorder); System.Drawing.PointF[] points = new System.Drawing.PointF[3]; //points[0] = new System.Drawing.PointF(15, 15); //points[1] = new System.Drawing.PointF(335, 15); //points[2] = new System.Drawing.PointF(15, 475); // Image needs to be 350x490 with 16-pixel border int newWidth = 350; int newHeight = 490; float borderSize = 14; //int newWidth = 179; //int newHeight = 250; //float borderSize = 7.5f; float widthHeightRatio = (float)innerImageRect.Width / (float)innerImageRect.Height; points[0] = new System.Drawing.PointF(borderSize, borderSize); points[1] = new System.Drawing.PointF(newWidth - borderSize, borderSize); points[2] = new System.Drawing.PointF(borderSize, (newWidth - (borderSize * 2.0f)) / widthHeightRatio + borderSize); /* Debugging redraw capabilities * points[0] = new System.Drawing.PointF(20, 20); * points[1] = new System.Drawing.PointF(320, 20); * points[2] = new System.Drawing.PointF(20, 450); */ // First, scale the image down to 350x490 System.Drawing.Bitmap scaledDown = new System.Drawing.Bitmap(newWidth, newHeight); using (System.Drawing.Graphics graphics = Graphics.FromImage(scaledDown)) { graphics.DrawImage(whitedOut, new System.Drawing.PointF[3] { new System.Drawing.PointF(0, 0), new System.Drawing.PointF(newWidth, 0), new System.Drawing.PointF(0, newHeight) }); } // Next, re-draw the original image on top of the whited-out version using (System.Drawing.Graphics graphics = Graphics.FromImage(scaledDown)) { graphics.DrawImage(untouchedImage, points, innerImageRect, System.Drawing.GraphicsUnit.Pixel); } whitedOut = scaledDown; /* * // Draw a slight black border around the whole image for cutting purposes * for (int x = 0; x < whitedOut.Width; x++) * { * for (int y = 0; y < whitedOut.Height; y++) * { * if ((y == whitedOut.Height - 1) || (x == whitedOut.Width - 1) || * (y == 0) || (x == 0)) * { * whitedOut.SetPixel(x, y, Color.FromArgb(255, 200, 200, 200)); * } * } * } */ return(whitedOut); }
public static Bitmap ToWhiteBorder(System.Drawing.Bitmap bmpOriginal, System.Drawing.KnownColor knownColor) { System.Drawing.Color subColor = GetCompatibleColor(knownColor); Bitmap bmp = CreateNonIndexedImage(bmpOriginal); System.Drawing.Size size = bmp.Size; isBlack = new bool[bmp.Width, bmp.Height]; wasChecked = new bool[bmp.Width, bmp.Height]; alreadyAdded = new bool[bmp.Width, bmp.Height]; bool[,] isContiguous = new bool[bmp.Width, bmp.Height]; pixels = new Color[bmp.Width, bmp.Height]; for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { isBlack[x, y] = false; wasChecked[x, y] = false; alreadyAdded[x, y] = false; pixels[x, y] = bmp.GetPixel(x, y); } } bmpSize = bmp.Size; List <Point> continguousEdges = new List <Point>(); Point startPoint = new Point(5, 5); continguousEdges.Add(startPoint); Point topRight = new Point(bmp.Width - 5, 5); continguousEdges.Add(topRight); Point bottomRight = new Point(bmp.Width - 5, bmp.Height - 5); continguousEdges.Add(bottomRight); bool pointAdded = true; while (continguousEdges.Count > 0) { pointAdded = false; if (continguousEdges.Count > 0) { Point point = continguousEdges[0]; // Check in each direction //left if (!AlreadyAdded(point.X - 1, point.Y, ref bmp) && IsBlack(point.X - 1, point.Y, ref bmp)) { alreadyAdded[point.X - 1, point.Y] = true; continguousEdges.Add(new Point(point.X - 1, point.Y)); pointAdded = true; } //right if (!AlreadyAdded(point.X + 1, point.Y, ref bmp) && IsBlack(point.X + 1, point.Y, ref bmp)) { alreadyAdded[point.X + 1, point.Y] = true; continguousEdges.Add(new Point(point.X + 1, point.Y)); pointAdded = true; } //Up if (!AlreadyAdded(point.X, point.Y - 1, ref bmp) && IsBlack(point.X, point.Y - 1, ref bmp)) { alreadyAdded[point.X, point.Y - 1] = true; continguousEdges.Add(new Point(point.X, point.Y - 1)); pointAdded = true; } //Down if (!AlreadyAdded(point.X, point.Y + 1, ref bmp) && IsBlack(point.X, point.Y + 1, ref bmp)) { alreadyAdded[point.X, point.Y + 1] = true; continguousEdges.Add(new Point(point.X, point.Y + 1)); pointAdded = true; } foreach (var pt in continguousEdges) { if ((pt.X == point.X) && (pt.Y == point.Y)) { continguousEdges.Remove(pt); break; } } } } for (int x = 0; x < bmp.Width; x++) { for (int y = 0; y < bmp.Height; y++) { if (alreadyAdded[x, y]) { isBlack[x, y] = true; } } } int xMiddle = bmp.Width / 2; // Find top of bottom border (we want to invert the bottom) int innerBottomBorder = bmp.Height; for (int y = bmp.Height - 1; y > bmp.Height / 2; y--) { if (isBlack[xMiddle, y]) { innerBottomBorder = y; } else { //break; } } int innerTopBorder = 0; for (int y = 1; y < bmp.Height / 2; y++) { if (isBlack[xMiddle, y]) { innerTopBorder = y; } else { //break; } } int innerLeft = 0; int innerRight = bmp.Width; // Find the inner-left and inner-right border for (int x = 2; x < bmp.Width / 2; x++) { if (isBlack[x, 25]) { innerLeft = x; } else { //break; } } // Find the inner-left and inner-right border for (int x = bmp.Width - 1; x > bmp.Width / 2; x--) { if (isBlack[x, 25]) { innerRight = x; } else { //break; } } System.Drawing.Color drawingColor = subColor; System.Drawing.Bitmap whitedOut = bmp; // Detect system cards and force a 15-pixel border if ((innerBottomBorder < bmp.Height - 1) && (innerTopBorder > 0) && (innerLeft > 0) && (innerRight < bmp.Width)) { int defaultBorder = 15; int maxBorder = 25; if ((innerBottomBorder < (bmp.Height - maxBorder)) || (innerTopBorder > maxBorder) || (innerLeft > maxBorder) || (innerRight < bmp.Width - maxBorder)) { // System card detected! Add 4 borders of 15 pixels each! innerBottomBorder = bmp.Height - defaultBorder; innerTopBorder = defaultBorder; innerLeft = defaultBorder; innerRight = bmp.Width - defaultBorder; } } // Invert the bottom-border and then sub-out all of the other pixels for (int x = 0; x < whitedOut.Width; x++) { for (int y = 0; y < whitedOut.Height; y++) { if (y >= innerBottomBorder) { Color oldPixel = whitedOut.GetPixel(x, y); whitedOut.SetPixel(x, y, Color.FromArgb(255 - oldPixel.R, 255 - oldPixel.G, 255 - oldPixel.B)); } if ((x <= innerLeft) || (x >= innerRight) || (y <= innerTopBorder) || (y >= innerBottomBorder)) { if (isBlack[x, y]) { whitedOut.SetPixel(x, y, drawingColor); } } } } // If not turning white, remove any white pixels if (subColor != System.Drawing.Color.White) { // Remove any white pixels for (int x = 0; x < whitedOut.Width; x++) { for (int y = 0; y < whitedOut.Height; y++) { if (y >= innerBottomBorder) { int whiteThreshold = 150; Color oldPixel = whitedOut.GetPixel(x, y); if ((oldPixel.R > whiteThreshold) && (oldPixel.G > whiteThreshold) && (oldPixel.B > whiteThreshold)) { whitedOut.SetPixel(x, y, drawingColor); } } } } } /* * // Draw a slight black border around the whole image for cutting purposes * for (int x = 0; x < whitedOut.Width; x++) * { * for (int y = 0; y < whitedOut.Height; y++) * { * if ((y == whitedOut.Height - 1) || (x == whitedOut.Width - 1) || * (y == 0) || (x == 0)) * { * whitedOut.SetPixel(x, y, Color.FromArgb(255, 200, 200, 200)); * } * } * } */ return(whitedOut); }
/// <summary> /// Gets the image for the page /// </summary> /// <returns></returns> public unsafe System.Drawing.Bitmap BuildImage(int subsample = 1) { lock (_loadingLock) { DateTime start = DateTime.Now; System.Drawing.Bitmap background = GetBackgroundImage(subsample, false); Console.WriteLine("Background: " + DateTime.Now.Subtract(start).TotalMilliseconds); start = DateTime.Now; using (System.Drawing.Bitmap foreground = GetForegroundImage(subsample, false)) { Console.WriteLine("Foreground: " + DateTime.Now.Subtract(start).TotalMilliseconds); start = DateTime.Now; using (System.Drawing.Bitmap mask = GetTextImage(subsample, false)) { Console.WriteLine("Mask: " + DateTime.Now.Subtract(start).TotalMilliseconds); start = DateTime.Now; _hasLoaded = true; BitmapData backgroundData = background.LockBits(new System.Drawing.Rectangle(0, 0, background.Width, background.Height), ImageLockMode.ReadWrite, background.PixelFormat); int backgroundPixelSize = GetPixelSize(backgroundData); BitmapData foregroundData = foreground.LockBits(new System.Drawing.Rectangle(0, 0, foreground.Width, foreground.Height), ImageLockMode.ReadOnly, foreground.PixelFormat); int foregroundPixelSize = GetPixelSize(foregroundData); BitmapData maskData = mask.LockBits(new System.Drawing.Rectangle(0, 0, mask.Width, mask.Height), ImageLockMode.ReadOnly, mask.PixelFormat); //int maskPixelSize = GetPixelSize(maskData); int height = background.Height; int width = background.Width; Parallel.For( 0, height, y => { byte *maskRow = (byte *)maskData.Scan0 + (y * maskData.Stride); uint *backgroundRow = (uint *)(backgroundData.Scan0 + (y * backgroundData.Stride)); uint *foregroundRow = (uint *)(foregroundData.Scan0 + (y * foregroundData.Stride)); for (int x = 0; x < width; x++) { // Check if the mask byte is set if (maskRow[x] > 0) { backgroundRow[x] = _isInverted == true ? InvertColor(foregroundRow[x]) : foregroundRow[x]; } else if (_isInverted == true) { backgroundRow[x] = InvertColor(backgroundRow[x]); } } }); mask.UnlockBits(maskData); foreground.UnlockBits(foregroundData); background.UnlockBits(backgroundData); return(background); } } } }
private bool getThumbNail( string file, IntPtr pidl, IShellFolder item ) { IntPtr hBmp = IntPtr.Zero; IExtractImage extractImage = null; try { string pidlPath = PathFromPidl(pidl); if (Path.GetFileName(pidlPath).ToUpper().Equals(Path.GetFileName(file).ToUpper())) { // we have the item: IUnknown iunk = null; int prgf = 0; Guid iidExtractImage = new Guid("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1"); item.GetUIObjectOf( IntPtr.Zero, 1, ref pidl, ref iidExtractImage, out prgf, ref iunk); extractImage = (IExtractImage)iunk; if (extractImage != null) { Console.WriteLine("Got an IExtractImage object!"); SIZE sz = new SIZE(); sz.cx = desiredSize.Width; sz.cy = desiredSize.Height; StringBuilder location = new StringBuilder(260, 260); int priority = 0; int requestedColourDepth = 32; EIEIFLAG flags = EIEIFLAG.IEIFLAG_ASPECT | EIEIFLAG.IEIFLAG_SCREEN; int uFlags = (int)flags; extractImage.GetLocation( location, location.Capacity, ref priority, ref sz, requestedColourDepth, ref uFlags); extractImage.Extract(out hBmp); if (hBmp != IntPtr.Zero) { // create the image object: thumbNail = System.Drawing.Bitmap.FromHbitmap(hBmp); // is thumbNail owned by the Bitmap? } Marshal.ReleaseComObject(extractImage); extractImage = null; } return true; } else { return false; } } catch (Exception ex) { if (hBmp != IntPtr.Zero) { UnManagedMethods.DeleteObject(hBmp); } if (extractImage != null) { Marshal.ReleaseComObject(extractImage); } throw ex; } }
public System.Drawing.Bitmap GetThumbNail( string file ) { if ((!File.Exists(file)) && (!Directory.Exists(file))) { throw new FileNotFoundException( String.Format("The file '{0}' does not exist", file), file); } if (thumbNail != null) { thumbNail.Dispose(); thumbNail = null; } IShellFolder folder = null; try { folder = getDesktopFolder; } catch (Exception ex) { throw ex; } if (folder != null) { IntPtr pidlMain = IntPtr.Zero; try { int cParsed = 0; int pdwAttrib = 0; string filePath = Path.GetDirectoryName(file); pidlMain = IntPtr.Zero; folder.ParseDisplayName( IntPtr.Zero, IntPtr.Zero, filePath, out cParsed, out pidlMain, out pdwAttrib); } catch (Exception ex) { Marshal.ReleaseComObject(folder); throw ex; } if (pidlMain != IntPtr.Zero) { // IShellFolder: Guid iidShellFolder = new Guid("000214E6-0000-0000-C000-000000000046"); IShellFolder item = null; try { folder.BindToObject(pidlMain, IntPtr.Zero, ref iidShellFolder, ref item); } catch (Exception ex) { Marshal.ReleaseComObject(folder); Allocator.Free(pidlMain); throw ex; } if (item != null) { // IEnumIDList idEnum = null; try { item.EnumObjects( IntPtr.Zero, (ESHCONTF.SHCONTF_FOLDERS | ESHCONTF.SHCONTF_NONFOLDERS), ref idEnum); } catch (Exception ex) { Marshal.ReleaseComObject(folder); Allocator.Free(pidlMain); throw ex; } if (idEnum != null) { // start reading the enum: int hRes = 0; IntPtr pidl = IntPtr.Zero; int fetched = 0; bool complete = false; while (!complete) { hRes = idEnum.Next(1, ref pidl, out fetched); if (hRes != 0) { pidl = IntPtr.Zero; complete = true; } else { if (getThumbNail(file, pidl, item)) { complete = true; } } if (pidl != IntPtr.Zero) { Allocator.Free(pidl); } } Marshal.ReleaseComObject(idEnum); } Marshal.ReleaseComObject(item); } Allocator.Free(pidlMain); } Marshal.ReleaseComObject(folder); } return thumbNail; }
/// <summary> /// Clears the stored image from memory /// </summary> public void ClearImage() { IsPageImageCached = false; if (_image != null) { _image.Dispose(); _image = null; } }
/// <summary> /// Gets the image for the page /// </summary> /// <returns></returns> public System.Drawing.Bitmap BuildImage(int subsample = 1) { lock (_loadingLock) { DateTime start = DateTime.Now; System.Drawing.Bitmap background = GetBackgroundImage(subsample, false); Console.WriteLine("Background: " + DateTime.Now.Subtract(start).TotalMilliseconds); start = DateTime.Now; using (System.Drawing.Bitmap _foreground = GetForegroundImage(subsample, false)) { Console.WriteLine("Foreground: " + DateTime.Now.Subtract(start).TotalMilliseconds); start = DateTime.Now; using (System.Drawing.Bitmap mask = GetTextImage(subsample, false)) { Console.WriteLine("Mask: " + DateTime.Now.Subtract(start).TotalMilliseconds); start = DateTime.Now; _hasLoaded = true; BitmapData backgroundData = background.LockBits(new System.Drawing.Rectangle(0, 0, background.Width, background.Height), ImageLockMode.ReadWrite, background.PixelFormat); int backgroundPixelSize = GetPixelSize(backgroundData); Bitmap foreground = null; if (_foreground.Height != background.Height || _foreground.Width != background.Width) { foreground = new Bitmap(background.Width, background.Height); System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(foreground); gr.DrawImage(_foreground, new Rectangle(0, 0, background.Width, background.Height), new Rectangle(0, 0, _foreground.Width, _foreground.Height), GraphicsUnit.Pixel); } else { foreground = _foreground; } BitmapData foregroundData = foreground.LockBits(new System.Drawing.Rectangle(0, 0, foreground.Width, foreground.Height), ImageLockMode.ReadOnly, foreground.PixelFormat); int foregroundPixelSize = GetPixelSize(foregroundData); BitmapData maskData = mask.LockBits(new System.Drawing.Rectangle(0, 0, mask.Width, mask.Height), ImageLockMode.ReadOnly, mask.PixelFormat); if (backgroundData.Height != foregroundData.Height) { throw new ArgumentException("foreground height!=background height"); } int size = backgroundData.Stride * backgroundData.Height; byte[] data = new byte[size]; int fsize = foregroundData.Stride * foregroundData.Height; byte[] fdata = new byte[fsize]; System.Runtime.InteropServices.Marshal.Copy(foregroundData.Scan0, fdata, 0, fsize); int msize = maskData.Stride * maskData.Height; byte[] mdata = new byte[msize]; System.Runtime.InteropServices.Marshal.Copy(maskData.Scan0, mdata, 0, msize); //int maskPixelSize = GetPixelSize(maskData); int height = background.Height; int width = background.Width; var bpxsz = Bitmap.GetPixelFormatSize(background.PixelFormat) / 8; var frsz = Bitmap.GetPixelFormatSize(foreground.PixelFormat) / 8; var msksz = Bitmap.GetPixelFormatSize(mask.PixelFormat) / 8; for (int y = 0; y < height; y++) { byte maskRow = mdata[y * maskData.Stride]; int mult = y * backgroundData.Stride; int fmult = y * foregroundData.Stride; for (int x = 0; x < width; x++) { // Check if the mask byte is set maskRow = mdata[y * maskData.Stride + x * msksz]; if (maskRow > 0) { var flag = _isInverted == true; var b1 = BitConverter.ToUInt32(fdata, fmult + x * frsz); var b2 = InvertColor(b1); var b3 = flag ? b2 : b1; for (int i = 0; i < frsz; i++) { data[mult + x * bpxsz + i] = (byte)((b3 & (0xff << (i * 8))) >> (i * 8)); } var res = BitConverter.ToUInt32(data, mult + x * bpxsz); } else if (_isInverted == true) { var b2 = InvertColor(BitConverter.ToInt32(data, mult + x * bpxsz)); for (int i = 0; i < frsz; i++) { data[mult + x * bpxsz + i] = (byte)((b2 & (0xff << (i * 8))) >> (i * 8)); } } } } System.Runtime.InteropServices.Marshal.Copy(data, 0, backgroundData.Scan0, data.Length); mask.UnlockBits(maskData); foreground.UnlockBits(foregroundData); background.UnlockBits(backgroundData); return(background); } } } }
/// <summary> /// Creates a blank image with the given color /// </summary> /// <param name="imageColor"></param> /// <returns></returns> private System.Drawing.Bitmap CreateBlankImage(Brush imageColor, int width, int height) { System.Drawing.Bitmap newBackground = new System.Drawing.Bitmap(Info.Width, Info.Height); // Fill the whole image with white using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newBackground)) { g.FillRegion(imageColor, new Region(new System.Drawing.Rectangle(0, 0, width, height))); } return newBackground; }
/// <summary> /// Converts the pixel data to a bitmap image /// </summary> /// <param name="pixels"></param> /// <returns></returns> private unsafe System.Drawing.Bitmap ConvertDataToImage(int[] pixels) { // create a bitmap and manipulate it System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Info.Width, Info.Height, PixelFormat.Format32bppArgb); BitmapData bits = bmp.LockBits(new System.Drawing.Rectangle(0, 0, Info.Width, Info.Height), ImageLockMode.ReadWrite, bmp.PixelFormat); for (int y = 0; y < Info.Height; y++) { var row = (int*)((byte*)bits.Scan0 + (y * bits.Stride)); for (int x = 0; x < Info.Width; x++) { row[x] = pixels[y * Info.Width + x]; } } bmp.UnlockBits(bits); return bmp; }
/// <summary> /// Resizes the image to the new dimensions /// </summary> /// <param name="srcImage"></param> /// <param name="newWidth"></param> /// <param name="newHeight"></param> /// <returns></returns> public System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap srcImage, int newWidth, int newHeight) { // Check if the image needs resizing if (srcImage.Width == newWidth && srcImage.Height == newHeight) { return srcImage; } // Resize the image System.Drawing.Bitmap newImage = new System.Drawing.Bitmap(newWidth, newHeight); using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(newImage)) { gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.DrawImage(srcImage, new System.Drawing.Rectangle(0, 0, newWidth, newHeight)); } srcImage.Dispose(); return newImage; }
public SC_SharpDX_ScreenCapture(int adapter, int numOutput, SharpDX.Direct3D11.Device device_) { //_textureByteArray[0] = 0; imageptrList = new IntPtr[num_cols * num_rows]; _frameCaptureData = new SC_SharpDX_ScreenFrame(); arrayOfTexture2DFrac = new Texture2D[num_cols * num_rows]; pastearray = new int[num_cols * num_rows]; pastearrayTwo = new int[num_cols * num_rows]; arrayOfBytesTwo = new byte[_textureDescriptionFinal.Width * _textureDescriptionFinal.Height]; _lastShaderResourceViewArray = new ShaderResourceView[num_cols * num_rows]; _ShaderResourceViewArray = new ShaderResourceView[num_cols * num_rows]; _numAdapter = adapter; _numOutput = numOutput; try { using (var _factory = new SharpDX.DXGI.Factory1()) { this._adapter = _factory.GetAdapter1(_numAdapter); } } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } try { //this._device = new Device(_adapter); //this._device = sccsVD4VE_LightNWithoutVr.SC_Console_DIRECTX._dxDevice.Device; this._device = device_; } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } try { //initializeOutput(); using (var _output = _adapter.GetOutput(_numOutput)) { // Width/Height of desktop to capture //getDesktopBoundaries(); _width = ((SharpDX.Rectangle)_output.Description.DesktopBounds).Width; _height = ((SharpDX.Rectangle)_output.Description.DesktopBounds).Height; _frameCaptureData.width = _width; _frameCaptureData.height = _height; this._output1 = _output.QueryInterface <Output1>(); } } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } try { //duplicateOutput(); this._outputDuplication = _output1.DuplicateOutput(_device); } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } try { //getTextureDescription(); this._textureDescription = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None,//BindFlags.None, //| BindFlags.RenderTarget Format = Format.B8G8R8A8_UNorm, Width = _width, Height = _height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; this._textureDescriptionFinal = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.None, BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, Format = Format.B8G8R8A8_UNorm, Width = _width, Height = _height, OptionFlags = ResourceOptionFlags.GenerateMipMaps, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Default }; wid = _textureDescriptionFinal.Width / num_cols; hgt = _textureDescriptionFinal.Height / num_rows; /*this._textureDescriptionFinalFrac = new Texture2DDescription * { * CpuAccessFlags = CpuAccessFlags.None, * BindFlags = BindFlags.ShaderResource | BindFlags.RenderTarget, * Format = Format.B8G8R8A8_UNorm, * Width = wid, * Height = hgt, * OptionFlags = ResourceOptionFlags.GenerateMipMaps, * MipLevels = 1, * ArraySize = 1, * SampleDescription = { Count = 1, Quality = 0 }, * Usage = ResourceUsage.Default * };*/ this._textureDescriptionFinalFrac = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None,//BindFlags.None, //| BindFlags.RenderTarget Format = Format.B8G8R8A8_UNorm, Width = wid, Height = hgt, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; piece = new Bitmap(wid, hgt); gr = Graphics.FromImage(piece); dest_rect = new System.Drawing.Rectangle(0, 0, wid, hgt); strider = wid * 4; for (int i = 0; i < arrayOfImage.Length; i++) { arrayOfImage[i] = new int[wid * hgt * 4]; } for (int i = 0; i < arrayOfBytes.Length; i++) { arrayOfBytes[i] = new byte[wid * hgt * 4]; } piece = new System.Drawing.Bitmap(wid, hgt); dest_rect = new System.Drawing.Rectangle(0, 0, wid, hgt); //int num_rows = _textureDescriptionFinal.Height / hgt; //int num_cols = _textureDescriptionFinal.Width / wid; source_rect = new System.Drawing.Rectangle(0, 0, wid, hgt); for (int tex2D = 0; tex2D < 10 * 10; tex2D++) { arrayOfTexture2DFrac[tex2D] = new Texture2D(_device, _textureDescriptionFinalFrac); } } catch (SharpDXException ex) { Console.WriteLine(ex.ToString()); return; } _texture2D = new Texture2D(_device, _textureDescription); _texture2DFinal = new Texture2D(_device, _textureDescriptionFinal); resourceViewDescription = new ShaderResourceViewDescription { Format = _texture2DFinal.Description.Format, Dimension = SharpDX.Direct3D.ShaderResourceViewDimension.Texture2D, Texture2D = new ShaderResourceViewDescription.Texture2DResource { MipLevels = -1, MostDetailedMip = 0 } }; _bitmap = new System.Drawing.Bitmap(_width, _height, PixelFormat.Format32bppArgb); var boundsRect = new System.Drawing.Rectangle(0, 0, _width, _height); var bmpData = _bitmap.LockBits(boundsRect, ImageLockMode.ReadOnly, _bitmap.PixelFormat); _bytesTotal = Math.Abs(bmpData.Stride) * _bitmap.Height; _bitmap.UnlockBits(bmpData); _textureByteArray = new byte[_bytesTotal]; /*try * { * * } * catch (SharpDXException ex) * { * Console.WriteLine(ex.ToString()); * return; * }*/ }
public unsafe System.Drawing.Bitmap BuildImage(int subsample = 1) { Verify.SubsampleRange(subsample); lock (LoadingLock) { System.Drawing.Bitmap background = GetBackgroundImage(subsample, true); // TODO ETW logging goes here using (System.Drawing.Bitmap foreground = GetForegroundImage(subsample, true)) { using (System.Drawing.Bitmap mask = GetMaskImage(subsample, true)) { HasLoaded = true; BitmapData backgroundData = background.LockBits(new System.Drawing.Rectangle(0, 0, background.Width, background.Height), ImageLockMode.ReadWrite, background.PixelFormat); int backgroundPixelSize = DjvuImage.GetPixelSize(backgroundData.PixelFormat); BitmapData foregroundData = foreground.LockBits(new System.Drawing.Rectangle(0, 0, foreground.Width, foreground.Height), ImageLockMode.ReadOnly, foreground.PixelFormat); int foregroundPixelSize = DjvuImage.GetPixelSize(foregroundData.PixelFormat); BitmapData maskData = mask.LockBits(new System.Drawing.Rectangle(0, 0, mask.Width, mask.Height), ImageLockMode.ReadOnly, mask.PixelFormat); //int maskPixelSize = GetPixelSize(maskData); int bgndHeight = background.Height; int bgndWidth = background.Width; int fgndHeight = foreground.Height; int fgndWidth = foreground.Width; int maskHeight = mask.Height; int maskWidth = mask.Width; int maskbgnH = maskHeight / bgndHeight; int maskfgnH = maskHeight / fgndHeight; int maskbgnW = maskWidth / bgndWidth; int maskfgnW = maskWidth / fgndWidth; //Parallel.For( // 0, // height, // y => // { for (int y = 0, yf = 0, yb = 0; y < maskHeight && yb < bgndHeight && yf < fgndHeight; ++y, yf = yb = y) { byte *maskRow = (byte *)maskData.Scan0 + (y * maskData.Stride); DjvuNet.Graphics.Pixel *backgroundRow = (DjvuNet.Graphics.Pixel *)(backgroundData.Scan0 + (yb * backgroundData.Stride)); DjvuNet.Graphics.Pixel *foregroundRow = (DjvuNet.Graphics.Pixel *)(foregroundData.Scan0 + (yf * foregroundData.Stride)); for (int x = 0, xf = 0, xb = 0; x < bgndWidth && xb < maskWidth && xf < fgndWidth; x++) { // Check if the mask byte is set if (maskRow[x] > 0) { DjvuNet.Graphics.Pixel xF = foregroundRow[xf]; if (_IsInverted) { backgroundRow[xb] = InvertColor(xF); } else { backgroundRow[xb] = xF; } } else if (_IsInverted) { backgroundRow[xb] = InvertColor(backgroundRow[xb]); } if (x >= 0) { if (x % maskbgnW == 0) { xb++; } if (x % maskfgnW == 0) { xf++; } } } if (y >= 0) { if (y % maskbgnH == 0) { yb++; } if (y % maskfgnH == 0) { yf++; } } } //}); mask.UnlockBits(maskData); foreground.UnlockBits(foregroundData); background.UnlockBits(backgroundData); return(background); } } } }