public void Draw(Action <ICanvas2D, Point2> action) { var visual = new DrawingVisual(); var context = visual.RenderOpen(); var canvas2DFactory = new Canvas2DFactory(context); using (var dc = canvas2DFactory.UsingCanvas2D(_RenderTarget.PixelWidth, _RenderTarget.PixelHeight)) { action(dc, (_RenderTarget.PixelWidth, _RenderTarget.PixelHeight)); } context.Close(); _RenderTarget.Render(visual); }
public static void RenderWithCollect(this swm.Imaging.RenderTargetBitmap bitmap, swm.Visual visual) { bitmap.Render(visual); // fix memory leak with RenderTargetBitmap. See http://stackoverflow.com/questions/14786490/wpf-memory-leak-using-rendertargetbitmap // Reproducible with the // GC.Collect alone seems to fix the issue. Adding GC.WaitForPendingFinalizers may impact performance. GC.Collect(); }
public static void SaveToImage(System.Windows.FrameworkElement ui, string fileName, double scale = 1) { System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Create); System.Windows.Media.Imaging.RenderTargetBitmap bmp = new System.Windows.Media.Imaging.RenderTargetBitmap((int)(scale * ui.ActualWidth), (int)(scale * ui.ActualHeight), scale * 96, scale * 96, System.Windows.Media.PixelFormats.Pbgra32); bmp.Render(ui); System.Windows.Media.Imaging.BitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp)); encoder.Save(fs); fs.Close(); }
public void DrawStringTest() { const int ColumnCount = 10; const int MaxDrawCount = 30; // use int.MaxValue to draw them all const double fontSize = 50d; // the height of each cell has to include over/under hanging glyphs var cellSize = new Size(fontSize, fontSize * _glyphTypeface.Height); var glyphs = from glyphIndex in _glyphTypeface.CharacterToGlyphMap.Values select _glyphTypeface.GetGlyphOutline(glyphIndex, fontSize, 1d); // now create the visual we'll draw them to var dv = new System.Windows.Media.DrawingVisual(); var drawCount = -1; using (var dc = dv.RenderOpen()) { foreach (var g in glyphs) { drawCount++; if (drawCount >= MaxDrawCount) { break; // don't draw more than you want } if (g.IsEmpty()) { continue; // don't draw the blank ones } // center horizontally in the cell var xOffset = (drawCount % ColumnCount) * cellSize.Width + (cellSize.Width - g.Bounds.Width) / 2d; // place the character on the baseline of the cell var yOffset = (drawCount / ColumnCount) * cellSize.Height + fontSize * _glyphTypeface.Baseline; dc.PushTransform(new System.Windows.Media.TranslateTransform(xOffset, yOffset)); dc.DrawGeometry(System.Windows.Media.Brushes.Red, null, g); dc.Pop(); // get rid of the transform } } var rowCount = drawCount / ColumnCount; if (drawCount % ColumnCount != 0) { rowCount++; // to include partial rows } var bitWidth = (int)Math.Ceiling(cellSize.Width * ColumnCount); var bitHeight = (int)Math.Ceiling(cellSize.Height * rowCount); var bmp = new System.Windows.Media.Imaging.RenderTargetBitmap(bitWidth, bitHeight, 96, 96, System.Windows.Media.PixelFormats.Pbgra32); bmp.Render(dv); var encoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp)); using (var file = new FileStream("FontTable.png", FileMode.Create)) encoder.Save(file); }
private ToolStripMenuItem SetFonts() { ToolStripMenuItem menuItem = new ToolStripMenuItem("Insert Font"); List <string> fonts = new List <string>(); foreach (System.Windows.Media.FontFamily font in System.Windows.Media.Fonts.SystemFontFamilies) //WPF fonts { fonts.Add(font.FamilyNames.Values.First()); } fonts.Sort(); foreach (string fontName in fonts) { Bitmap bmp = null; try { int size = 20; //bmp = new Bitmap(4 * size, 5 * size / 4); //Graphics g = Graphics.FromImage(bmp); //g.SmoothingMode = SmoothingMode.HighQuality; //g.InterpolationMode = InterpolationMode.HighQualityBicubic; //g.PixelOffsetMode = PixelOffsetMode.HighQuality; //g.DrawString("Basic", new Font(new FontFamily(fontName), size, FontStyle.Regular, GraphicsUnit.Pixel), Brushes.Black, 1, 1); System.Windows.Media.DrawingVisual dv = new System.Windows.Media.DrawingVisual(); using (System.Windows.Media.DrawingContext dc = dv.RenderOpen()) { dc.DrawRectangle(System.Windows.Media.Brushes.White, null, new System.Windows.Rect(0, 0, 4 * size, 5 * size / 4)); dc.DrawText(new System.Windows.Media.FormattedText("Basic", System.Globalization.CultureInfo.InvariantCulture, System.Windows.FlowDirection.LeftToRight, new System.Windows.Media.Typeface(fontName), size, System.Windows.Media.Brushes.Black), new System.Windows.Point(1, 1)); } System.Windows.Media.Imaging.RenderTargetBitmap rtb = new System.Windows.Media.Imaging.RenderTargetBitmap(4 * size, 5 * size / 4, 96, 96, System.Windows.Media.PixelFormats.Pbgra32); rtb.Render(dv); rtb.Freeze(); MemoryStream stream = new MemoryStream(); System.Windows.Media.Imaging.BitmapEncoder encoder = new System.Windows.Media.Imaging.BmpBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb)); encoder.Save(stream); bmp = new Bitmap(stream); } catch { } ToolStripMenuItem item = new ToolStripMenuItem(fontName, bmp, Insert); item.ImageScaling = ToolStripItemImageScaling.None; menuItem.DropDownItems.Add(item); } return(menuItem); }
static void convert(double dpi, string path, string out_path) { double scale = dpi / 96.0; System.Windows.Xps.Packaging.XpsDocument xpsDoc = new System.Windows.Xps.Packaging.XpsDocument( path, System.IO.FileAccess.Read); if (xpsDoc == null) { throw new System.Exception("XpsDocumentfailed"); } System.Windows.Documents.FixedDocumentSequence docSeq = xpsDoc.GetFixedDocumentSequence(); if (docSeq == null) { throw new System.Exception("GetFixedDocumentSequence failed"); } System.Windows.Documents.DocumentReferenceCollection drc = docSeq.References; int index = 0; foreach (System.Windows.Documents.DocumentReference dr in drc) { System.Windows.Documents.FixedDocument dp = dr.GetDocument(false); foreach (System.Windows.Documents.PageContent pc in dp.Pages) { System.Windows.Documents.FixedPage fixedPage = pc.GetPageRoot(false); double width = fixedPage.Width; double height = fixedPage.Height; System.Windows.Size sz = new System.Windows.Size(width, height); fixedPage.Measure(sz); fixedPage.Arrange( new System.Windows.Rect(new System.Windows.Point(), sz)); fixedPage.UpdateLayout(); System.Windows.Media.Imaging.BitmapImage bitmap = new System.Windows.Media.Imaging.BitmapImage(); System.Windows.Media.Imaging.RenderTargetBitmap renderTarget = new System.Windows.Media.Imaging.RenderTargetBitmap( ceil(scale * width), ceil(scale * height), dpi, dpi, System.Windows.Media.PixelFormats.Default); renderTarget.Render(fixedPage); System.Windows.Media.Imaging.BitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); encoder.Frames.Add( System.Windows.Media.Imaging.BitmapFrame.Create(renderTarget)); string filename = string.Format("{0}_{1}.png", out_path, index); System.IO.FileStream pageOutStream = new System.IO.FileStream( filename, System.IO.FileMode.Create, System.IO.FileAccess.Write); encoder.Save(pageOutStream); pageOutStream.Close(); System.Console.WriteLine(filename); ++index; } } }
public static void RenderWithCollect(this swm.Imaging.RenderTargetBitmap bitmap, swm.Visual visual) { bitmap.Render(visual); // fix memory leak with RenderTargetBitmap. See http://stackoverflow.com/questions/14786490/wpf-memory-leak-using-rendertargetbitmap // Reproducible with the // GC.Collect alone seems to fix the issue. Adding GC.WaitForPendingFinalizers may impact performance. // Note: this may no longer be an issue with the latest version of .NET after some testing, however // we keep it here to keep memory in check, but instead make it non-blocking so it doesn't cause a huge // performance penalty creating many Bitmaps with a Graphics object. GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, false); }
public System.Drawing.Bitmap RenderSingleCharacter(ushort glyphIndex, System.Drawing.Color backColor, System.Drawing.Color foreColor, int fontSize) { try { var geometry = _glyphTypeface.GetGlyphOutline(glyphIndex, fontSize, 1); var advanceWidth = _glyphTypeface.AdvanceWidths[glyphIndex]; var cellSize = new Size(fontSize, fontSize * _glyphTypeface.Height); var offsetX = advanceWidth * cellSize.Width; var offsetY = fontSize * _glyphTypeface.Baseline; var drawingVisual = new System.Windows.Media.DrawingVisual(); var brush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(foreColor.A, foreColor.R, foreColor.G, foreColor.B)); var pen = new System.Windows.Media.Pen(); using (var dc = drawingVisual.RenderOpen()) { dc.PushTransform(new System.Windows.Media.TranslateTransform(0, offsetY)); dc.DrawGeometry(brush, null, geometry); dc.Pop(); // get rid of the transform } var bitWidth = (int)Math.Ceiling(offsetX); var bitHeight = (int)Math.Ceiling(cellSize.Height); var targetImage = new System.Windows.Media.Imaging.RenderTargetBitmap(bitWidth, bitHeight, Dpi, Dpi, System.Windows.Media.PixelFormats.Pbgra32); targetImage.Render(drawingVisual); var bmpEncoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); bmpEncoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(targetImage)); var bmp = new System.Drawing.Bitmap(bitWidth, bitHeight); bmp.SetResolution(Dpi, Dpi); using (var graphics = System.Drawing.Graphics.FromImage(bmp)) { graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.Clear(backColor); using (var ms = new MemoryStream()) { bmpEncoder.Save(ms); graphics.DrawImage(System.Drawing.Image.FromStream(ms), new System.Drawing.PointF(0, 0)); } graphics.Save(); } return(bmp); } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } }
// Do printing to a set of bitmaps using the XPS/WPF path. This is used for testing support. public System.Windows.Media.Imaging.BitmapSource[] PrintXpsBitmaps(float dpi) { // Set up and position everything. printingToBitmaps = true; printPreviewInProgress = false; SetupPrinting(); if (totalPages <= 0) { return(new System.Windows.Media.Imaging.BitmapSource[0]); } PrintEventArgs printArgs = new PrintEventArgs(); List <System.Windows.Media.Imaging.BitmapSource> bitmapList = new List <System.Windows.Media.Imaging.BitmapSource>(); BeginPrint(this, printArgs); float paperWidth = pageSettings.PaperSize.Width, paperHeight = pageSettings.PaperSize.Height; if (pageSettings.Landscape) { float temp = paperWidth; paperWidth = paperHeight; paperHeight = temp; } var paginator = new Paginator(this, 0, new SizeF(paperWidth, paperHeight), pageSettings.Margins, dpi, false); for (int pageNumber = 0; pageNumber < paginator.PageCount; ++pageNumber) { DocumentPage docPage = paginator.GetPage(pageNumber); paperWidth = (float)PointsToHundreths(docPage.Size.Width); paperHeight = (float)PointsToHundreths(docPage.Size.Height); var bitmapNew = new System.Windows.Media.Imaging.RenderTargetBitmap( (int)Math.Round(paperWidth * dpi / 100F), (int)Math.Round(paperHeight * dpi / 100F), dpi, dpi, System.Windows.Media.PixelFormats.Pbgra32); bitmapNew.Render(docPage.Visual); bitmapNew.Freeze(); bitmapList.Add(bitmapNew); } EndPrint(this, printArgs); return(bitmapList.ToArray()); }
private void DrawToImage(FrameworkElement element) { element.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity)); element.Arrange(new Rect(element.DesiredSize)); System.Windows.Media.Imaging.RenderTargetBitmap bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 120.0, 120.0, System.Windows.Media.PixelFormats.Pbgra32); bitmap.Render(element); System.Windows.Media.Imaging.BitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bitmap)); using (Stream s = File.OpenWrite(@"C:\555.png")) { encoder.Save(s); } }
public static void GenerateImage(System.Windows.Controls.Viewbox control, Stream result) { //Set background to white //control.Background = System.Windows.Media.Brushes.White; System.Windows.Size controlSize = RetrieveDesiredSize(control); System.Windows.Rect rect = new System.Windows.Rect(0, 0, controlSize.Width, controlSize.Height); System.Windows.Media.Imaging.RenderTargetBitmap rtb = new System.Windows.Media.Imaging.RenderTargetBitmap((int)controlSize.Width, (int)controlSize.Height, IMAGE_DPI, IMAGE_DPI, PixelFormats.Pbgra32); control.Arrange(rect); rtb.Render(control); System.Windows.Media.Imaging.PngBitmapEncoder png = new System.Windows.Media.Imaging.PngBitmapEncoder(); png.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb)); png.Save(result); }
/// <summary> /// Converts the framework element to drawing visual. /// </summary> /// <param name="element">The framework element that must be converted.</param> /// <param name="size">The size of the diagram.</param> /// <returns>A new DrawingVisual with the Diagram.</returns> internal static System.Windows.Media.DrawingVisual DrawingVisualFromFrameworkElement(System.Windows.FrameworkElement element, System.Windows.Size size) { System.Windows.Media.DrawingVisual dv = new System.Windows.Media.DrawingVisual(); System.Windows.Media.Imaging.RenderTargetBitmap renderBitmap = new System.Windows.Media.Imaging.RenderTargetBitmap( (int)size.Width, (int)size.Height, 96D, 96D, System.Windows.Media.PixelFormats.Default); renderBitmap.Render(element); using (System.Windows.Media.DrawingContext context = dv.RenderOpen()) { context.DrawImage(renderBitmap, new System.Windows.Rect(size)); } return dv; }
/// <summary> /// Função privada para converter a o Chart para imagem /// </summary> /// <param name="visual">Objeto que deseja salvar em tipo PNG</param> /// <param name="filename">Onde será salvo</param> /// <param name="encoder">Tipo de codificação da imagem</param> private static void EncodeVisual(FrameworkElement visual, string filename, System.Windows.Media.Imaging.BitmapEncoder encoder) { try { // Os itens 96 e 74 deve-se ser modificado conforme a necessidade da imagem. var bitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 74, PixelFormats.Pbgra32); bitmap.Render(visual); var frame = System.Windows.Media.Imaging.BitmapFrame.Create(bitmap); encoder.Frames.Add(frame); using (var stream = File.Create(filename)) encoder.Save(stream); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error Message"); } }
// Sources //https://stackoverflow.com/questions/20623126/inkcanvas-to-bitmap //https://stackoverflow.com/a/554455 public void UpdateThumbnail() { // TODO : Fix align? int margin = (int)Canvas.Margin.Left; int width = (int)Canvas.ActualWidth; int height = (int)Canvas.ActualHeight; //render ink to bitmap System.Windows.Media.Imaging.RenderTargetBitmap renderBitmap = new System.Windows.Media.Imaging.RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Default); renderBitmap.Render(Canvas); using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()) { System.Windows.Media.Imaging.JpegBitmapEncoder encoder = new System.Windows.Media.Imaging.JpegBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(renderBitmap)); encoder.Save(memStream); string b64 = Convert.ToBase64String(memStream.ToArray()); networkManager.PostThumbnail(Username, SessionId, SocketManager.SessionID, b64); } }
public static System.Windows.Media.Imaging.BitmapSource Generate(HDT.Hearthstone.Deck deck, bool cardsOnly) { const int CardHeight = 35; const int InfoHeight = 124; const int ScreenshotWidth = 219; const int Dpi = 96; var height = CardHeight * deck.GetSelectedDeckVersion().Cards.Count; if (!cardsOnly) { height += InfoHeight; } var control = new HDT.Controls.DeckView(deck, cardsOnly); control.Measure(new System.Windows.Size(ScreenshotWidth, height)); control.Arrange(new System.Windows.Rect(new System.Windows.Size(ScreenshotWidth, height))); control.UpdateLayout(); //Log.Debug($"Screenshot: {control.ActualWidth} x {control.ActualHeight}"); var bmp = new System.Windows.Media.Imaging.RenderTargetBitmap(ScreenshotWidth, height, Dpi, Dpi, System.Windows.Media.PixelFormats.Pbgra32); bmp.Render(control); return(bmp); }
/* * // Windows Forms版 TODO: 直書きあり * public static void DrawString(string str, double fontSize) * { * var window = System.Windows.Application.Current.MainWindow; * * double[] glDoubleColor = new double[4]; * GL.GetDouble(GetPName.CurrentColor, glDoubleColor); * byte glR = (byte)(glDoubleColor[0] * 255); * byte glG = (byte)(glDoubleColor[1] * 255); * byte glB = (byte)(glDoubleColor[2] * 255); * byte glA = (byte)(glDoubleColor[3] * 255); //255; * var glColor = System.Drawing.Color.FromArgb(glA, glR, glG, glB); * System.Drawing.Brush foreground = new System.Drawing.SolidBrush(glColor); * * //var font = new System.Drawing.Font("Arial", 12); * //var font = new System.Drawing.Font(window.FontFamily.Source, (int)window.FontSize); * // 1 point = 1 / 72.0 inch = (1 / 72.0) * 96 = 1.333333 pixel * var font = new System.Drawing.Font(window.FontFamily.Source, (int)(fontSize / 1.333333)); * // サイズ取得用に生成 * var bmp = new System.Drawing.Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format32bppArgb); * System.Drawing.SizeF size; * using (var g = System.Drawing.Graphics.FromImage(bmp)) * { * g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; * * size = g.MeasureString(str, font); * } * * // 再生成 * { * int width = (int)size.Width; * //int height = (int)size.Height; * // TODO: テキストのY座標がずれている : 画像の高さが大きすぎる * int height = (int)(size.Height * 0.75); * bmp = new System.Drawing.Bitmap(width, height, * System.Drawing.Imaging.PixelFormat.Format32bppArgb); * } * * using (var g = System.Drawing.Graphics.FromImage(bmp)) * { * g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; * * g.DrawString(str, font, foreground, new System.Drawing.Point(0, 0)); * } * * // check * //bmp.Save("1.bmp"); * * // 上下反転する * bmp.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY); * * var bitmapData = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), * System.Drawing.Imaging.ImageLockMode.ReadOnly, * System.Drawing.Imaging.PixelFormat.Format32bppArgb); * int bmpWidth = bitmapData.Width; * int bmpHeight = bitmapData.Height; * * bool isTexture = GL.IsEnabled(EnableCap.Texture2D); * bool isBlend = GL.IsEnabled(EnableCap.Blend); * GL.Enable(EnableCap.Texture2D); * GL.Enable(EnableCap.Blend); * GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha); * * int texture = GL.GenTexture(); * GL.BindTexture(TextureTarget.Texture2D, texture); * GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, * (int)TextureMinFilter.Linear); * GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, * (int)TextureMagFilter.Linear); * GL.TexImage2D(TextureTarget.Texture2D, 0, * PixelInternalFormat.Rgba, * bmpWidth, bmpHeight, 0, * PixelFormat.Bgra, PixelType.UnsignedByte, bitmapData.Scan0); * * GL.PushMatrix(); * OpenTK.Matrix4d m; * GL.GetDouble(GetPName.ModelviewMatrix, out m); * //GL.Translate(0, 0, -m.M14); * GL.Scale(1.0 / m.M11, 1.0 / m.M22, 1.0 / m.M33); * GL.Scale(FontScale, FontScale, 1.0); // TODO: これを計算で求める必要がある * * GL.Begin(PrimitiveType.Quads); * GL.TexCoord2(0, 0); * GL.Vertex2(0, 0); * * GL.TexCoord2(1, 0); * GL.Vertex2(bmpWidth, 0); * * GL.TexCoord2(1, 1); * GL.Vertex2(bmpWidth, bmpHeight); * * GL.TexCoord2(0, 1); * GL.Vertex2(0, bmpHeight); * GL.End(); * GL.PopMatrix(); * * bmp.UnlockBits(bitmapData); * * if (!isTexture) * { * GL.Disable(EnableCap.Texture2D); * } * if (!isBlend) * { * GL.Disable(EnableCap.Blend); * } * } */ // WPF版 TODO: 直書きあり public static void DrawString(string str, double fontSize) { var window = System.Windows.Application.Current.MainWindow; double[] glDoubleColor = new double[4]; GL.GetDouble(GetPName.CurrentColor, glDoubleColor); var glColor = new System.Windows.Media.Color(); glColor.R = (byte)(glDoubleColor[0] * 255); glColor.G = (byte)(glDoubleColor[1] * 255); glColor.B = (byte)(glDoubleColor[2] * 255); glColor.A = (byte)(glDoubleColor[3] * 255); //255; System.Windows.Media.Brush foreground = new System.Windows.Media.SolidColorBrush(glColor); //System.Windows.Media.Brush foreground = window.Foreground; var text = new System.Windows.Media.FormattedText( str, new System.Globalization.CultureInfo("en-us"), System.Windows.FlowDirection.LeftToRight, new System.Windows.Media.Typeface( window.FontFamily, System.Windows.FontStyles.Normal, System.Windows.FontWeights.Normal, new System.Windows.FontStretch()), fontSize, //window.FontSize, foreground); var drawingVisual = new System.Windows.Media.DrawingVisual(); using (System.Windows.Media.DrawingContext drawingContext = drawingVisual.RenderOpen()) { drawingContext.DrawText(text, new System.Windows.Point(0, 0)); } System.Windows.Media.Imaging.RenderTargetBitmap bmp = null; { int width = (int)text.Width; int height = (int)text.Height; int dpiX = 96; int dpiY = 96; bmp = new System.Windows.Media.Imaging.RenderTargetBitmap( width, height, dpiX, dpiY, System.Windows.Media.PixelFormats.Pbgra32); } bmp.Render(drawingVisual); int bmpWidth = bmp.PixelWidth; int bmpHeight = bmp.PixelHeight; int stride = bmpWidth * 4; byte[] tmpbits = new byte[stride * bmpHeight]; var rectangle = new System.Windows.Int32Rect(0, 0, bmpWidth, bmpHeight); bmp.CopyPixels(rectangle, tmpbits, stride, 0); // 上下反転する byte[] bits = new byte[stride * bmpHeight]; for (int h = 0; h < bmpHeight; h++) { for (int w = 0; w < stride; w++) { bits[h * stride + w] = tmpbits[(bmpHeight - 1 - h) * stride + w]; } } // check //var png = new System.Windows.Media.Imaging.PngBitmapEncoder(); //png.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(bmp)); //using (var fs = new FileStream("1.png", FileMode.Create)) //{ // png.Save(fs); //} bool isTexture = GL.IsEnabled(EnableCap.Texture2D); bool isBlend = GL.IsEnabled(EnableCap.Blend); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha); int texture = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, texture); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmpWidth, bmpHeight, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bits); GL.PushMatrix(); OpenTK.Matrix4d m; GL.GetDouble(GetPName.ModelviewMatrix, out m); GL.Scale(1.0 / m.M11, 1.0 / m.M22, 1.0 / m.M33); GL.Scale(FontScale, FontScale, 1.0); // TODO: これを計算で求める必要がある GL.Begin(PrimitiveType.Quads); GL.TexCoord2(0, 0); GL.Vertex2(0, 0); GL.TexCoord2(1, 0); GL.Vertex2(bmpWidth, 0); GL.TexCoord2(1, 1); GL.Vertex2(bmpWidth, bmpHeight); GL.TexCoord2(0, 1); GL.Vertex2(0, bmpHeight); GL.End(); GL.PopMatrix(); if (!isTexture) { GL.Disable(EnableCap.Texture2D); } if (!isBlend) { GL.Disable(EnableCap.Blend); } }
// Do printing to a set of bitmaps using the XPS/WPF path. This is used for testing support. public System.Windows.Media.Imaging.BitmapSource[] PrintXpsBitmaps(float dpi) { // Set up and position everything. printingToBitmaps = true; printPreviewInProgress = false; SetupPrinting(); if (totalPages <= 0) return new System.Windows.Media.Imaging.BitmapSource[0]; PrintEventArgs printArgs = new PrintEventArgs(); List<System.Windows.Media.Imaging.BitmapSource> bitmapList = new List<System.Windows.Media.Imaging.BitmapSource>(); BeginPrint(this, printArgs); float paperWidth = pageSettings.PaperSize.Width, paperHeight = pageSettings.PaperSize.Height; if (pageSettings.Landscape) { float temp = paperWidth; paperWidth = paperHeight; paperHeight = temp; } var paginator = new Paginator(this, 0, new SizeF(paperWidth, paperHeight), pageSettings.Margins, dpi, false); for (int pageNumber = 0; pageNumber < paginator.PageCount; ++pageNumber) { DocumentPage docPage = paginator.GetPage(pageNumber); paperWidth = (float)PointsToHundreths(docPage.Size.Width); paperHeight = (float)PointsToHundreths(docPage.Size.Height); var bitmapNew = new System.Windows.Media.Imaging.RenderTargetBitmap( (int) Math.Round(paperWidth * dpi / 100F), (int) Math.Round(paperHeight * dpi / 100F), dpi, dpi, System.Windows.Media.PixelFormats.Pbgra32); bitmapNew.Render(docPage.Visual); bitmapNew.Freeze(); bitmapList.Add(bitmapNew); } EndPrint(this, printArgs); return bitmapList.ToArray(); }
public static void CreateRemappedRasterFromVector(string xamlFile, System.Windows.Media.Color newColor, System.IO.Stream stream, double height, double width, string dynamicText) { string remapBase = "ReMapMe_"; int max = 3; int index = 0; int missed = 0; Object temp = null; string dynamText = "DynamicText"; System.Windows.Controls.Canvas theVisual = System.Windows.Markup.XamlReader.Load(new System.IO.FileStream(xamlFile, System.IO.FileMode.Open)) as System.Windows.Controls.Canvas; if (null == theVisual) { return; } System.Windows.Size size = new System.Windows.Size(width, height); System.Windows.Media.DrawingVisual drawingVisual = new System.Windows.Media.DrawingVisual(); System.Windows.Media.VisualBrush visualBrush = new System.Windows.Media.VisualBrush(theVisual); System.Windows.Rect rect = new System.Windows.Rect(new System.Windows.Point(), size); while (missed < max) { string elementid = remapBase + index; temp = theVisual.FindName(elementid); if (null == temp) { missed++; index++; continue; } System.Windows.Media.SolidColorBrush scb = ((temp as System.Windows.Shapes.Path).Fill as System.Windows.Media.SolidColorBrush); System.Windows.Media.Color c = scb.Color; c.B = newColor.B; c.R = newColor.R; c.G = newColor.G; scb.Color = c; index++; } theVisual.Arrange(rect); theVisual.UpdateLayout(); using (System.Windows.Media.DrawingContext dc = drawingVisual.RenderOpen()) { dc.DrawRectangle(visualBrush, null, rect); } if (!dynamText.IsNullOrWhitespace()) { temp = theVisual.FindName(dynamText); if (null != temp) { //do dynamic text shit } } System.Windows.Media.Imaging.RenderTargetBitmap render = new System.Windows.Media.Imaging.RenderTargetBitmap((int)height, (int)width, 96, 96, System.Windows.Media.PixelFormats.Pbgra32); render.Render(drawingVisual); System.Windows.Media.Imaging.PngBitmapEncoder encoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(render)); encoder.Save(stream); stream.Flush(); stream.Close(); visualBrush = null; drawingVisual = null; theVisual = null; render = null; encoder = null; }
public System.Windows.Media.Imaging.RenderTargetBitmap CaptureSnapshot() { System.Windows.Media.Imaging.RenderTargetBitmap renderTarget = new System.Windows.Media.Imaging.RenderTargetBitmap((int)DisplayGrid.ActualWidth, (int)DisplayGrid.ActualHeight, 96, 96, PixelFormats.Pbgra32); renderTarget.Render(DisplayGrid); return(renderTarget); }
public Bitmap Shadow(Bitmap src, Color color, int width, double opacity = 0.6f, double angle = 315) { Bitmap result = new Bitmap(src); #region Get DPI float dpiX = 96f; float dpiY = 96f; using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { dpiX = g.DpiX; dpiY = g.DpiY; } #endregion int offset = 4 * width; #region Create Effect var effect = new Media.Effects.DropShadowEffect(); effect.BlurRadius = width; effect.Color = color.ToMediaColor(); effect.Direction = angle; effect.Opacity = opacity; effect.ShadowDepth = width; //var effect = new Media.Effects.BlurEffect(); //effect.Radius = 50; #endregion #region Draw source bitmap to DrawingVisual Media.DrawingVisual drawingVisual = new Media.DrawingVisual(); drawingVisual.Effect = effect; using (var drawingContext = drawingVisual.RenderOpen()) { System.Windows.Rect dRect = new System.Windows.Rect(2 * width, 2 * width, src.Width, src.Height); drawingContext.DrawImage(src.ToBitmapSource(), dRect); drawingContext.Close(); } #endregion #region Render the DrawingVisual into a RenderTargetBitmap var rtb = new Media.Imaging.RenderTargetBitmap( src.Width + offset, src.Height + offset, dpiX, dpiY, Media.PixelFormats.Pbgra32); rtb.Render(drawingVisual); #endregion #region Create a System.Drawing.Bitmap var bitmap = new Bitmap(rtb.PixelWidth, rtb.PixelHeight, PixelFormat.Format32bppArgb); #endregion #region Copy the RenderTargetBitmap pixels into the bitmap's pixel buffer var pdata = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat); rtb.CopyPixels(System.Windows.Int32Rect.Empty, pdata.Scan0, pdata.Stride * pdata.Height, pdata.Stride); bitmap.UnlockBits(pdata); #endregion #region Crop Transparent Area var rect = bitmap.ContentBound(); result = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat); using (var g = Graphics.FromImage(result)) { g.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel); } #endregion return(result); }
public Bitmap Shader(Bitmap src, double radius = 10) { Bitmap result = new Bitmap(src); #region Get DPI float dpiX = 96f; float dpiY = 96f; using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) { dpiX = g.DpiX; dpiY = g.DpiY; } #endregion int width = (int)Math.Ceiling(radius); int offset = 4 * width; #region Create Effect var effect = new MyShaderEffect(); //Media.Effects.ShaderRenderMode = Media.Effects.ShaderRenderMode.Auto; //effect. #endregion #region Draw source bitmap to DrawingVisual Media.DrawingVisual drawingVisual = new Media.DrawingVisual(); drawingVisual.Effect = effect; using (var drawingContext = drawingVisual.RenderOpen()) { //drawingContext.PushEffect( new Media.Effects.BlurBitmapEffect(), null ); System.Windows.Rect dRect = new System.Windows.Rect(2 * width, 2 * width, src.Width, src.Height); drawingContext.DrawImage(src.ToBitmapSource(), dRect); drawingContext.Close(); } #endregion #region Render the DrawingVisual into a RenderTargetBitmap var rtb = new Media.Imaging.RenderTargetBitmap( src.Width + offset, src.Height * offset, dpiX, dpiY, Media.PixelFormats.Pbgra32); rtb.Render(drawingVisual); #endregion #region Create a System.Drawing.Bitmap var bitmap = new Bitmap(rtb.PixelWidth, rtb.PixelHeight, PixelFormat.Format32bppArgb); #endregion #region Copy the RenderTargetBitmap pixels into the bitmap's pixel buffer var pdata = bitmap.LockBits( new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat); rtb.CopyPixels(System.Windows.Int32Rect.Empty, pdata.Scan0, pdata.Stride * pdata.Height, pdata.Stride); bitmap.UnlockBits(pdata); #endregion #region Crop Opaque var rect = bitmap.ContentBound(); rect.Width = rect.Width < 0 ? 1 : rect.Width + 2; rect.Height = rect.Height < 0 ? 1 : rect.Height + 2; result = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat); using (var g = Graphics.FromImage(result)) { g.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel); } #endregion return(result); }
/// <summary> /// 渲染字符串 /// </summary> /// <param name="previewText"></param> /// <param name="backColor">背景色</param> /// <param name="foreColor">前景色</param> /// <param name="fontSize">font size in pixel</param> /// <returns></returns> public System.Drawing.Bitmap RenderString(string previewText, System.Drawing.Color backColor, System.Drawing.Color foreColor, int fontSize) { try { if (string.IsNullOrWhiteSpace(previewText)) { if (_glyphTypeface.FamilyNames.Count == 0) { previewText = "no name"; } else if (_glyphTypeface.FamilyNames.ContainsKey(CultureInfo.CurrentCulture)) { previewText = _glyphTypeface.FamilyNames[CultureInfo.CurrentCulture]; } else { previewText = _glyphTypeface.FamilyNames[_glyphTypeface.FamilyNames.Keys.First()]; } } var glyphIndexList = GetGlyphIndexList(previewText); if (glyphIndexList.Count <= 0) { return(null); } var geometryList = glyphIndexList.Select(glyphIndex => _glyphTypeface.GetGlyphOutline(glyphIndex, fontSize, 1d)).ToList(); var advanceWidthList = glyphIndexList.Select(glyphIndex => _glyphTypeface.AdvanceWidths[glyphIndex]).ToList(); var cellSize = new Size(fontSize, fontSize * _glyphTypeface.Height); var offsetX = 0d; var offsetY = fontSize * _glyphTypeface.Baseline; var drawingVisual = new System.Windows.Media.DrawingVisual(); var brush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(foreColor.R, foreColor.G, foreColor.B)); //var pen = new System.Windows.Media.Pen(brush, 0); using (var dc = drawingVisual.RenderOpen()) { for (var i = 0; i < geometryList.Count; i++) { var geometry = geometryList[i]; var advanceWidth = advanceWidthList[i]; //if (geometry.IsEmpty()) continue; dc.PushTransform(new System.Windows.Media.TranslateTransform(offsetX, offsetY)); dc.DrawGeometry(brush, null, geometry); dc.Pop(); // get rid of the transform offsetX += advanceWidth * cellSize.Width; } } var bitWidth = (int)Math.Ceiling(offsetX); var bitHeight = (int)Math.Ceiling(cellSize.Height); var targetImage = new System.Windows.Media.Imaging.RenderTargetBitmap(bitWidth, bitHeight, Dpi, Dpi, System.Windows.Media.PixelFormats.Pbgra32); targetImage.Render(drawingVisual); var bmpEncoder = new System.Windows.Media.Imaging.PngBitmapEncoder(); bmpEncoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(targetImage)); //redraw to Bitmap var bmp = new System.Drawing.Bitmap(bitWidth, bitHeight); bmp.SetResolution(Dpi, Dpi); using (var graphics = System.Drawing.Graphics.FromImage(bmp)) { graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.Clear(backColor); using (var ms = new MemoryStream()) { bmpEncoder.Save(ms); graphics.DrawImage(System.Drawing.Image.FromStream(ms), new System.Drawing.PointF(0, 0)); } graphics.Save(); } return(bmp); } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } }
///<summary>生成3D模型</summary> public void genModel() { //数据初始化 //定义参数 double maxX3D = parent.para.Limit.X, maxY3D = parent.para.Limit.Y, maxZ3D = parent.para.Limit.Z; // 3D场景最大坐标 int xcount = 12, zcount = 24, xcountData, zcountData = 25; // x y 方向数目,x为月数,z为小时数,其中,xcount表征月分,xcountData为数据的x方向个数 //zcount为0-23点,但zcountData为0-24点,多一个数据,同理,xcount中,增加一个数,全年下为12.31日 xcountData = samplePoints.GroupBy(p => p.zDate.Date).Count(); MeshGeometry3D mesh = new MeshGeometry3D(); double devx = maxX3D / (xcount), devy = maxY3D / parent.maxYValue, devz = maxZ3D / (zcount); allpoint = new Point3D[xcountData, zcountData]; double tx, tz; int di, dj; di = 0; DateTime olddate = samplePoints.OrderBy(p => p.zDate).First().zDate.Date; foreach (var e in samplePoints.OrderBy(p => p.zDate)) { //di = e.zDate.Month - 1; if (e.zDate.Date != olddate) { di++; olddate = e.zDate.Date; } dj = e.zDate.Hour; allpoint[di, dj] = new Point3D((double)((e.zDate - parent.startDate).TotalDays - 1) / ((parent.endDate - parent.startDate).TotalDays - 1) * maxX3D, devy * (double)e.zValue, -devz * dj); if (dj == 0) //赋第24点,以本日0代替 { allpoint[di, zcountData - 1] = new Point3D((double)((e.zDate - parent.startDate).TotalDays - 1) / ((parent.endDate - parent.startDate).TotalDays - 1) * maxX3D, devy * (double)e.zValue, -devz * (zcountData - 1)); } } allpoint = insertZPoint(allpoint, 2); //z插点 allpoint = insertXPoint(allpoint, 2); //x插点 for (int i = 0; i < allpoint.GetLength(0); i++) //加positions { for (int j = 0; j < allpoint.GetLength(1); j++) { mesh.Positions.Add(allpoint[i, j]); tx = 1.0 * i / allpoint.GetLength(0); tz = 1.0 * j / allpoint.GetLength(1); mesh.TextureCoordinates.Add(new Point(tx, tz)); } } for (int i = 0; i < allpoint.GetLength(0) - 1; i++) // 加三角索引 { for (int j = 0; j < allpoint.GetLength(1) - 1; j++) { mesh.TriangleIndices.Add(j + i * allpoint.GetLength(1)); mesh.TriangleIndices.Add(j + (i + 1) * allpoint.GetLength(1)); mesh.TriangleIndices.Add(j + 1 + i * allpoint.GetLength(1)); mesh.TriangleIndices.Add(j + 1 + i * allpoint.GetLength(1)); mesh.TriangleIndices.Add(j + (i + 1) * allpoint.GetLength(1)); mesh.TriangleIndices.Add(j + 1 + (i + 1) * allpoint.GetLength(1)); } } //=============== 曲面材质 Canvas panelLine = new Canvas(); panelLine.Width = devx * (parent.endDate - parent.startDate).TotalDays; panelLine.Height = devz * 23 * 30; //色变化说明:最高255,0,0最低0,255,0;从低到高变化顺序1:R 0->255,2:G 255->0; double x, y, maxy = 10, miny = 0, maxh = panelLine.Height, maxw = panelLine.Width; double w = maxw / (allpoint.GetLength(0) - 1), h = maxh / (allpoint.GetLength(1) - 1); double v; Color c1, c2; byte cr, cg, cb = 0; maxy = 0; miny = 10000; for (int i = 0; i < allpoint.GetLength(0) - 1; i++) { for (int j = 0; j < allpoint.GetLength(1) - 1; j++) { if (allpoint[i, j].Y > maxy) { maxy = allpoint[i, j].Y; } if (allpoint[i, j].Y < miny) { miny = allpoint[i, j].Y; } } } Point3D lastpoint = allpoint[allpoint.GetLength(0) - 1, allpoint.GetLength(1) - 1]; for (int i = 0; i < allpoint.GetLength(0) - 1; i++) { for (int j = 0; j < allpoint.GetLength(1) - 1; j++) { x = allpoint[i, j].X / lastpoint.X * maxw; y = allpoint[i, j].Z / lastpoint.Z * maxh; w = (allpoint[i + 1, j].X - allpoint[i, j].X) / lastpoint.X * maxw; double temp = 1;// .2;//新疆怪需求,人为加大最大值,以避免纯红 v = (allpoint[i, j].Y - miny) / (maxy * temp - miny) * 511; cr = v > 255 ? (byte)255 : (byte)v; cg = v > 255 ? (byte)(255 - (v - 256)) : (byte)255; c1 = Color.FromRgb(cr, cg, cb); v = (allpoint[i + 1, j + 1].Y - miny) / (maxy * temp - miny) * 511; cr = v > 255 ? (byte)255 : (byte)v; cg = v > 255 ? (byte)(255 - (v - 256)) : (byte)255; c2 = Color.FromRgb(cr, cg, cb); RectangleGeometry rect = new RectangleGeometry(new Rect(x, y, w, h)); rect.Freeze(); Path pr = new Path(); pr.Data = rect; LinearGradientBrush cbrush = new LinearGradientBrush(c1, c2, new Point(0, 0), new Point(1, 1)); pr.Fill = cbrush; pr.StrokeThickness = 0; panelLine.Children.Add(pr); } } panelLine.Measure(new System.Windows.Size(h, w)); panelLine.Arrange(new Rect(0, 0, h, w)); System.Windows.Media.Imaging.RenderTargetBitmap renderTarget = new System.Windows.Media.Imaging.RenderTargetBitmap((int)panelLine.Width, (int)panelLine.Height, 96, 96, PixelFormats.Pbgra32); renderTarget.Render(panelLine); renderTarget.Freeze(); curveBrush = new ImageBrush(renderTarget); DiffuseMaterial mat = new DiffuseMaterial(curveBrush); mat.Freeze(); model = new GeometryModel3D(mesh, mat); model.BackMaterial = mat; }