public FormDisplay(Root root) { Root = root; InitializeComponent(); this.Left = SystemInformation.VirtualScreen.Left; this.Top = SystemInformation.VirtualScreen.Top; int targetbottom = 0; foreach (Screen screen in Screen.AllScreens) { if (screen.WorkingArea.Bottom > targetbottom) targetbottom = screen.WorkingArea.Bottom; } int virwidth = SystemInformation.VirtualScreen.Width; this.Width = virwidth; this.Height = targetbottom - this.Top; Bitmap InitCanvus = new Bitmap(this.Width, this.Height); Canvus = InitCanvus.GetHbitmap(Color.FromArgb(0)); OneStrokeCanvus = InitCanvus.GetHbitmap(Color.FromArgb(0)); //BlankCanvus = InitCanvus.GetHbitmap(Color.FromArgb(0)); IntPtr screenDc = GetDC(IntPtr.Zero); canvusDc = CreateCompatibleDC(screenDc); SelectObject(canvusDc, Canvus); onestrokeDc = CreateCompatibleDC(screenDc); SelectObject(onestrokeDc, OneStrokeCanvus); //blankcanvusDc = CreateCompatibleDC(screenDc); //SelectObject(blankcanvusDc, BlankCanvus); gCanvus = Graphics.FromHdc(canvusDc); gCanvus.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; gOneStrokeCanvus = Graphics.FromHdc(onestrokeDc); gOneStrokeCanvus.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; if (Root.AutoScroll) { hScreenBitmap = InitCanvus.GetHbitmap(Color.FromArgb(0)); memscreenDc = CreateCompatibleDC(screenDc); SelectObject(memscreenDc, hScreenBitmap); screenbits = new byte[50000000]; lastscreenbits = new byte[50000000]; } ReleaseDC(IntPtr.Zero, screenDc); InitCanvus.Dispose(); //this.DoubleBuffered = true; gpButtonsImage = new Bitmap(2400, 100); TransparentBrush = new SolidBrush(Color.Transparent); SemiTransparentBrush = new SolidBrush(Color.FromArgb(120, 255, 255, 255)); ToTopMostThrough(); }
public BorderPaint(Bitmap image, bool imageIsOwned, BorderPaintMode flags, params Rectangle[] slices) { _flags = flags; _slices = slices; _bitmap = image; _imageIsOwned = imageIsOwned; if (IsFlagSet(flags, BorderPaintMode.GDI)) { _hBitmap = image.GetHbitmap(); } else if (IsFlagSet(flags, BorderPaintMode.Cached)) { _sliceCache = new Bitmap[SLICECOUNT]; for (int i = 0; i < SLICECOUNT; i++) { if (slices[i].Width > 0 && slices[i].Height > 0) { Bitmap cachedSlice = new Bitmap(slices[i].Width, slices[i].Height, image.PixelFormat); using (Graphics g = Graphics.FromImage(cachedSlice)) g.DrawImage(image, new Rectangle(0, 0, slices[i].Width, slices[i].Height), slices[i], GraphicsUnit.Pixel); _sliceCache[i] = cachedSlice; } } } }
private void UpdateLayeredWindow() { Bitmap bitmap1 = new Bitmap(this.Size.Width, this.Size.Height, PixelFormat.Format32bppArgb); using (Graphics graphics1 = Graphics.FromImage(bitmap1)) { Rectangle rectangle1; SIZE size1; POINT point1; POINT point2; BLENDFUNCTION blendfunction1; rectangle1 = new Rectangle(0, 0, this.Size.Width, this.Size.Height); this.PerformPaint(new PaintEventArgs(graphics1, rectangle1)); IntPtr ptr1 = User32.GetDC(IntPtr.Zero); IntPtr ptr2 = Gdi32.CreateCompatibleDC(ptr1); IntPtr ptr3 = bitmap1.GetHbitmap(Color.FromArgb(0)); IntPtr ptr4 = Gdi32.SelectObject(ptr2, ptr3); size1.cx = this.Size.Width; size1.cy = this.Size.Height; point1.x = this.Location.X; point1.y = this.Location.Y; point2.x = 0; point2.y = 0; blendfunction1 = new BLENDFUNCTION(); blendfunction1.BlendOp = 0; blendfunction1.BlendFlags = 0; blendfunction1.SourceConstantAlpha = this._alpha; blendfunction1.AlphaFormat = 1; User32.UpdateLayeredWindow(base.Handle, ptr1, ref point1, ref size1, ptr2, ref point2, 0, ref blendfunction1, 2); //2=ULW_ALPHA Gdi32.SelectObject(ptr2, ptr4); User32.ReleaseDC(IntPtr.Zero, ptr1); Gdi32.DeleteObject(ptr3); Gdi32.DeleteDC(ptr2); } }
//打开图片 private void OpenButton_OnClick(object sender, RoutedEventArgs e) { var openFile = new OpenFileDialog { InitialDirectory = Environment.CurrentDirectory, Filter = "JPEG图片|*.jpg|PNG图片|*.png", RestoreDirectory = false, FilterIndex = 1 }; if (openFile.ShowDialog() != true) return; _srcImage?.Dispose(); _dstImage?.Dispose(); _dstImage = null; GC.Collect(); //强行回收内存 _srcImage = new Bitmap(openFile.FileName, false); //将源图像转化为BitmapSource,并用Image控件显示 var ip = _srcImage.GetHbitmap(); var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); Rescale.CenterX = 0; Rescale.CenterY = 0; Rescale.ScaleX = Rescale.ScaleY = 1; CurrentImage.Source = bitmapSource; }
/// <summary> /// The display and show icon. /// </summary> /// <param name="message"> /// The message. /// </param> public void DisplayAndShowIcon(string message) { var b = new Bitmap( @"E:\Development\SonarQube\VssonarExtension\VSSonarQubeExtension\VSSonarExtension\PackageImplementation\Resources\sonariconsource.bmp"); IntPtr hdc = IntPtr.Zero; hdc = b.GetHbitmap(); object hdcObject = hdc; vssStatusBar.Bar.Animation(1, ref hdcObject); Thread.Sleep(10000); vssStatusBar.Bar.Animation(0, ref hdcObject); DeleteObject(hdc); return; object icon = Constants.SBAI_Build; vssStatusBar.dte.StatusBar.Animate(true, icon); // this.Bar.Animation(1, ref icon); vssStatusBar.dte.StatusBar.Text = message; // this.Bar.SetText(message); vssStatusBar.dte.StatusBar.Animate(false, icon); // this.Bar.Animation(0, ref icon); vssStatusBar.dte.StatusBar.Text = "Build Succeeded"; }
/// <summary> /// Set overlay bitmap with a custom opacity level. /// </summary> public void SetBitmap(Bitmap bitmap, byte opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) throw new ApplicationException("The bitmap must be 32ppp with alpha-channel."); var screenDc = Win32.GetDC(IntPtr.Zero); var memDc = Win32.CreateCompatibleDC(screenDc); var hBitmap = IntPtr.Zero; var oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); // grab a GDI handle from this GDI+ bitmap oldBitmap = Win32.SelectObject(memDc, hBitmap); var size = new Win32.Size(bitmap.Width, bitmap.Height); var pointSource = new Win32.Point(0, 0); var topPos = new Win32.Point(Left, Top); var blend = new Win32.BLENDFUNCTION{ BlendOp = Win32.AC_SRC_OVER, BlendFlags = 0, SourceConstantAlpha = opacity, AlphaFormat = Win32.AC_SRC_ALPHA }; Win32.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, Win32.ULW_ALPHA); } finally { Win32.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { Win32.SelectObject(memDc, oldBitmap); Win32.DeleteObject(hBitmap); } Win32.DeleteDC(memDc); } }
//Code within this region is credited to user "Alastair Pitts" in the thread http://stackoverflow.com/questions/94456/load-a-wpf-bitmapimage-from-a-system-drawing-bitmap /// <summary> /// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>. /// </summary> /// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject. /// </remarks> /// <param name="source">The source bitmap.</param> /// <returns>A BitmapSource</returns> public static BitmapSource ToBitmapSource(Bitmap source) { BitmapSource bitSrc = null; var hBitmap = source.GetHbitmap(); try { bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } catch (Win32Exception) { bitSrc = null; } finally { NativeMethods.DeleteObject(hBitmap); } return bitSrc; }
public Bitmap SnapshotWindow() { Bitmap bm = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); #if false IntPtr screenDc = Win32.GetDC(IntPtr.Zero); IntPtr memDc = Win32.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; hBitmap = bm.GetHbitmap(); // grab a GDI handle from this GDI+ bitmap oldBitmap = Win32.SelectObject(memDc, hBitmap); Win32.PrintWindow(Handle, memDc, 0); Win32.ReleaseDC(IntPtr.Zero, screenDc); Win32.SelectObject(memDc, oldBitmap); // Win32.DeleteObject(hBitmap); Win32.DeleteDC(memDc); bm = Bitmap.FromHbitmap(hBitmap); #else Graphics g = Graphics.FromImage(bm); IntPtr hdcMem = g.GetHdc(); Win32.PrintWindow(Handle, hdcMem, 0); g.ReleaseHdc(hdcMem); g.Dispose(); #endif return bm; }
public Tile(Image image, TileCoordinate tile, RenderMode mode) { this.tile = tile; if(image != null) { this.mode = mode; switch(mode) { case RenderMode.GDI: { using(Bitmap bitmap = new Bitmap(image)) { this.ptrHbitmap = bitmap.GetHbitmap(); } } break; case RenderMode.GDI_PLUS: { this.image = image; } break; } } }
/// <summary> /// カーソルを作成する /// </summary> /// <param name="bitmap">カーソル画像</param> /// <param name="xHotSpot">ホットスポットのX座標</param> /// <param name="yHotSpot">ホットスポットのY座標</param> /// <returns>作成したカーソル</returns> public static Cursor CreateCursor(Bitmap bitmap, int xHotSpot, int yHotSpot) { Bitmap andMask = new Bitmap(bitmap.Width, bitmap.Height); Bitmap xorMask = new Bitmap(bitmap.Width, bitmap.Height); Color transparent = bitmap.GetPixel(bitmap.Width - 1, bitmap.Height - 1); for (int x = 0; x < bitmap.Width; x++) { for (int y = 0; y < bitmap.Height; y++) { Color pixel = bitmap.GetPixel(x, y); if (pixel == transparent) { andMask.SetPixel(x, y, Color.White); xorMask.SetPixel(x, y, Color.Transparent); } else { andMask.SetPixel(x, y, Color.Black); xorMask.SetPixel(x, y, pixel); } } } IntPtr hIcon = bitmap.GetHicon(); IconInfo info = new IconInfo(); NativeMethods.GetIconInfo(hIcon, ref info); info.xHotspot = xHotSpot; info.yHotspot = yHotSpot; info.hbmMask = andMask.GetHbitmap(); info.hbmColor = xorMask.GetHbitmap(); info.fIcon = false; hIcon = NativeMethods.CreateIconIndirect(ref info); return new Cursor(hIcon); }
// freeze the form public void Freeze() { // Remember we have frozen the form once more // Do nothing if it was already frozen if (++FreezeCount > 1) return; Rectangle rect = form.ClientRectangle; if (rect.IsEmpty || form.WindowState == FormWindowState.Minimized) return; Point topLeft = form.PointToScreen(new Point(rect.Left, rect.Top)); // Create a PictureBox that resizes with its contents pictureBox = new PictureBox(); pictureBox.SizeMode = PictureBoxSizeMode.AutoSize; // create a bitmap as large as the form's client area and with same color depth using (Graphics frmGraphics = form.CreateGraphics()) { Bitmap bitmap = new Bitmap(rect.Width, rect.Height, frmGraphics); hBitmap = bitmap.GetHbitmap(); pictureBox.Image = Image.FromHbitmap(hBitmap); } // copy the screen contents, from the form's client area to the hidden bitmap using (Graphics picGraphics = Graphics.FromImage(pictureBox.Image)) { picGraphics.CopyFromScreen(topLeft, Point.Empty, rect.Size, CopyPixelOperation.SourceCopy); } // Display the bitmap in the picture box, and show the picture box in front of all other controls form.Controls.Add(pictureBox); pictureBox.BringToFront(); }
public static BitmapSource BitmapSourceFromBitmap(Bitmap bitmap) { BitmapSource bitSrc = null; var hBitmap = bitmap.GetHbitmap(); bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); return bitSrc; }
private void btnProcess_Click(object sender, RoutedEventArgs e) { double[,] matrix = new double[3, 3]; matrix[0, 0] = double.Parse(txt00.Text, CultureInfo.InvariantCulture); matrix[0, 1] = double.Parse(txt01.Text, CultureInfo.InvariantCulture); matrix[0, 2] = double.Parse(txt02.Text, CultureInfo.InvariantCulture); matrix[1, 0] = double.Parse(txt10.Text, CultureInfo.InvariantCulture); matrix[1, 1] = double.Parse(txt11.Text, CultureInfo.InvariantCulture); matrix[1, 2] = double.Parse(txt12.Text, CultureInfo.InvariantCulture); matrix[2, 0] = double.Parse(txt20.Text, CultureInfo.InvariantCulture); matrix[2, 1] = double.Parse(txt21.Text, CultureInfo.InvariantCulture); matrix[2, 2] = double.Parse(txt22.Text, CultureInfo.InvariantCulture); GenericFilter sharpen = new GenericFilter(); sharpen.FilterName = "Sharpen"; sharpen.FilterMatrix = matrix; //sharpen.FilterMatrix = new double[,] {{ 0.0, 0.2, 0.0 }, // { 0.2, 0.2, 0.2 }, // { 0.0, 0.2, 0.2 }}; resultImage = previewImage.ConvolutionFilter(sharpen); image.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(resultImage.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); previewImage = resultImage; }
public MultivariateRendPropPageCS() { //'MsgBox("New (color prop page)") m_Page = new PropPageForm(); m_Priority = 550; // 5th category is for multiple attribute renderers string[] res = typeof(MultivariateRendPropPageCS).Assembly.GetManifestResourceNames(); if (res.GetLength(0) > 0) { try { string bitmapResourceName = GetType().Name + ".bmp"; //creating a new bitmap m_bitmap = new Bitmap(GetType(), bitmapResourceName); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } if (m_bitmap != null) { m_bitmap.MakeTransparent(m_bitmap.GetPixel(1, 1)); m_hBitmap = m_bitmap.GetHbitmap(); } } }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //convert GDI+ bitmap to image source Bitmap bmp = value as Bitmap; if (bmp != null) { BitmapSource bitmapsource = null; try { bitmapsource = Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions ()); } catch (Exception exp) { Bitmap tempbmp = new Bitmap(32, 32); Graphics g = Graphics.FromImage(tempbmp); g.Clear(Color.Magenta); bitmapsource = Imaging.CreateBitmapSourceFromHBitmap(tempbmp.GetHbitmap(Color.Magenta), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } return bitmapsource; } return null; }
public ItemImagesContainer() { // // Required for Windows Form Designer support // InitializeComponent(); imageListBox.Size = new Size (this.Size.Width-2,this.Size.Height-2); this.TopLevel = false; // We create an empty bitmap, corresponding to the item none. ie when the item doesn't have any image to be displayed with it. int dimension=16; Bitmap emptyBMP = new Bitmap(dimension,dimension); Graphics graphics = Graphics.FromImage((Image)emptyBMP); graphics.SmoothingMode = SmoothingMode.AntiAlias; Rectangle imgRect = new Rectangle(0,0,emptyBMP.Width-1,emptyBMP.Height-1); graphics.DrawRectangle (new Pen (new SolidBrush (Color.Black)),imgRect); graphics.FillRectangle(new SolidBrush (Color.White),imgRect); noneIcon = Image.FromHbitmap(emptyBMP.GetHbitmap()); graphics.Dispose(); emptyBMP.Dispose(); this.imageListBox .DrawMode = DrawMode.OwnerDrawFixed; this.imageListBox.ItemHeight = 25; // // TODO: Add any constructor code after InitializeComponent call // }
public static byte[,,] Fill_Image_Buffer(Bitmap bmp, IProgress progress, ICurrentOperation operation) { if (operation != null) operation.SetOperation(CurrentOperation.FillImageBuffer); Point originalSize = GetActualDimension(new Point(bmp.Width, bmp.Height)); byte[,,] Bitmap_Buffer = new byte[originalSize.X,originalSize.Y, 3]; IntPtr hbmScreen = IntPtr.Zero; IntPtr hBmpInput = bmp.GetHbitmap(); InteropGDI.BITMAP bmpInput = new InteropGDI.BITMAP(); InteropGDI.GetObject(hBmpInput, 24, ref bmpInput); InteropGDI.BITMAPINFOHEADER bi; bi.biSize = 40; bi.biWidth = bmpInput.bmWidth; bi.biHeight = -bmpInput.bmHeight; // Negative to reverse the scan order. bi.biPlanes = 1; bi.biBitCount = 32; bi.biCompression = (uint)InteropGDI.BMP_Compression_Modes.BI_RGB; bi.biSizeImage = 0; bi.biXPelsPerMeter = 0; bi.biYPelsPerMeter = 0; bi.biClrUsed = 0; bi.biClrImportant = 0; ulong bitmapLengthBytes = (ulong)(((bmpInput.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmpInput.bmHeight); byte[] bitmap_array = new byte[bitmapLengthBytes]; IntPtr hdcWindow = InteropGDI.CreateCompatibleDC(IntPtr.Zero); InteropGDI.GetDIBits(hdcWindow, hBmpInput, (uint)0, (uint)bmpInput.bmHeight, bitmap_array, ref bi, (uint)InteropGDI.DIB_COLORS.DIB_RGB_COLORS); int k = 0, wd = bmpInput.bmWidth, ht = bmpInput.bmHeight; for (int j = 0; j < ht; j++) { if (progress != null) progress.SetProgress((int)bitmapLengthBytes, k); for (int i = 0; i < wd; i++) { Bitmap_Buffer[i, j, 2] = bitmap_array[k++]; Bitmap_Buffer[i, j, 1] = bitmap_array[k++]; Bitmap_Buffer[i, j, 0] = bitmap_array[k++]; k++; } } InteropGDI.DeleteObject(hdcWindow); InteropGDI.DeleteObject(hbmScreen); InteropGDI.DeleteObject(hBmpInput); return Bitmap_Buffer; }
public void LoadAssets() { if (null != this.assets) { return; } this.assets = new Assets(); this.assets.PlatformBottomSource = new BitmapImage(new Uri("Sprites\\Platform-Bottom.png", UriKind.Relative)); this.assets.PlatformTopSource = new BitmapImage(new Uri("Sprites\\Platform-Top.png", UriKind.Relative)); this.assets.PlatformInnerSource = new BitmapImage(new Uri("Sprites\\Platform-Inner.png", UriKind.Relative)); this.assets.CharacterSource = new BitmapSource[30]; int spriteWidth = 42; int spriteHeight = 51; System.Drawing.Rectangle croppedSource = new System.Drawing.Rectangle(0, 0, spriteWidth, spriteHeight); Bitmap source = System.Drawing.Image.FromFile("Sprites\\Character.png") as Bitmap; for (int row = 0; row < 5; row++) { for (int col = 0; col < 6; col++) { croppedSource.X = col * spriteWidth; croppedSource.Y = row * spriteHeight; Bitmap target = new System.Drawing.Bitmap((int)croppedSource.Width, (int)croppedSource.Height); Graphics.FromImage(target).DrawImage(source, new System.Drawing.Rectangle(0, 0, target.Width, target.Height), croppedSource, GraphicsUnit.Pixel); BitmapSource frame = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(target.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(target.Width, target.Height)); int index = row * 6 + col; this.assets.CharacterSource[index] = frame; } } }
public void UpdateWindow(Bitmap image, byte opacity, int width, int height, Point pos) { IntPtr hdcWindow = Win32.GetWindowDC(this.Handle); IntPtr hDC = Win32.CreateCompatibleDC(hdcWindow); IntPtr hBitmap = image.GetHbitmap(Color.FromArgb(0)); IntPtr hOld = Win32.SelectObject(hDC, hBitmap); Size size = new Size(0,0); Point zero = new Point(0, 0); if (width == -1 || height == -1) { //No width and height specified, use the size of the image size.Width = image.Width; size.Height = image.Height; } else { //Use whichever size is smallest, so that the image will //be clipped if necessary size.Width = Math.Min(image.Width, width); size.Height = Math.Min(image.Height, height); } m_rect.Size = size; m_rect.Location = pos; Win32.BLENDFUNCTION blend = new Win32.BLENDFUNCTION(); blend.BlendOp = (byte)Win32.BlendOps.AC_SRC_OVER; blend.SourceConstantAlpha = opacity; blend.AlphaFormat = (byte)Win32.BlendOps.AC_SRC_ALPHA; blend.BlendFlags = (byte)Win32.BlendFlags.None; Win32.UpdateLayeredWindow(this.Handle, hdcWindow, ref pos, ref size, hDC, ref zero, 0, ref blend, Win32.BlendFlags.ULW_ALPHA); Win32.SelectObject(hDC, hOld); Win32.DeleteObject(hBitmap); Win32.DeleteDC(hDC); Win32.ReleaseDC(this.Handle, hdcWindow); }
public void GetHbitmap () { Bitmap b = new Bitmap (10, 10); try { Assert.IsTrue (b.GetHbitmap () != IntPtr.Zero, "GetHbitmap"); } catch (NotImplementedException) { // not available on Mono } try { Assert.IsTrue (b.GetHbitmap (Color.Aqua) != IntPtr.Zero, "GetHbitmap(Color)"); } catch (NotImplementedException) { // not available on Mono } }
/// <summary> /// Converts an System.Drawing.Image to a BitmapSource. /// </summary> /// <param name="value">Image to convert.</param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns>Submitted value as a Bitmapsource.</returns> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Image myImage = value as Image; BitmapSource bitmapSource = null; if (myImage != null) { IntPtr bmpPt = IntPtr.Zero; try { var bitmap = new Bitmap(myImage); bmpPt = bitmap.GetHbitmap(); bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmpPt, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); bitmapSource.Freeze(); } finally { if (bmpPt != IntPtr.Zero) DeleteObject(bmpPt); } } return bitmapSource; }
public static BitmapImage Bitmap2BitmapImage(Bitmap bitmap) { IntPtr hBitmap = bitmap.GetHbitmap(); BitmapImage res =new BitmapImage(); try { BitmapSource retval = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); JpegBitmapEncoder encoder = new JpegBitmapEncoder(); MemoryStream memoryStream = new MemoryStream(); encoder.Frames.Add(BitmapFrame.Create(retval)); encoder.Save(memoryStream); res.BeginInit(); res.StreamSource = new MemoryStream(memoryStream.ToArray()); res.EndInit(); } finally { DeleteObject(hBitmap); } return res; }
public BitmapSource getIcon(int Index) { if (this.IconMap == null) throw new MWException("The icon map has not been initialized"); int x = Convert.ToInt32(this.IconMap.Width) / 30; int y = Convert.ToInt32(this.IconMap.Height) / 30; int iconCount = x * y; if (Index < 0 || Index >= iconCount) return null; int offsetX = (Index % x) * 30; int offsetY = (Index / x) * 30; Bitmap bitmap = new Bitmap(30, 30); Graphics.FromImage(bitmap).DrawImage(this.IconMap, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(offsetX, offsetY, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel); IntPtr hbitmap = bitmap.GetHbitmap(); BitmapSource bimage = Imaging.CreateBitmapSourceFromHBitmap( hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions() ); return (bimage); }
public static BitmapSource GetEmbeddedImageResource(string fileName) { var stream = GetDataStreamFromEmbeddResource(fileName); var bitmap = new Bitmap(stream); bitmap.MakeTransparent(); var bmSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); return bmSource; }
public static BitmapSource BitmapToBitmapSource(Bitmap source) { return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( source.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); }
private static BitmapSource BitmapToSource(Bitmap bitmap) { var hBitmap = bitmap.GetHbitmap(); var sizeOptions = BitmapSizeOptions.FromEmptyOptions(); var destination = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, sizeOptions); destination.Freeze(); return destination; }
public static BitmapSource BitmapToBitmapSource(Bitmap bitmap) { intPointer = bitmap.GetHbitmap(); bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(intPointer, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); DeleteObject(intPointer); return bitmapSource; }
private static BitmapSource CopyScreen() { using (var bmp = new Bitmap((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight, PixelFormat.Format32bppArgb)) { using (var graphics = Graphics.FromImage(bmp)) { graphics.CopyFromScreen(0, 0, 0, 0, bmp.Size); return Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } } }
/// <summary> /// Adds the layers to image. /// </summary> /// <param name="img">The img.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="imgPaths">The img paths.</param> /// <returns>The Layered Image</returns> public static Image AddLayersToImage(this Image img, float? width = null, float? height = null, params string[] imgPaths) { if (img != null) { using (var bitmap = new Bitmap((int?)width ?? img.Width, (int?)height ?? img.Height)) { using (var graphics = Graphics.FromImage(bitmap)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; graphics.DrawImage(img, new Rectangle(0, 0, bitmap.Width, bitmap.Height)); foreach (var imgPath in imgPaths) { try { var filepath = imgPath.MapPath(); if (File.Exists(filepath)) { using (var layer = Image.FromFile(filepath, true)) { if (layer.IsNotNull()) { graphics.DrawImage(layer, new Rectangle(0, 0, layer.Width, layer.Height)); } } } else { VLog.Logger.Error("AddLayersToImage: filepath is not found=> " + filepath); } } catch (OutOfMemoryException mex) { VLog.LogException(mex); } catch (FileNotFoundException fex) { VLog.LogException(fex); } catch (ArgumentException aex) { VLog.LogException(aex); } } return Image.FromHbitmap(bitmap.GetHbitmap()); } } } return null; }
public GxAddPostGisConnection() { m_bitmapLrg = new Bitmap(GetType().Assembly.GetManifestResourceStream("Pulp.ArcGis.ZigGis.images.pgsql_lrg.bmp")); m_bitmapLrg.MakeTransparent(m_bitmapLrg.GetPixel(1, 1)); m_hBitmapLrg = m_bitmapLrg.GetHbitmap(); m_bitmapSm = new Bitmap(GetType().Assembly.GetManifestResourceStream("Pulp.ArcGis.ZigGis.images.pgsql_sm.bmp")); m_bitmapSm.MakeTransparent(m_bitmapSm.GetPixel(1, 1)); m_hBitmapSm = m_bitmapSm.GetHbitmap(); }
public static BitmapSource ToBitmapSource(IImage image) { using (System.Drawing.Bitmap source = image.Bitmap) { IntPtr ptr = source.GetHbitmap(); BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( ptr, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); DeleteObject(ptr); return(bs); } }
private static BitmapSource GetBitmapSource(System.Drawing.Bitmap bmap, BitmapSource bimg) { IntPtr handle = IntPtr.Zero; try { handle = bmap.GetHbitmap(); bimg = Imaging.CreateBitmapSourceFromHBitmap( handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } finally { if (handle != IntPtr.Zero) { DeleteObject(handle); } } return(bimg); }
internal void GiveFrame(DepthImageFrame depthFrame, PointCluster floodFill) { short[] imagePixelData = new short[depthFrame.PixelDataLength]; depthFrame.CopyPixelDataTo(imagePixelData); float RenderWidth = 640.0f; float RenderHeight = 480.0f; Bitmap bmap = new System.Drawing.Bitmap(depthFrame.Width, depthFrame.Height, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); System.Drawing.Imaging.BitmapData bmapdata = bmap.LockBits(new System.Drawing.Rectangle(0, 0, depthFrame.Width , depthFrame.Height), ImageLockMode.WriteOnly, bmap.PixelFormat); IntPtr ptr = bmapdata.Scan0; System.Runtime.InteropServices.Marshal.Copy(imagePixelData, 0, ptr, depthFrame.Width * depthFrame.Height); bmap.UnlockBits(bmapdata); /*System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmap); * this.myImageBox.Source = * System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( * bmap.GetHbitmap(), * IntPtr.Zero, * System.Windows.Int32Rect.Empty, * BitmapSizeOptions.FromWidthAndHeight((int)this.myImageBox.Width, (int)this.myImageBox.Height));*/ using (DrawingContext lfdc = drawingGroup.Open())//this.liveFeedbackGroup.Open()) { lfdc.DrawImage(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmap.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight((int)RenderWidth, (int)RenderHeight)), //BitmapSizeOptions.FromWidthAndHeight((int)this.myImageBox.ActualWidth, (int)this.myImageBox.ActualHeight)), new Rect(0.0, 0.0, RenderWidth, RenderHeight)); foreach (DepthPoint point in floodFill.points) { lfdc.DrawRoundedRectangle(System.Windows.Media.Brushes.Red, null, new Rect(point.x, point.y, 3, 3), null, 1, null, 1, null); } } }
/// <summary> /// ドラッグで選択された範囲のスクリーンショットを撮ってウィンドウに表示 /// trimmedBitmapに保存用の画像を生成 /// </summary> private void beginTakeSnapshot() { var window = new CaptureDragWindow(); window.ReceiveDragAsync(resultRect => { if (resultRect.Width < 10 || resultRect.Height < 10) { return; } using (var screenBitmap = new System.Drawing.Bitmap((int)resultRect.Width, (int)resultRect.Height)) { // ドラッグされた範囲のスクリーンショットを撮影 using (var g = Graphics.FromImage(screenBitmap)) { g.CopyFromScreen((int)resultRect.Left, (int)resultRect.Top, 0, 0, screenBitmap.Size, System.Drawing.CopyPixelOperation.SourceCopy); } // 画像を表示 var hBitmap = screenBitmap.GetHbitmap(); image.Source = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); image.Width = screenBitmap.Width; image.Height = screenBitmap.Height; image.Visibility = Visibility.Visible; // トリミングされる範囲を表示 var trimRect = measureTrimmingRect(screenBitmap); trimRectangle.Margin = new Thickness(trimRect.Left - 1, trimRect.Top - 1, screenBitmap.Width - trimRect.Right, screenBitmap.Height - trimRect.Bottom); trimRectangle.Visibility = Visibility.Visible; // 保存用のトリミングされたBitmapを用意 if (trimmedBitmap != null) { trimmedBitmap.Dispose(); } trimmedBitmap = new System.Drawing.Bitmap(trimRect.Width, trimRect.Height, screenBitmap.PixelFormat); using (var g = Graphics.FromImage(trimmedBitmap)) { g.DrawImage(screenBitmap, 0, 0, trimRect, GraphicsUnit.Pixel); } } }); }
public BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap source) { BitmapSource bitSrc = null; var hBitmap = source.GetHbitmap(); try { bitSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } catch (Win32Exception) { bitSrc = null; } return(bitSrc); }
public static BitmapSource ToBitmapSource(SD.Bitmap source) { var hBitmap = source.GetHbitmap(); try { return(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); } catch (Win32Exception) { return(null); } finally { DeleteObject(hBitmap); } }
public void LoadBitmap(System.Drawing.Bitmap source) { IntPtr ip = source.GetHbitmap(); BitmapSource bs = null; try { bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } finally { DeleteObject(ip); } // Fix found here: // http://stackoverflow.com/questions/26361020/error-must-create-dependencysource-on-same-thread-as-the-dependencyobject-even bs.Freeze(); Dispatcher.CurrentDispatcher.Invoke(() => AlbumArt = bs); }
private BitmapSource BitmapToSource(System.Drawing.Bitmap bmp) { BitmapSource bmpSource; IntPtr ptr = IntPtr.Zero; try { ptr = bmp.GetHbitmap(); bmpSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } catch (Exception ex) { Console.WriteLine(ex); bmpSource = null; } finally { DeleteObject(ptr); } return(bmpSource); }
private PageContent generatePageContent(System.Drawing.Bitmap bmp, int top, int bottom, double pageWidth, double PageHeight, System.Printing.PrintCapabilities capabilities) { FixedPage printDocumentPage = new FixedPage(); printDocumentPage.Width = pageWidth; printDocumentPage.Height = PageHeight; int newImageHeight = bottom - top; System.Drawing.Bitmap bmpPage = bmp.Clone(new System.Drawing.Rectangle(0, top, bmp.Width, newImageHeight), System.Drawing.Imaging.PixelFormat.Format32bppArgb); // Create a new bitmap for the contents of this page Image pageImage = new Image(); BitmapSource bmpSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmpPage.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmp.Width, newImageHeight)); pageImage.Source = bmpSource; pageImage.VerticalAlignment = VerticalAlignment.Top; // Place the bitmap on the page printDocumentPage.Children.Add(pageImage); PageContent pageContent = new PageContent(); ((System.Windows.Markup.IAddChild)pageContent).AddChild(printDocumentPage); FixedPage.SetLeft(pageImage, capabilities.PageImageableArea.OriginWidth); FixedPage.SetTop(pageImage, capabilities.PageImageableArea.OriginHeight); pageImage.Width = capabilities.PageImageableArea.ExtentWidth; pageImage.Height = capabilities.PageImageableArea.ExtentHeight; return(pageContent); }
// } //L = new Line(); //L.X1 = PointsList[PointsList.Count-1][0] * BitmapSize; //L.Y1 = PointsList[PointsList.Count-1][1] * BitmapSize; //L.X2 = PointsList[0][0] * BitmapSize; //L.Y2 = PointsList[0][1] * BitmapSize; //CanvasLeft.Children.Add(L); //} private void CanvasLeft_OnMouseDown(object sender, MouseButtonEventArgs e) { System.Drawing.Bitmap Bitmap = ConvertCanvasToBitmap(true); System.Drawing.Bitmap Bitmap2 = ConvertCanvasToBitmap(false); //Bitmap.SetPixel((int)(BitmapSize * SideDeteriminantPoint[0]), (int)(BitmapSize * SideDeteriminantPoint[1]), System.Drawing.Color.FromArgb(0, 0, 0, 0)); floodFill(Bitmap, (int)(BitmapSize * SideDeteriminantPoint[0]), (int)(BitmapSize * SideDeteriminantPoint[1]), 0, 255); floodFill(Bitmap2, (int)(BitmapSize * SideDeteriminantPoint[0]), (int)(BitmapSize * SideDeteriminantPoint[1]), 0, 255); ImageBrush ib = new ImageBrush(); //var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(Bitmap.GetHbitmap(), // IntPtr.Zero, // Int32Rect.Empty, // BitmapSizeOptions.FromEmptyOptions() //); ib.ImageSource = Imaging.CreateBitmapSourceFromHBitmap(Bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); ImageBrush ib2 = new ImageBrush(); //var bitmapSource2 = Imaging.CreateBitmapSourceFromHBitmap(Bitmap2.GetHbitmap(), // IntPtr.Zero, // Int32Rect.Empty, // BitmapSizeOptions.FromEmptyOptions() //); ib2.ImageSource = Imaging.CreateBitmapSourceFromHBitmap(Bitmap2.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); CanvasLeft.Background = ib; //CanvasRight.Background = ib2; }
// Convert a Bitmap to a BitmapSource. public static BitmapSource ToBitmapSource(this System.Drawing.Bitmap src) { if (src == null) { return(null); } var ptr = src.GetHbitmap(); //obtain the Hbitmap try { var bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( ptr, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); return(bs); } finally { DeleteObject(ptr); //release the HBitmap } }
/// <summary> /// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source /// </summary> /// <param name="bitmap">The Source Bitmap</param> /// <returns>The equivalent BitmapSource</returns> public static BitmapSource ToBitmapSource(System.Drawing.Bitmap bitmap) { if (bitmap == null) { return(null); } using (System.Drawing.Bitmap source = (System.Drawing.Bitmap)bitmap.Clone()) { IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( ptr, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); NativeMethods.DeleteObject(ptr); //release the HBitmap bs.Freeze(); return(bs); } }
public static BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap bitmap) { if (bitmap == null) { throw new ArgumentNullException("bitmap"); } lock (bitmap) { IntPtr hBitmap = bitmap.GetHbitmap(); try { return(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); } finally { DeleteObject(hBitmap); } } }
private ImageSource GetIcon(Process p) { System.Drawing.Bitmap ico = null; try { ico = System.Drawing.Icon.ExtractAssociatedIcon(p.MainModule.FileName) .ToBitmap(); } catch (Exception ex) { } if (ico == null) { ico = (Bitmap)Properties.Resources.default_windows_app; } return(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( ico.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); }
public static ImageSource ToImageSource(this Icon icon) { int hashCode = icon.GetHashCode(); if (Cache.ContainsKey(hashCode)) { return(Cache[hashCode]); } Bitmap bitmap = icon.ToBitmap(); IntPtr hBitmap = bitmap.GetHbitmap(); var imageSource = CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); if (!DeleteObject(hBitmap)) { throw new Win32Exception(); } Cache.Add(hashCode, imageSource); return(imageSource); }
/// <summary> /// 轉成WPF圖片,並新增 /// </summary> /// <param name="bitmap"></param> private void fun_add(System.Drawing.Bitmap bitmap, List <data_apng> ar_apng, int int_延遲) { IntPtr ptr = bitmap.GetHbitmap(); BitmapSource result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( ptr, IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); //release resource DeleteObject(ptr); ar_apng.Add(new data_apng { int_延遲 = int_延遲, img = result }); bitmap.Dispose(); bitmap = null; //return result; }
public MainWindow() { InitializeComponent(); gameTimer.Interval = new TimeSpan(0, 0, 0, 0, 10); gameTimer.Tick += GameTimer_Tick; gameBallTop = Canvas.GetTop(gameBall); gameBallLeft = Canvas.GetLeft(gameBall); rectangleTop = Canvas.GetTop(gameRectangle); rectangleLeft = Canvas.GetLeft(gameRectangle); //never needs to be updated b/c never changes //The following code sets the canvas background as the Resource Image 'orangebackground' System.Drawing.Bitmap background = Properties.Resources.orangebackground; ImageBrush ib = new ImageBrush(); var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(background.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); this.highScore.Text = "HIGH SCORE: " + currentHighScore; background.Dispose(); ib.ImageSource = bitmapSource; myGameCanvas.Background = ib; }
/// <summary> /// Converts an instance of <see cref="Bitmap"/> to <see cref="BitmapSource"/>. /// Use this method to retrieve an image from a resx resource and display it in a WPF UI. /// </summary> /// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.</remarks> public static BitmapSource ToBitmapSource(this Bitmap source) { BitmapSource bitmapSource; var hBitmap = source.GetHbitmap(); try { bitmapSource = InteropImaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } catch (Win32Exception) { //This should not be needed. bitmapSource = null; } finally { //Since this method uses GDI to do the conversion, the DeleteObject function must be called. DeleteObject(hBitmap); } return(bitmapSource); }
public static Bitmap CreateBitmapSourceFromBitmap(System.Drawing.Bitmap bitmap) { if (bitmap == null) { throw new ArgumentNullException("bitmap"); } lock (bitmap) { IntPtr hBitmap = new IntPtr(); try { hBitmap = bitmap.GetHbitmap(); return(Image.FromHbitmap( hBitmap, IntPtr.Zero)); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { if (hBitmap != null) { DeleteObject(hBitmap); } GC.Collect(); } } return(null); }
public BitmapSource BitmapToBitmapSource(System.Drawing.Bitmap bitmap) { var hBitmap = bitmap.GetHbitmap(); BitmapSource result = null; try { result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( hBitmap, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } catch (Exception ex) { } finally { //Release resource Win32.DeleteObject(hBitmap); } return(result); }
private void OK_button_Click(object sender, RoutedEventArgs e) { if (themes.Text != "") { ThemeManager.ApplyTheme(App.Current, themes.Text.ToString()); } if (Sourcepath.Text != "") { System.Drawing.Image image = null; image = System.Drawing.Image.FromFile(Sourcepath.Text); var bitmap = new System.Drawing.Bitmap(image); var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions() ); bitmap.Dispose(); var brush = new ImageBrush(bitmapSource); App.mainWindow.Background = brush; } }
private System.Windows.Media.ImageSource ConvertIconToImageSource(VistaTaskDialogIcon icon, Icon customIcon, bool isLarge) { System.Windows.Media.ImageSource iconSource = null; System.Drawing.Icon sysIcon = null; System.Drawing.Bitmap altBmp = null; try { switch (icon) { default: case VistaTaskDialogIcon.None: break; case VistaTaskDialogIcon.Information: sysIcon = SystemIcons.Information; break; case VistaTaskDialogIcon.Warning: sysIcon = SystemIcons.Warning; break; case VistaTaskDialogIcon.Error: sysIcon = SystemIcons.Error; break; case VistaTaskDialogIcon.Shield: if (isLarge) { altBmp = Properties.Resources.shield_32; } else { altBmp = Properties.Resources.shield_16; } break; } // Custom Icons always take priority if (customIcon != null) { iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon( customIcon.Handle, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } else if (sysIcon != null) { iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon( sysIcon.Handle, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } else if (altBmp != null) { iconSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( altBmp.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); } } finally { // Not responsible for disposing of custom icons if (sysIcon != null) { sysIcon.Dispose(); } if (altBmp != null) { altBmp.Dispose(); } } return(iconSource); }
// 调用c++ dll进行抠图 private void DoConvert(int nIndex) { string sInput = AppDomain.CurrentDomain.BaseDirectory + "Datas/input" + nIndex + ".jpg"; byte[] bytes = System.IO.File.ReadAllBytes(sInput); BitmapImage bitImg = new BitmapImage(); bitImg.BeginInit(); bitImg.StreamSource = new System.IO.MemoryStream(bytes); bitImg.EndInit(); bitImg.Freeze(); this.ImgMain.Source = bitImg; string sTrimap = AppDomain.CurrentDomain.BaseDirectory + "Datas/trimap" + nIndex + ".jpg"; System.Drawing.Bitmap oBitmap = new Bitmap(sInput); DateTime timeStart = DateTime.Now; int nlength = oBitmap.Width * oBitmap.Height; IntPtr intptr = GetMatteMap(sInput, sTrimap); int[] arrAlpha = new int[nlength]; Marshal.Copy(intptr, arrAlpha, 0, nlength); System.Drawing.Bitmap newBitmap = new System.Drawing.Bitmap(oBitmap.Width, oBitmap.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newBitmap)) { g.DrawImage(oBitmap, 0, 0); for (int i = 0; i < oBitmap.Height; i++) { for (int j = 0; j < oBitmap.Width; j++) { int nAlpha = arrAlpha[i * oBitmap.Width + j]; if (nAlpha > 0) { System.Drawing.Color pixelColor = oBitmap.GetPixel(j, i); System.Drawing.Color newColor = System.Drawing.Color.FromArgb(nAlpha, pixelColor.R, pixelColor.G, pixelColor.B); newBitmap.SetPixel(j, i, newColor); } else { newBitmap.SetPixel(j, i, System.Drawing.Color.Transparent); } } } } IntPtr ptr = newBitmap.GetHbitmap(); BitmapSource bitmapSrc = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( ptr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); DeleteObject(ptr); this.ImgResult.Source = bitmapSrc; DateTime timeEnd = DateTime.Now; TimeSpan timeInterval = timeEnd - timeStart; this.TbkResult.Text = "Use Time (s) :" + timeInterval.TotalSeconds.ToString(); }
static System.Drawing.Bitmap CopyToBpp(System.Drawing.Bitmap b, int bpp) { if (bpp != 1 && bpp != 8) { throw new System.ArgumentException("1 or 8", "bpp"); } int w = b.Width, h = b.Height; IntPtr hbm = b.GetHbitmap(); BITMAPINFO bmi = new BITMAPINFO(); bmi.biSize = 40; bmi.biWidth = w; bmi.biHeight = h; bmi.biPlanes = 1; bmi.biBitCount = (short)bpp; bmi.biCompression = BI_RGB; bmi.biSizeImage = (uint)(((w + 7) & 0xFFFFFFF8) * h / 8); bmi.biXPelsPerMeter = 1000000; bmi.biYPelsPerMeter = 1000000; // Now for the colour table. uint ncols = (uint)1 << bpp; bmi.biClrUsed = ncols; bmi.biClrImportant = ncols; bmi.cols = new uint[256]; if (bpp == 1) { bmi.cols[0] = MAKERGB(0, 0, 0); bmi.cols[1] = MAKERGB(255, 255, 255); } else { for (int i = 0; i < ncols; i++) { bmi.cols[i] = MAKERGB(i, i, i); } } IntPtr bits0; IntPtr hbm0 = CreateDIBSection(IntPtr.Zero, ref bmi, DIB_RGB_COLORS, out bits0, IntPtr.Zero, 0); IntPtr sdc = GetDC(IntPtr.Zero); IntPtr hdc = CreateCompatibleDC(sdc); SelectObject(hdc, hbm); IntPtr hdc0 = CreateCompatibleDC(sdc); SelectObject(hdc0, hbm0); BitBlt(hdc0, 0, 0, w, h, hdc, 0, 0, SRCCOPY); System.Drawing.Bitmap b0 = System.Drawing.Bitmap.FromHbitmap(hbm0); DeleteDC(hdc); DeleteDC(hdc0); ReleaseDC(IntPtr.Zero, sdc); DeleteObject(hbm); DeleteObject(hbm0); // return(b0); }
private void Button_Click(object sender, RoutedEventArgs e) { plot_gray1 = new int[256]; plot_gray2 = new int[256]; Bitmap gray1_bitmap, gray2_bitmap, diff; //Преобразование из BitmapImage в Bitmap using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(mainImage)); enc.Save(outStream); gray1_bitmap = new System.Drawing.Bitmap(outStream); gray2_bitmap = new System.Drawing.Bitmap(outStream); diff = new System.Drawing.Bitmap(outStream); } for (int i = 0; i < gray1_bitmap.Width; i++) { for (int j = 0; j < gray1_bitmap.Height; j++) { //gray1 System.Drawing.Color c1 = gray1_bitmap.GetPixel(i, j); byte gr = (byte)(0.2126 * c1.R + 0.7152 * c1.G + 0.0722 * c1.B); c1 = System.Drawing.Color.FromArgb(255, gr, gr, gr); gray1_bitmap.SetPixel(i, j, c1); plot_gray1[gr]++; //gray2 System.Drawing.Color c2 = gray2_bitmap.GetPixel(i, j); byte gr2; if ((bool)type_gr.IsChecked) { gr2 = (byte)(0.299 * c2.R + 0.587 * c2.G + 0.114 * c2.B); } else { gr2 = (byte)(0.333 * c2.R + 0.333 * c2.G + 0.333 * c2.B); } c2 = System.Drawing.Color.FromArgb(255, gr2, gr2, gr2); gray2_bitmap.SetPixel(i, j, c2); plot_gray2[gr2]++; //difference byte gr_diff = (byte)Math.Abs(gr - gr2); diff.SetPixel(i, j, System.Drawing.Color.FromArgb(255, gr_diff, gr_diff, gr_diff)); } } BitmapSource b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(gray1_bitmap.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); BitmapSource b2 = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(gray2_bitmap.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); BitmapSource b3 = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(diff.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); gray1.Source = (System.Windows.Media.ImageSource)b; gray2.Source = (System.Windows.Media.ImageSource)b2; difference.Source = (System.Windows.Media.ImageSource)b3; }
/// <summary> /// Copies a bitmap into a 1bpp/8bpp bitmap of the same dimensions, fast /// http://www.wischik.com/lu/programmer/1bpp.html /// </summary> /// <param name="b">original bitmap</param> /// <param name="bpp">1 or 8, target bpp</param> /// <returns>a 1bpp copy of the bitmap</returns> static System.Drawing.Bitmap CopyToBpp(System.Drawing.Bitmap b, int bpp) { if (bpp != 1 && bpp != 8) { throw new System.ArgumentException("1 or 8", "bpp"); } // Plan: built into Windows GDI is the ability to convert // bitmaps from one format to another. Most of the time, this // job is actually done by the graphics hardware accelerator card // and so is extremely fast. The rest of the time, the job is done by // very fast native code. // We will call into this GDI functionality from C#. Our plan: // (1) Convert our Bitmap into a GDI hbitmap (ie. copy unmanaged->managed) // (2) Create a GDI monochrome hbitmap // (3) Use GDI "BitBlt" function to copy from hbitmap into monochrome (as above) // (4) Convert the monochrone hbitmap into a Bitmap (ie. copy unmanaged->managed) int w = b.Width, h = b.Height; IntPtr hbm = b.GetHbitmap(); // this is step (1) // // Step (2): create the monochrome bitmap. // "BITMAPINFO" is an interop-struct which we define below. // In GDI terms, it's a BITMAPHEADERINFO followed by an array of two RGBQUADs BITMAPINFO bmi = new BITMAPINFO(); bmi.biSize = 40; // the size of the BITMAPHEADERINFO struct bmi.biWidth = w; bmi.biHeight = h; bmi.biPlanes = 1; // "planes" are confusing. We always use just 1. Read MSDN for more info. bmi.biBitCount = (short)bpp; // ie. 1bpp or 8bpp bmi.biCompression = BI_RGB; // ie. the pixels in our RGBQUAD table are stored as RGBs, not palette indexes bmi.biSizeImage = (uint)(((w + 7) & 0xFFFFFFF8) * h / 8); bmi.biXPelsPerMeter = 1000000; // not really important bmi.biYPelsPerMeter = 1000000; // not really important // Now for the colour table. uint ncols = (uint)1 << bpp; // 2 colours for 1bpp; 256 colours for 8bpp bmi.biClrUsed = ncols; bmi.biClrImportant = ncols; bmi.cols = new uint[256]; // The structure always has fixed size 256, even if we end up using fewer colours if (bpp == 1) { bmi.cols[0] = MAKERGB(0, 0, 0); bmi.cols[1] = MAKERGB(255, 255, 255); } else { for (int i = 0; i < ncols; i++) { bmi.cols[i] = MAKERGB(i, i, i); } } // For 8bpp we've created an palette with just greyscale colours. // You can set up any palette you want here. Here are some possibilities: // greyscale: for (int i=0; i<256; i++) bmi.cols[i]=MAKERGB(i,i,i); // rainbow: bmi.biClrUsed=216; bmi.biClrImportant=216; int[] colv=new int[6]{0,51,102,153,204,255}; // for (int i=0; i<216; i++) bmi.cols[i]=MAKERGB(colv[i/36],colv[(i/6)%6],colv[i%6]); // optimal: a difficult topic: http://en.wikipedia.org/wiki/Color_quantization // // Now create the indexed bitmap "hbm0" IntPtr bits0; // not used for our purposes. It returns a pointer to the raw bits that make up the bitmap. IntPtr hbm0 = CreateDIBSection(IntPtr.Zero, ref bmi, DIB_RGB_COLORS, out bits0, IntPtr.Zero, 0); // // Step (3): use GDI's BitBlt function to copy from original hbitmap into monocrhome bitmap // GDI programming is kind of confusing... nb. The GDI equivalent of "Graphics" is called a "DC". IntPtr sdc = GetDC(IntPtr.Zero); // First we obtain the DC for the screen // Next, create a DC for the original hbitmap IntPtr hdc = CreateCompatibleDC(sdc); SelectObject(hdc, hbm); // and create a DC for the monochrome hbitmap IntPtr hdc0 = CreateCompatibleDC(sdc); SelectObject(hdc0, hbm0); // Now we can do the BitBlt: BitBlt(hdc0, 0, 0, w, h, hdc, 0, 0, SRCCOPY); // Step (4): convert this monochrome hbitmap back into a Bitmap: System.Drawing.Bitmap b0 = System.Drawing.Bitmap.FromHbitmap(hbm0); // // Finally some cleanup. DeleteDC(hdc); DeleteDC(hdc0); ReleaseDC(IntPtr.Zero, sdc); DeleteObject(hbm); DeleteObject(hbm0); // return(b0); }
/// <summary> /// Initializes a new instance of the <see cref="SeeingSharpRendererElement"/> class. /// </summary> public SeeingSharpRendererElement() { this.Loaded += OnLoaded; this.Unloaded += OnUnloaded; // Basic configuration this.Focusable = true; this.IsHitTestVisible = true; this.Stretch = System.Windows.Media.Stretch.Fill; this.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch; this.VerticalAlignment = System.Windows.VerticalAlignment.Stretch; // Load ummy bitmap using (System.Drawing.Bitmap dummyOrig = Properties.Resources.GfxNotInitialized) { m_dummyBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( dummyOrig.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(500, 500)); } this.Source = m_dummyBitmap; //Create the RenderLoop object GraphicsCore.Touch(); m_renderLoop = new RenderLoop( SynchronizationContext.Current, this, isDesignMode: this.IsInDesignMode()); // Break here if we are in design mode if (this.IsInDesignMode()) { return; } m_renderLoop.ClearColor = Color4.Transparent; m_renderLoop.CallPresentInUIThread = true; // Create new scene and camera object if (SeeingSharpApplication.IsInitialized) { this.Scene = new Core.Scene(); this.Camera = new PerspectiveCamera3D(); } //Attach to SizeChanged event (refresh view resources only after a specific time) if (SeeingSharpApplication.IsInitialized) { // Observe events and trigger rendreing as long as the control lives this.Loaded += (sender, eArgs) => { if (m_controlObserver == null) { m_controlObserver = CommonTools.DisposeObject(m_controlObserver); m_controlObserver = Observable.FromEventPattern <EventArgs>(this, "SizeChanged") .Merge(Observable.FromEventPattern <EventArgs>(m_renderLoop.ViewConfiguration, "ConfigurationChanged")) .Throttle(TimeSpan.FromSeconds(0.5)) .ObserveOn(SynchronizationContext.Current) .Subscribe((innerEArgs) => OnThrottledSizeChanged()); SystemEvents.SessionSwitch += OnSystemEvents_SessionSwitch; } }; this.Unloaded += (sender, eArgs) => { if (m_controlObserver != null) { SystemEvents.SessionSwitch -= OnSystemEvents_SessionSwitch; m_controlObserver = CommonTools.DisposeObject(m_controlObserver); } }; } }
public void LvCalibrate(Action callBack, System.Windows.Forms.PictureBox cavaus) { float exposure = 4096; float runExp = exposure; float maxExp = exposure; float minExp = 1; new Action(delegate() { IntegratingSphere sphere = (IntegratingSphere)DevManage.Instance.SelectDevice(typeof(IntegratingSphere).Name); try { if (ca310Hanle == null) { ca310Hanle = new KonicaCa310(); ca310Hanle.Initiaze(); if (ca310Pipe.ErrorMessage == "") { System.Windows.Forms.MessageBox.Show("Please switch Ca310 to initial mode."); ca310Hanle.Zero(); System.Windows.Forms.MessageBox.Show("Please switch Ca310 to measure mode."); } } fixture.HoldOut(); fixture.IntegratingSphereUp(); sphere.Lighten(); System.Windows.Forms.MessageBox.Show("Software will waitting 5 minutes"); System.Threading.Thread.Sleep(300000); fixture.RotateOn(); // CIE1931Value value = ca310Pipe.GetCa310Data(); CIE1931Value value = ca310Hanle.GetCa310Data(); fixture.RotateOff(); fixture.CameraDown(); fixture.MotorMove(150000); System.Threading.Thread.Sleep(26000); foreach (TestItem item in Items) { if (item.RGB == Color.FromArgb(255, 255, 255)) { do { colorimeter.ExposureTime = runExp; System.Drawing.Bitmap bitmap = colorimeter.GrabImage(); if (cavaus != null) { cavaus.Image = System.Drawing.Image.FromHbitmap(bitmap.GetHbitmap()); } double[] rgbMean = this.Mean(ip.bmp2rgb(bitmap)); if (rgbMean[0] > 230 || rgbMean[1] > 230 || rgbMean[2] > 230) { maxExp = runExp; runExp = (runExp + minExp) / 2; } else if (rgbMean[0] < 215 || rgbMean[1] < 215 || rgbMean[2] < 215) { minExp = runExp; runExp = (runExp + maxExp) / 2; } else { optimalExp = runExp; item.Exposure = optimalExp; } if (Math.Abs(minExp) == Math.Abs(maxExp)) { throw new Exception("Luminance calibration fail."); } }while (true); } else { double faction = (redWeight * item.RGB.R + greenWeight * item.RGB.G + blueWeight * item.RGB.B) / 255; if (faction == 0) { item.Exposure = 4000; } item.Exposure = (float)(optimalExp / faction); } } if (callBack != null) { callBack(); } } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); } finally { if (sphere != null) { sphere.Lightoff(); } if (fixture != null) { fixture.IntegratingSphereDown(); fixture.CameraUp(); fixture.Reset(); } xml.SaveScript(); } }).BeginInvoke(null, null); }
public ImageSource GetWindowImage(IntPtr hWnd, FormsDraw.Rectangle bounds) { using (FormsDraw.Bitmap result = new FormsDraw.Bitmap(bounds.Width, bounds.Height)) { //creates a new Bitmap which will contain the window's image using (FormsDraw.Graphics MemG = FormsDraw.Graphics.FromImage(result)) { //makes a Graphics from the Bitmap whose HDC will hold the window's RAW image IntPtr dc = MemG.GetHdc(); //gets the Bitmap's HDC try { WinUtils.PrintWindow(hWnd, dc, 0);//Writes the window's image to the HDC created above } finally { MemG.ReleaseHdc(dc); } return(System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(result.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); } } }
internal Bitmap(System.Drawing.Bitmap bitmap) { this.hbitmap = bitmap.GetHbitmap(); }