public override void Draw(System.Drawing.RectangleF dirtyRect) { var g = new Graphics(); // NSView does not have a background color so we just use Clear to white here g.Clear(Color.White); //RectangleF ClientRectangle = this.Bounds; RectangleF ClientRectangle = dirtyRect; // Calculate the location and size of the drawing area // within which we want to draw the graphics: Rectangle rect = new Rectangle((int)ClientRectangle.X, (int)ClientRectangle.Y, (int)ClientRectangle.Width, (int)ClientRectangle.Height); drawingRectangle = new Rectangle(rect.Location, rect.Size); drawingRectangle.Inflate(-offset, -offset); //Draw ClientRectangle and drawingRectangle using Pen: g.DrawRectangle(Pens.Red, rect); g.DrawRectangle(Pens.Black, drawingRectangle); // Draw a line from point (3,2) to Point (6, 7) // using the Pen with a width of 3 pixels: Pen aPen = new Pen(Color.Green, 3); g.DrawLine(aPen, Point2D(new PointF(3, 2)), Point2D(new PointF(6, 7))); g.PageUnit = GraphicsUnit.Inch; ClientRectangle = new RectangleF(0.5f,0.5f, 1.5f, 1.5f); aPen.Width = 1 / g.DpiX; g.DrawRectangle(aPen, ClientRectangle); aPen.Dispose(); g.Dispose(); }
/// <summary> /// Function to return a glyph bitmap, sized to fit the glyph. /// </summary> /// <param name="oldBitmap">The previous bitmap used to store the glyph.</param> /// <param name="oldGraphics">The previous graphics context for the bitmap.</param> /// <param name="glyphSize">The size of the glyph.</param> private void GetGlyphBitmap(ref Bitmap oldBitmap, ref System.Drawing.Graphics oldGraphics, RectangleF glyphSize) { if ((oldBitmap != null) && (glyphSize.Width * 2 <= oldBitmap.Width) && (glyphSize.Height <= oldBitmap.Height)) { return; } oldBitmap?.Dispose(); oldGraphics?.Dispose(); oldBitmap = new Bitmap((int)glyphSize.Width * 2, (int)glyphSize.Height, PixelFormat.Format32bppArgb); oldGraphics = System.Drawing.Graphics.FromImage(oldBitmap); oldGraphics.PageUnit = GraphicsUnit.Pixel; oldGraphics.CompositingMode = CompositingMode.SourceOver; oldGraphics.CompositingQuality = CompositingQuality.HighQuality; switch (_fontInfo.AntiAliasingMode) { case FontAntiAliasMode.AntiAlias: oldGraphics.SmoothingMode = SmoothingMode.AntiAlias; oldGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; break; default: oldGraphics.SmoothingMode = SmoothingMode.None; oldGraphics.InterpolationMode = InterpolationMode.NearestNeighbor; break; } }
private void Draw(Graphics gr) { Bitmap bitmap = new Bitmap(Width, Height); Graphics g = Graphics.FromImage(bitmap); g.FillRectangle(BlackBrush, 10, 10, 100, 250); Color c; Brush b; switch (s.Color) { case TrafficLightColor.Red: c = Color.Red; b = new SolidBrush(c); g.FillEllipse(b, 25, 25, 70, 70); break; case TrafficLightColor.Yellow: c = Color.Yellow; b = new SolidBrush(c); g.FillEllipse(b, 25, 95, 70, 70); break; case TrafficLightColor.Green: c = Color.Green; b = new SolidBrush(c); g.FillEllipse(b, 25, 165, 70, 70); break; } gr.DrawImage(bitmap, 0, 0, Width, Height); gr.Dispose(); bitmap.Dispose(); g.Dispose(); }
static Enemy() { _mdl = OBJModelParser.GetInstance().Parse("res/mdl/enemy"); _garbage = new Bitmap(1, 1); _garbageg = Graphics.FromImage(_garbage); List<Pair<string, Rect2D>> quotes = new List<Pair<string, Rect2D>>(); using (StreamReader s = new StreamReader("res/screams.txt")) { while (!s.EndOfStream) { string q = s.ReadLine(); while (q.EndsWith(@"\")) { q = q.Substring(0, q.Length - 1); q += "\n"; q += s.ReadLine(); } SizeF size = _garbageg.MeasureString(q, SystemFonts.DefaultFont); Bitmap img = new Bitmap((int)size.Width + 6, (int)size.Height + 6); Graphics g = Graphics.FromImage(img); g.FillRectangle(Brushes.White, 0, 0, img.Width, img.Height); g.DrawString(q, SystemFonts.DefaultFont, Brushes.Black, 3, 3); g.Dispose(); Pair<string, Rect2D> ins = new Pair<string, Rect2D>(); ins.First = q; const int SCALE = 30; const int SCALE2 = 2 * SCALE; ins.Second = new Rect2D(img, -(size.Width / SCALE2), -(size.Height / SCALE2), (size.Width / SCALE), (size.Height / SCALE)); quotes.Add(ins); } } _garbageg.Dispose(); _garbageg = null; //Prevent accidental use. _quotes = quotes.ToArray(); _r = new Random(); }
public override void DrawRect(System.Drawing.RectangleF dirtyRect) { // var gc = NSGraphicsContext.FromGraphicsPort( // NSGraphicsContext.CurrentContext.GraphicsPort.Handle,true); // var gc = NSGraphicsContext.CurrentContext; // // var g = new Graphics(gc.GraphicsPort); var g = new Graphics(); // NSView does not have a background color so we just use Clear to white here g.Clear(Color.White); //RectangleF ClientRectangle = this.Bounds; RectangleF ClientRectangle = dirtyRect; // Following codes draw a line from (0, 0) to (1, 1) in unit of inch: /*g.PageUnit = GraphicsUnit.Inch; Pen blackPen = new Pen(Color.Black, 1/g.DpiX); g.DrawLine(blackPen, 0, 0, 1, 1);*/ // Following code shifts the origin to the center of // client area, and then draw a line from (0,0) to (1, 1) inch: g.PageUnit = GraphicsUnit.Inch; g.TranslateTransform((ClientRectangle.Width / g.DpiX) / 2, (ClientRectangle.Height / g.DpiY) / 2); Pen greenPen = new Pen(Color.Green, 1 / g.DpiX); g.DrawLine(greenPen, 0, 0, 1, 1); g.Dispose (); }
public override void Draw(RectangleF dirtyRect) { Graphics g = new Graphics(); var ClientRectangle = new Rectangle((int)dirtyRect.X, (int)dirtyRect.Y, (int)dirtyRect.Width, (int)dirtyRect.Height); // Calculate the location and size of the drawing area // Within which we want to draw the graphics: //Rectangle ChartArea = ClientRectangle; Rectangle ChartArea = new Rectangle(50, 50, ClientRectangle.Width - 70, ClientRectangle.Height - 70); g.DrawRectangle(Pens.LightCoral, ChartArea); PlotArea = new Rectangle(ChartArea.Location, ChartArea.Size); PlotArea.Inflate(-offset, -offset); //Draw ClientRectangle and PlotArea using pen: g.DrawRectangle(Pens.Black, PlotArea); // Generate Sine and Cosine data points to plot: PointF[] pt1 = new PointF[nPoints]; PointF[] pt2 = new PointF[nPoints]; for (int i = 0; i < nPoints; i++) { pt1[i] = new PointF(i / 5.0f, (float)Math.Sin(i/5.0f)); pt2[i] = new PointF(i / 5.0f, (float)Math.Cos(i/5.0f)); } for (int i = 1; i < nPoints; i++) { g.DrawLine(Pens.Blue, Point2D(pt1[i - 1]), Point2D(pt1[i])); g.DrawLine(Pens.Red, Point2D(pt2[i - 1]), Point2D(pt2[i])); } g.Dispose(); }
private void T_Tick(object sender, EventArgs e) { this.SuspendLayout(); state = obj.GetState; int istate = 1; try { istate = Convert.ToInt32(state); state += "%"; } catch (Exception ex) {} rect.Size = new Size(this.Width - 1, this.Height - 1); bmp = new Bitmap(this.Width, this.Height); g = Graphics.FromImage(bmp); g.DrawRectangle(new Pen(Color.Black), rect); g.FillRectangle(Brushes.Blue, new Rectangle(1, 1, rect.Width - 1, rect.Height - 1)); g.FillRectangle(Brushes.White, new Rectangle(1, 1, rect.Width - 1, (int)(rect.Height-rect.Height*0.01* istate))); using (Font _normalFont = new Font("Century Gothic", 48, FontStyle.Regular, GraphicsUnit.Point)) { StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Center; g.DrawString(state, _normalFont, Brushes.Black,rect,stringFormat); } g.Dispose(); this.BackgroundImage = bmp; this.ResumeLayout(); }
public override void Draw(RectangleF rect) { Graphics g = new Graphics(); //g.Clear(Color.White); // Create a pen object: Pen aPen = new Pen(Color.Blue, 1 / g.DpiX); // Create a brush object with a transparent red color: SolidBrush aBrush = new SolidBrush(Color.Red); g.PageUnit = GraphicsUnit.Inch; g.PageScale = 2; g.RenderingOrigin = new PointF(0.5f,0.0f); // Draw a rectangle: g.DrawRectangle(aPen, .20f, .20f, 1.00f, .50f); // Draw a filled rectangle: g.FillRectangle(aBrush, .20f, .90f, 1.00f, .50f); // Draw ellipse: g.DrawEllipse(aPen, new RectangleF(.20f, 1.60f, 1.00f, .50f)); // Draw filled ellipse: g.FillEllipse(aBrush, new RectangleF(1.70f, .20f, 1.00f, .50f)); // Draw arc: g.DrawArc(aPen, new RectangleF(1.70f, .90f, 1.00f, .50f), -90, 180); // Draw filled pie pieces g.FillPie(aBrush, 1.70f, 1.60f, 1.00f, 1.00f, -90, 90); g.FillPie(Brushes.Green, 1.70f, 1.60f, 1.00f, 1.00f, -90, -90); g.Dispose(); }
private void Form1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point point = new Point(); point.X = e.X; point.Y = e.Y; ListOfPoints.Add(point); Type[] args = new Type[1]; args[0] = typeof(List<Point>); object[] par = new object[1]; par[0] = ListOfPoints; ConstructorInfo CI = SelectedType.GetConstructor(args); if (CI != null) { Gr = Form.ActiveForm.CreateGraphics(); ShapeC shape = (ShapeC)CI.Invoke(par); shape.Draw(Gr); Gr.Dispose(); } } if (e.Button == MouseButtons.Right) { ListOfPoints.Clear(); } }
public void DrawFormBackgroud(Graphics g, Rectangle r) { drawing = new Bitmap(this.Width, AnimSize, g); gg = Graphics.FromImage(drawing); Rectangle shadowRect = new Rectangle(r.X, r.Y, r.Width, 10); Rectangle gradRect = new Rectangle(r.X, r.Y + 9, r.Width, AnimSize-9); LinearGradientBrush shadow = new LinearGradientBrush(shadowRect, Color.FromArgb(30, 61, 61), Color.FromArgb(47, colorR, colorR), LinearGradientMode.Vertical); //LinearGradientBrush shadow = new LinearGradientBrush(shadowRect, Color.FromArgb(30, 61, 41), Color.FromArgb(47, colorR, 64), LinearGradientMode.Vertical); LinearGradientBrush grad = new LinearGradientBrush(gradRect, Color.FromArgb(47, 64, 94), Color.FromArgb(49, 66, 95), LinearGradientMode.Vertical); //LinearGradientBrush grad = new LinearGradientBrush(gradRect, Color.Green, Color.DarkGreen, LinearGradientMode.Vertical); ColorBlend blend = new ColorBlend(); // Set multi-color gradient blend.Positions = new[] { 0.0f, 0.35f, 0.5f, 0.65f, 0.95f,1f }; blend.Colors = new[] { Color.FromArgb(47, colorR, colorR), Color.FromArgb(64, colorR + 22, colorR + 32), Color.FromArgb(66, colorR + 20, colorR + 35), Color.FromArgb(64, colorR + 20, colorR + 32), Color.FromArgb(49, colorR, colorR + 1), SystemColors.Control }; //blend.Colors = new[] { Color.FromArgb(47, colorR, 64), Color.FromArgb(64, colorR + 32, 88), Color.FromArgb(66, colorR + 35, 90), Color.FromArgb(64, colorR + 32, 88), Color.FromArgb(49, colorR + 1, 66),SystemColors.Control }; grad.InterpolationColors = blend; Font myf = new System.Drawing.Font(this.Font.FontFamily, 16); // Draw basic gradient and shadow //gg.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gg.FillRectangle(grad, gradRect); gg.FillRectangle(shadow, shadowRect); gg.TextRenderingHint = TextRenderingHint.AntiAlias; gg.DrawString("Поиск по ресурсам сети", myf, Brushes.GhostWhite, new PointF(55, 15)); gg.DrawImage(Properties.Resources.search1.ToBitmap(), 10, 10,32,32); g.DrawImageUnscaled(drawing, 0, 0); gg.Dispose(); // Draw checkers //g.FillRectangle(checkers, r); }
public void DrawFormBackgroud(Graphics g, Rectangle r) { drawing = new Bitmap(this.Width, this.Height, g); gg = Graphics.FromImage(drawing); Rectangle shadowRect = new Rectangle(r.X, r.Y, r.Width, 10); Rectangle gradRect = new Rectangle(r.X, r.Y + 9, r.Width, 42); //LinearGradientBrush shadow = new LinearGradientBrush(shadowRect, Color.FromArgb(30, 41, 61), Color.FromArgb(47, 64, 94), LinearGradientMode.Vertical); LinearGradientBrush shadow = new LinearGradientBrush(shadowRect, Color.FromArgb(30, 61, 41), Color.FromArgb(47, colorR, 64), LinearGradientMode.Vertical); //LinearGradientBrush grad = new LinearGradientBrush(gradRect, Color.FromArgb(47, 64, 94), Color.FromArgb(49, 66, 95), LinearGradientMode.Vertical); LinearGradientBrush grad = new LinearGradientBrush(gradRect, Color.Green, Color.DarkGreen, LinearGradientMode.Vertical); ColorBlend blend = new ColorBlend(); // Set multi-color gradient blend.Positions = new[] { 0.0f, 0.35f, 0.5f, 0.65f, 1.0f }; //blend.Colors = new[] { Color.FromArgb(47, 64, 94), Color.FromArgb(64, 88, 126), Color.FromArgb(66, 90, 129), Color.FromArgb(64, 88, 126), Color.FromArgb(49, 66, 95) }; blend.Colors = new[] { Color.FromArgb(47,colorR, 64), Color.FromArgb(64, colorR+32, 88), Color.FromArgb(66, colorR+35, 90), Color.FromArgb(64, colorR+32, 88), Color.FromArgb(49, colorR+1, 66) }; grad.InterpolationColors = blend; Font myf=new System.Drawing.Font(this.Font.FontFamily,16); // Draw basic gradient and shadow //gg.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gg.FillRectangle(grad, gradRect); gg.FillRectangle(shadow, shadowRect); gg.DrawString("Добавить один ПК", myf, Brushes.GhostWhite, new PointF(55, 15)); gg.DrawImage(Properties.Resources.singleAdd1.ToBitmap(), 10, 10,32,32); g.DrawImageUnscaled(drawing, 0, 0); gg.Dispose(); // Draw checkers //g.FillRectangle(checkers, r); }
public void ProcessEMF(byte[] emf) { try { _ms = new MemoryStream(emf); _mf = new Metafile(_ms); _bm = new Bitmap(1, 1); g = Graphics.FromImage(_bm); //XScale = Width / _mf.Width; //YScale = Height/ _mf.Height; m_delegate = new Graphics.EnumerateMetafileProc(MetafileCallback); g.EnumerateMetafile(_mf, new Point(0, 0), m_delegate); } finally { if (g != null) g.Dispose(); if (_bm != null) _bm.Dispose(); if (_ms != null) { _ms.Close(); _ms.Dispose(); } } }
public void Dispose() { GC.SuppressFinalize(this); sdBuffer?.Dispose(); sdGraphics?.Dispose(); GC.Collect(); }
private void t_Tick(object sender, EventArgs e) { //graphics g = Graphics.FromImage(bmp); //clear graphics g.Clear(Color.LightSkyBlue); //draw progressbar g.FillRectangle(Brushes.CornflowerBlue, new Rectangle(0, 0, (int)(pbComplete * pbUnit), pbHEIGHT)); //draw % complete g.DrawString(pbComplete + "%", new Font("Arial", pbHEIGHT / 2), Brushes.Black, new PointF(pbWIDTH / 2 - pbHEIGHT, pbHEIGHT / 10)); //load bitmap in picturebox picboxPB picboxPB.Image = bmp; //update pbComplete //Note! //To keep things simple I am adding +1 to pbComplete every 50ms //You can change this as per your requirement :) pbComplete++; if (pbComplete > 100) { //dispose g.Dispose(); t.Stop(); } }
public override void DrawRect(System.Drawing.RectangleF dirtyRect) { Graphics g = new Graphics(); //g.Clear(Color.White); DrawObjects(g); g.Dispose(); }
// Clear Button private void button1_Click(object sender, EventArgs e) { bmp = new Bitmap(400, 400); g = Graphics.FromImage(bmp); g.Clear(Color.White); pictureBox1.Image = bmp; g.Dispose(); }
public override void Draw(RectangleF rect) { Graphics g = new Graphics(); //g.Clear(Color.LightGreen); // TODO: Fill in the UI Just lazy right now g.Dispose(); }
public Wallpaper() { s = Settings.Instance; allScreen = MultiScreenInfo.Instance; CanAddAnotherBitmap = true; try { desktop = new Bitmap(allScreen.VirtualDesktop.Width, allScreen.VirtualDesktop.Height); gDesktop = Graphics.FromImage(desktop); gDesktop.SetHighQuality(); needFullRedraw = true; try { if (allScreen.IsChanged == false) { var currentPath = GetCurrentPath(); var expectedPath = SafeFilename.Convert(s.SaveFolder, "Current Wallpaper.bmp", true); if (currentPath == expectedPath) { using (var currentDesktop = new Bitmap(currentPath)) { //not needed? if (currentDesktop.Size == allScreen.VirtualDesktop.Size) { gDesktop.DrawImageUnscaled(currentDesktop, 0, 0); needFullRedraw = false; } } } } } catch { } } catch { if (gDesktop != null) { gDesktop.Dispose(); gDesktop = null; } if (desktop != null) { desktop.Dispose(); desktop = null; } } if (desktop == null) { throw new ArgumentException(); } }
public override void Draw(RectangleF rect) { Graphics g = new Graphics(); //g.Clear(Color.White); DrawObjects(g); g.Dispose(); }
protected override void Dispose(bool disposing) { if (disposing) { g?.Dispose(); bmpSurface?.Dispose(); } base.Dispose(disposing); }
private void T_Tick(object sender, EventArgs e) { g = Graphics.FromImage(bmp); g.Clear(Color.Transparent); g.FillRectangle(new SolidBrush(Color.FromArgb(68, 10, 79)),new Rectangle(new Point(0,0),new Size(Width,y))); if(y<GetResolution.GetHeight) y += i; box.Image = bmp; g.Dispose(); }
private void DisplayValue(int value, PictureBox picBox) { point = GetPoint(value); valueImage = GetBitmap(value); valueToImageWriter = Graphics.FromImage(valueImage); valueToImageWriter.DrawString(value.ToString(), font, brush, point); picBox.Image = valueImage; valueToImageWriter.Dispose(); }
public void Draw(Graphics panelGraphics, Dictionary<Guid, DrawableNode> allNodes) { System.Drawing.Pen myPen; myPen = new System.Drawing.Pen(System.Drawing.Color.DodgerBlue, 3f); myPen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; panelGraphics.DrawLine(myPen, allNodes[TailNodeGuid].Location.X + 25, allNodes[TailNodeGuid].Location.Y + 25, allNodes[HeadNodeGuid].Location.X + 25, allNodes[HeadNodeGuid].Location.Y + 25); myPen.Dispose(); panelGraphics.Dispose(); }
/// <summary> /// Raises the <see cref="E:System.Windows.Forms.Form.FormClosing" /> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.FormClosingEventArgs" /> that contains the event data.</param> protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); _graphics?.Dispose(); _formGraphics?.Dispose(); _bitmap?.Dispose(); }
private void AnimateTimer1_Tick(object sender, EventArgs e) { g = Graphics.FromImage(bmpAnimate); g.Clear(Color.White); if ((Rect2LocationX - Rect1LocationX) <= 50 && (Rect2LocationX - Rect1LocationX) != 0) { g.FillRectangle(new System.Drawing.SolidBrush(Color.FromArgb(RedBar1.Value, GreenBar1.Value, BlueBar1.Value)), Rect1LocationX, Rect1LocationYDef, (Rect2LocationX - Rect1LocationX), 50); g.FillRectangle(new System.Drawing.SolidBrush(Color.FromArgb(RedResult, GreenResult, BlueResult)), RectTargetX, Rect1LocationYDef, 50 - (Rect2LocationX - Rect1LocationX), 50); g.FillRectangle(new System.Drawing.SolidBrush(Color.FromArgb(RedBar2.Value, GreenBar2.Value, BlueBar2.Value)), RectTargetX + (50 - (Rect2LocationX - Rect1LocationX)), Rect2LocationYDef, (Rect2LocationX - Rect1LocationX), 50); Rect1LocationX = Rect1LocationX + 10; g.Dispose(); pictureBox1.Image = bmpAnimate; } else if ((Rect2LocationX - Rect1LocationX) == 0) { g.FillRectangle(new System.Drawing.SolidBrush(Color.FromArgb(RedResult, GreenResult, BlueResult)), RectTargetX, Rect1LocationYDef, 50, 50); g.Dispose(); pictureBox1.Image = bmpAnimate; Rect1LocationX = Rect1LocationXDef; Rect2LocationX = Rect2LocationXDef; AnimateTimer1.Stop(); } else { if (Rect2LocationX == RectTargetX) { g.FillRectangle(new System.Drawing.SolidBrush(Color.FromArgb(RedBar1.Value, GreenBar1.Value, BlueBar1.Value)), Rect1LocationX, Rect1LocationYDef, 50, 50); g.FillRectangle(new System.Drawing.SolidBrush(Color.FromArgb(RedBar2.Value, GreenBar2.Value, BlueBar2.Value)), RectTargetX, Rect2LocationYDef, 50, 50); Rect1LocationX = Rect1LocationX + 10; g.Dispose(); pictureBox1.Image = bmpAnimate; } else { g.FillRectangle(new System.Drawing.SolidBrush(Color.FromArgb(RedBar1.Value, GreenBar1.Value, BlueBar1.Value)), Rect1LocationX, Rect1LocationYDef, 50, 50); //Rect1 g.FillRectangle(new System.Drawing.SolidBrush(Color.FromArgb(RedBar2.Value, GreenBar2.Value, BlueBar2.Value)), Rect2LocationX, Rect2LocationYDef, 50, 50); //Rect2 Rect1LocationX = Rect1LocationX + 10; Rect2LocationX = Rect2LocationX + 10; g.Dispose(); pictureBox1.Image = bmpAnimate; } } }
private void T_Tick(object sender, EventArgs e) { g = Graphics.FromImage(bmp); g.Clear(Color.Transparent); y += dy; g.FillRectangle(new SolidBrush(_color), new Rectangle(this.Location.X, this.Location.Y, this.Width, (int)y)); this.Image = bmp; g.Dispose(); if (y > this.Height) t.Stop(); }
private void T_Tick(object sender, EventArgs e) { g = Graphics.FromImage(bmp); g.FillRectangle(new SolidBrush(Color.FromArgb(68,10,79)),new Rectangle(new Point(0,0),new Size(Width,_height))); g.Clear(Color.Transparent); _height += i; this.Image = bmp; g.Dispose(); if (_height > 200) t.Stop(); }
public MainForm() { InitializeComponent(); snapshotDrawArea = new Bitmap(panelDrawArea.ClientRectangle.Width, panelDrawArea.ClientRectangle.Height); //Creating layer for drawing g = Graphics.FromImage(snapshotDrawArea); //fill layer with white color for normal saving process g.FillRectangle(Brushes.White, 0, 0, panelDrawArea.ClientRectangle.Width, panelDrawArea.ClientRectangle.Height); g.Dispose(); }
public void Reset(Bitmap bitmap) { if (bitmap == default) { return; } Bitmap = bitmap; _graphics?.Dispose(); _graphics = GetBitmapGraphics(bitmap); }
public override void Draw(RectangleF rect) { var ctx = new Graphics (UIGraphics.GetCurrentContext ()); var red = new SolidBrush (Color.Red); ctx.DrawLine (new Pen (red), new PointF (1, 1), new PointF (100, 100)); ctx.Dispose (); }
private void button1_Click(object sender, EventArgs e) { Grafika = Graphics.FromImage(Rastr); DrawAxes(); DrawHorizLines(); DrawVertLines(); DrawEpur(); pictureBox1.Image = Rastr; Grafika.Dispose(); }
public override void Draw(RectangleF rect) { Graphics g = new Graphics(); //g.Clear(Color.White); g.SmoothingMode = SmoothingMode.AntiAlias; // Create a pen object: Pen aPen = new Pen(Color.Blue, 2); // Create a brush object with a transparent red color: SolidBrush aBrush = new SolidBrush(Color.Red); HatchBrush hBrush = new HatchBrush(HatchStyle.Shingle, Color.Blue, Color.LightCoral); HatchBrush hBrush2 = new HatchBrush(HatchStyle.Cross, Color.Blue, Color.LightCoral); HatchBrush hBrush3 = new HatchBrush(HatchStyle.BackwardDiagonal, Color.Blue, Color.LightCoral); HatchBrush hBrush4 = new HatchBrush(HatchStyle.Sphere, Color.Blue, Color.LightCoral); // Draw a rectangle: g.DrawRectangle(aPen, 20, 20, 100, 50); // Draw a filled rectangle: g.FillRectangle(hBrush, 20, 90, 100, 50); // Draw ellipse: g.DrawEllipse(aPen, new Rectangle(20, 160, 100, 50)); // Draw filled ellipse: g.FillEllipse(hBrush2, new Rectangle(170, 20, 100, 50)); // Draw arc: g.DrawArc(aPen, new Rectangle(170, 90, 100, 50), -90, 180); // Draw filled pie pieces g.FillPie(aBrush, new Rectangle(170, 160, 100, 100), -90, 90); g.FillPie(hBrush4, new Rectangle(170, 160, 100, 100), -90, -90); // Create pens. Pen redPen = new Pen(Color.Red, 3); Pen greenPen = new Pen(Color.Green, 3); greenPen.DashStyle = DashStyle.DashDotDot; SolidBrush transparentBrush = new SolidBrush(Color.FromArgb(150, Color.Wheat)); // define point array to draw a curve: Point point1 = new Point(300, 250); Point point2 = new Point(350, 125); Point point3 = new Point(400, 110); Point point4 = new Point(450, 210); Point point5 = new Point(500, 300); Point[] curvePoints ={ point1, point2, point3, point4, point5}; // Draw lines between original points to screen. g.DrawLines(redPen, curvePoints); // Fill Curve g.FillClosedCurve(transparentBrush, curvePoints); // Draw closed curve to screen. g.DrawClosedCurve(greenPen, curvePoints); g.Dispose(); }
public void InitializePictureBox() { Debug.WriteLine("BaseActivator - Initialize"); Debug.WriteLine(string.Format("Display Width: {0}, Height: {1}", m_pbDisplay.Width, m_pbDisplay.Height)); Bitmap bmp = new Bitmap(m_pbDisplay.Width, m_pbDisplay.Height); m_gp = Graphics.FromImage(bmp); m_gp.FillRectangle(Brushes.White, 0, 0, m_pbDisplay.Width, m_pbDisplay.Height); m_gp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; m_pbDisplay.Image = bmp; m_gp.Dispose(); }
public override void DrawRect(System.Drawing.RectangleF dirtyRect) { Graphics g = new Graphics(); g.Clear(Color.LightGreen); Width = dirtyRect.Width; DrawFlag(g, 20, 20, this.Width - 50); g.Dispose(); }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { foreach (SolidBrush brush in _brushes) { brush.Dispose(); } Surface?.Dispose(); _graphics?.Dispose(); GC.SuppressFinalize(this); }
public override void Draw(RectangleF rect) { Graphics g = new Graphics(); //g.Clear(Color.LightGreen); Width = rect.Width; DrawFlag(g, 20, 50, this.Width - 50); g.Dispose(); }
protected override void Resize(string text) { base.Resize(text); Bitmap currentSurface = bmpSurface; System.Drawing.Graphics currentGraphics = g; bmpSurface = new Bitmap(texture.Width, texture.Height); g = System.Drawing.Graphics.FromImage(bmpSurface); currentGraphics?.Dispose(); currentSurface?.Dispose(); g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit; }
private bool BitBlt(Surface surface, GDI.Bitmap bmp) { bool success; IntPtr hdcDest = IntPtr.Zero; GDI.Graphics graphDest = null; IntPtr hdcSrc = surface.GetDC(); try { graphDest = System.Drawing.Graphics.FromImage(bmp); hdcDest = graphDest.GetHdc(); GDI.Size destSize = bmp.Size; int nXDest = 0; int nYDest = 0; int nWidth = destSize.Width; int nHeight = destSize.Height; int nXSrc = SrcRect.Left; int nYSrc = SrcRect.Top; int nWidthSrc = SrcRect.Width; int nHeightSrc = SrcRect.Height; var dwRop = TernaryRasterOperations.SRCCOPY; success = Gdi32.BitBlt(hdcDest, nXDest, nYDest, nWidth, nHeight, hdcSrc, nXSrc, nYSrc, dwRop); } finally { graphDest?.ReleaseHdc(hdcDest); graphDest?.Dispose(); graphDest = null; surface.ReleaseDC(hdcSrc); } return(success); }
/// <summary> /// 图片等比缩放 /// </summary> /// <remarks>吴剑 2012-08-08</remarks> /// <param name="fromFile">原图Stream对象</param> /// <param name="savePath">缩略图存放地址</param> /// <param name="targetWidth">指定的最大宽度</param> /// <param name="targetHeight">指定的最大高度</param> /// <param name="watermarkText">水印文字(为""表示不使用水印)</param> /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param> public static void ZoomAuto(System.IO.Stream fromFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText, string watermarkImage) { //创建目录 string dir = Path.GetDirectoryName(savePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= targetWidth && initImage.Height <= targetHeight) { //文字水印 if (watermarkText != "") { using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage)) { System.Drawing.Font fontWater = new Font("黑体", 10); System.Drawing.Brush brushWater = new SolidBrush(Color.White); gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10); gWater.Dispose(); } } //透明图片水印 if (watermarkImage != "") { if (File.Exists(watermarkImage)) { //获取水印图片 using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage)) { //水印绘制条件:原始图片宽高均大于或等于水印图片 if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height) { Graphics gWater = Graphics.FromImage(initImage); //透明属性 ImageAttributes imgAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5 new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes); gWater.Dispose(); } wrImage.Dispose(); } } } //保存 initImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //缩略图宽、高计算 double newWidth = initImage.Width; double newHeight = initImage.Height; //宽大于高或宽等于高(横图或正方) if (initImage.Width > initImage.Height || initImage.Width == initImage.Height) { //如果宽大于模版 if (initImage.Width > targetWidth) { //宽按模版,高按比例缩放 newWidth = targetWidth; newHeight = initImage.Height * (targetWidth / initImage.Width); } } //高大于宽(竖图) else { //如果高大于模版 if (initImage.Height > targetHeight) { //高按模版,宽按比例缩放 newHeight = targetHeight; newWidth = initImage.Width * (targetHeight / initImage.Height); } } //生成新图 //新建一个bmp图片 System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight); //新建一个画板 System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage); //设置质量 newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //置背景色 newG.Clear(Color.White); //画图 newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); //文字水印 if (watermarkText != "") { using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(newImage)) { System.Drawing.Font fontWater = new Font("宋体", 10); System.Drawing.Brush brushWater = new SolidBrush(Color.White); gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10); gWater.Dispose(); } } //透明图片水印 if (watermarkImage != "") { if (File.Exists(watermarkImage)) { //获取水印图片 using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage)) { //水印绘制条件:原始图片宽高均大于或等于水印图片 if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height) { Graphics gWater = Graphics.FromImage(newImage); //透明属性 ImageAttributes imgAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5 new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes); gWater.Dispose(); } wrImage.Dispose(); } } } //保存缩略图 newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg); //释放资源 newG.Dispose(); newImage.Dispose(); initImage.Dispose(); } }
/// <summary> /// 指定长宽裁剪 /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸 /// </summary> /// <param name="fromFile">原图Stream对象</param> /// <param name="fileSaveUrl">保存路径</param> /// <param name="maxWidth">最大宽(单位:px)</param> /// <param name="maxHeight">最大高(单位:px)</param> /// <param name="quality">质量(范围0-100)</param> public static void CutForCustom(System.IO.Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality) { //从文件获取原始图片,并使用流中嵌入的颜色管理信息 System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= maxWidth && initImage.Height <= maxHeight) { initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //模版的宽高比例 double templateRate = (double)maxWidth / maxHeight; //原图片的宽高比例 double initRate = (double)initImage.Width / initImage.Height; //原图与模版比例相等,直接缩放 if (templateRate == initRate) { //按模版大小生成最终图片 System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } //原图与模版比例不等,裁剪后缩放 else { //裁剪对象 System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; //定位 Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位 Rectangle toR = new Rectangle(0, 0, 0, 0); //目标定位 //宽为标准进行裁剪 if (templateRate > initRate) { //裁剪对象实例化 pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)System.Math.Floor(initImage.Width / templateRate)); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //裁剪源定位 fromR.X = 0; fromR.Y = (int)System.Math.Floor((initImage.Height - initImage.Width / templateRate) / 2); fromR.Width = initImage.Width; fromR.Height = (int)System.Math.Floor(initImage.Width / templateRate); //裁剪目标定位 toR.X = 0; toR.Y = 0; toR.Width = initImage.Width; toR.Height = (int)System.Math.Floor(initImage.Width / templateRate); } //高为标准进行裁剪 else { pickedImage = new System.Drawing.Bitmap((int)System.Math.Floor(initImage.Height * templateRate), initImage.Height); pickedG = System.Drawing.Graphics.FromImage(pickedImage); fromR.X = (int)System.Math.Floor((initImage.Width - initImage.Height * templateRate) / 2); fromR.Y = 0; fromR.Width = (int)System.Math.Floor(initImage.Height * templateRate); fromR.Height = initImage.Height; toR.X = 0; toR.Y = 0; toR.Width = (int)System.Math.Floor(initImage.Height * templateRate); toR.Height = initImage.Height; } //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //裁剪 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //按模版大小生成最终图片 System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel); //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo i in icis) { if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif") { ici = i; } } EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); //保存缩略图 templateImage.Save(fileSaveUrl, ici, ep); //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); //释放资源 templateG.Dispose(); templateImage.Dispose(); pickedG.Dispose(); pickedImage.Dispose(); } } //释放资源 initImage.Dispose(); }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(相对路径)</param> /// <param name="thumbnailPath">缩略图目标路径(相对路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> /// <param name="deloriginalImage">是否删除源图</param> public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, ImgCreateWay imgCreateWay, bool deleteOriginalImage) { string originalImagePath_asb = HttpContext.Current.Server.MapPath(originalImagePath); string thumbnailPath_asb = HttpContext.Current.Server.MapPath(thumbnailPath); if (!File.Exists(originalImagePath_asb)) { // throw new CySoftException("源文件" + originalImagePath + "不存在或没有足够的访问权限!"); return; } System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath_asb); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (imgCreateWay) { case ImgCreateWay.HW: //指定高宽缩放(可能变形) break; case ImgCreateWay.W: //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case ImgCreateWay.H: //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case ImgCreateWay.Cut: //指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(System.Drawing.Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { //以jpg格式保存缩略图 bitmap.Save(thumbnailPath_asb, System.Drawing.Imaging.ImageFormat.Jpeg); // 删除源图 if (deleteOriginalImage) { File.Delete(originalImagePath_asb); } } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } }
public override CompiledSpriteFont Process(SpriteFontContent input, string filename, ContentProcessorContext context) { string fontFile; if (!FontConfig.Instance.GetFontFile(input.FontName, input.Size, input.Style, out fontFile)) { context.RaiseBuildMessage(filename, $"'{input.FontName}' was not found, using fallback font", BuildMessageEventArgs.BuildMessageType.Warning); } if (fontFile == null) { context.RaiseBuildMessage(filename, $"'{input.FontName}' was not found, no fallback font provided", BuildMessageEventArgs.BuildMessageType.Error); return(null); } //Initialization SharpFont.Library lib = new SharpFont.Library(); var face = lib.NewFace(fontFile, 0); Bitmap dummyBitmap = new Bitmap(1, 1); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dummyBitmap); face.SetCharSize(new Fixed26Dot6(0), new Fixed26Dot6(input.Size), (uint)g.DpiX, (uint)g.DpiY); CompiledSpriteFont compiled = new CompiledSpriteFont(); compiled.Spacing = input.Spacing; compiled.DefaultCharacter = input.DefaultCharacter; var glyphs = new Dictionary <uint, GlyphSlot>(); var characters = input.CharacterRegions.SelectMany( r => r.GetChararcters().Select(c => Tuple.Create(c, face.GetCharIndex(c)))).Where(x => x.Item2 != 0).ToList(); var bitmaps = new List <Tuple <char, FTBitmap, int, GlyphMetrics> >(); compiled.LineSpacing = face.Size.Metrics.Height.Value >> 6; compiled.BaseLine = face.Size.Metrics.Ascender.Value >> 6; //Loading Glyphs, Calculate Kernings and Create Bitmaps int totalWidth = 0, maxWidth = 0, maxHeight = 0; foreach (var l in characters) { var character = l.Item1; var glyphIndex = l.Item2; //Load Glyphs face.LoadGlyph(glyphIndex, LoadFlags.Color, LoadTarget.Normal); var glyph = face.Glyph; glyph.Tag = character; glyphs.Add(character, glyph); //Calculate Kernings if (input.UseKerning) { foreach (var r in characters) { var kerning = face.GetKerning(l.Item2, r.Item2, KerningMode.Default); if (kerning == default(FTVector26Dot6)) { continue; } compiled.kernings[(int)l.Item1 << 16 | (int)r.Item1] = kerning.X.Value >> 6; } } //Create bitmaps glyph.OwnBitmap(); var glyphActual = glyph.GetGlyph(); glyphActual.ToBitmap(RenderMode.Normal, default(FTVector26Dot6), false); var bmg = glyphActual.ToBitmapGlyph(); if (bmg.Bitmap.Width == 0 || bmg.Bitmap.Rows == 0) { totalWidth += 2 + 1; maxWidth = Math.Max(maxWidth, 1 + 2); maxHeight = Math.Max(maxHeight, 1 + 2); bitmaps.Add(Tuple.Create(character, (FTBitmap)null, glyph.Advance.X.Value >> 6, glyph.Metrics)); } else { var bmp = bmg.Bitmap; totalWidth += 2 + bmp.Width; maxWidth = Math.Max(maxWidth, bmp.Width + 2);//TODO: divide by 3? maxHeight = Math.Max(maxHeight, bmp.Rows + 2); bitmaps.Add(Tuple.Create(character, bmp, glyph.Advance.X.Value >> 6, glyph.Metrics)); } } g.Dispose(); dummyBitmap.Dispose(); int cellCount = (int)Math.Ceiling(Math.Sqrt(bitmaps.Count)); var target = new Bitmap(cellCount * maxWidth, cellCount * maxHeight); var targetRectangle = new Rectangle(0, 0, target.Width, target.Height); var targetData = target.LockBits(new System.Drawing.Rectangle(0, 0, target.Width, target.Height), ImageLockMode.WriteOnly, target.PixelFormat); int offsetX = 0, offsetY = 0; //Create Glyph Atlas foreach (var bmpKvp in bitmaps) { var bmp = bmpKvp.Item2; var character = bmpKvp.Item1; if (bmp == null) { compiled.characterMap.Add(character, new FontCharacter(character, targetRectangle, new Rectangle(offsetX, offsetY, 1, 1), new Vector2(bmpKvp.Item4.HorizontalBearingX.Value >> 6, compiled.BaseLine - (bmpKvp.Item4.HorizontalBearingY.Value >> 6)), bmpKvp.Item3)); if (offsetX++ > target.Width) { offsetY += maxHeight; offsetX = 0; } continue; } int width = bmp.Width; int height = bmp.Rows; if (offsetX + width > target.Width) { offsetY += maxHeight; offsetX = 0; } //TODO divide width by 3? compiled.characterMap.Add(character, new FontCharacter(character, targetRectangle, new Rectangle(offsetX, offsetY, width, height), new Vector2(bmpKvp.Item4.HorizontalBearingX.Value >> 6, compiled.BaseLine - (bmpKvp.Item4.HorizontalBearingY.Value >> 6)), bmpKvp.Item3)); unsafe { switch (bmp.PixelMode) { case PixelMode.Mono: CopyFTBitmapToAtlas_Mono((uint *)targetData.Scan0 + offsetX + offsetY * target.Width, offsetX, offsetY, target.Width, bmp, width, height);//TODO: divide width by 3? break; case PixelMode.Gray: CopyFTBitmapToAtlas_Gray((uint *)targetData.Scan0 + offsetX + offsetY * target.Width, offsetX, offsetY, target.Width, bmp, width, height);//TODO: divide width by 3? break; case PixelMode.Lcd: CopyFTBitmapToAtlas_LcdBGR((uint *)targetData.Scan0 + offsetX + offsetY * target.Width, offsetX, offsetY, target.Width, bmp, width, height);//TODO: divide width by 3? break; case PixelMode.Bgra: CopyFTBitmapToAtlas_BGRA((uint *)targetData.Scan0 + offsetX + offsetY * target.Width, offsetX, offsetY, target.Width, bmp, width, height);//TODO: divide width by 3? break; default: throw new NotImplementedException("Pixel Mode not supported"); } } offsetX += width;//TODO divide by 3? bmp.Dispose(); } compiled.texture = new TextureContent(context.GraphicsDevice, false, 1, targetData.Scan0, target.Width, target.Height, TextureContentFormat.Png, TextureContentFormat.Png); compiled.Spacing = input.Spacing; compiled.DefaultCharacter = input.DefaultCharacter; target.UnlockBits(targetData); //Saving files //target.Save("test.png",ImageFormat.Png); target.Dispose(); //System.Diagnostics.Process.Start("test.png"); //TODO: Remove later return(compiled); }
/// <summary> /// 水印图片 /// 【如果图片需要缩略,请使用skeletonize.Resizepic()方法对图片进行缩略】 /// 返回图片虚拟路径,和一个警告信息,可根据此信息获取图片合成信息 /// </summary> /// <param name="picpath">需要水印的图片路径</param> /// <param name="waterspath">水印图片(Image)</param> /// <param name="watermodel">水印模式</param> /// <param name="spath">文件保存路径,带文件名</param> /// <param name="imgtype">保存文件类型</param> /// <param name="filecache">原文件处理方式</param> /// <param name="warning">处理警告信息</param> /// <returns>错误,返回错误信息;成功,返回图片路径</returns> public static string makewatermark(string picpath, System.Drawing.Image water, WaterType watermodel, string spath, ImageType imgtype, FileCache filecache, out string warning, int trans = 100) { #region //反馈信息 System.Text.StringBuilder checkmessage = new System.Text.StringBuilder(); //检测源文件 string _sourceimg_common_mappath = ""; bool checkfile = false; checkfile = FileExistMapPath(picpath, FileCheckModel.C, out _sourceimg_common_mappath); System.Drawing.Image _sourceimg_common = null; if (checkfile == true) { //从指定源文件,创建image对象 _sourceimg_common = System.Drawing.Image.FromFile(_sourceimg_common_mappath); } else { checkmessage.Append("error:找不到需要的水印图片!" + picpath + ";"); } #endregion #region if (string.IsNullOrEmpty(checkmessage.ToString())) { //源图宽、高 int _sourceimg_common_width = _sourceimg_common.Width; int _sourceimg_common_height = _sourceimg_common.Height; //水印图片宽、高 int _sourceimg_water_width = water.Width; int _sourceimg_water_height = water.Height; #region 水印坐标 //水印坐标 int _sourceimg_water_point_x = 0; int _sourceimg_water_point_y = 0; switch (watermodel) { case WaterType.Center: _sourceimg_water_point_x = (_sourceimg_common_width - _sourceimg_water_width) / 2; _sourceimg_water_point_y = (_sourceimg_common_height - _sourceimg_water_height) / 2; ; break; case WaterType.CenterDown: _sourceimg_water_point_x = (_sourceimg_common_width - _sourceimg_water_width) / 2; _sourceimg_water_point_y = _sourceimg_common_height - _sourceimg_water_height; ; break; case WaterType.CenterUp: _sourceimg_water_point_x = (_sourceimg_common_width - _sourceimg_water_width) / 2; _sourceimg_water_point_y = 0; ; break; case WaterType.LeftDown: _sourceimg_water_point_x = 0; _sourceimg_water_point_y = _sourceimg_common_height - _sourceimg_water_height; ; break; case WaterType.LeftUp: ; break; case WaterType.Random: Random r = new Random(); int x_random = r.Next(0, _sourceimg_common_width); int y_random = r.Next(0, _sourceimg_common_height); _sourceimg_water_point_x = x_random > (_sourceimg_common_width - _sourceimg_water_width) ? _sourceimg_common_width - _sourceimg_water_width : x_random; _sourceimg_water_point_y = y_random > (_sourceimg_common_height - _sourceimg_water_height) ? _sourceimg_common_height - _sourceimg_water_height : y_random; ; break; case WaterType.RightDown: _sourceimg_water_point_x = _sourceimg_common_width - _sourceimg_water_width; _sourceimg_water_point_y = _sourceimg_common_height - _sourceimg_water_height; ; break; case WaterType.RightUp: _sourceimg_water_point_x = _sourceimg_common_width - _sourceimg_water_width; _sourceimg_water_point_y = 0; ; break; } #endregion //从源图创建画板 System.Drawing.Graphics _g_common = Graphics.FromImage(_sourceimg_common); //设置画笔 _g_common.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; _g_common.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; _g_common.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; #region 设置透明 int ap = trans; if (ap > 100 || ap < 0) { ap = 100; } float alpha = (float)ap / (float)100; //包含有关在呈现时如何操作位图和图元文件颜色的信息。 ImageAttributes imageAttributes = new ImageAttributes(); //Colormap: 定义转换颜色的映射 ColorMap colorMap = new ColorMap(); //我的水印图被定义成拥有绿色背景色的图片被替换成透明 colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, // red红色 new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, //green绿色 new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, //blue蓝色 new float[] { 0.0f, 0.0f, 0.0f, alpha, 0.0f }, //透明度 new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; // // ColorMatrix:定义包含 RGBA 空间坐标的 5 x 5 矩阵。 // ImageAttributes 类的若干方法通过使用颜色矩阵调整图像颜色。 ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); #endregion //绘制水印图片 // g.DrawImage(copyImage, new Rectangle(postx, posty, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel, imageAttributes); //new Rectangle(0, 0, _sourceimg_water_width, _sourceimg_water_height) _g_common.DrawImage(water, new Rectangle(_sourceimg_water_point_x, _sourceimg_water_point_y, _sourceimg_water_width, _sourceimg_water_height), 0, 0, _sourceimg_water_width, _sourceimg_water_height, GraphicsUnit.Pixel, imageAttributes); //保存图片 string _spath_common_mappath = ""; //全局文件名 //获取图片类型的hashcode值,生成图片后缀名 //int extro = imgtype.GetHashCode(); //string extend = extro == 0 ? ".jpg" : (extro == 1 ? ".gif" : (extro == 2 ? ".png" : ".jpg")); //spath = spath + Guid.NewGuid().ToString() + extend; FileExistMapPath(spath, FileCheckModel.M, out _spath_common_mappath); switch (imgtype) { case ImageType.JPEG: _sourceimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Jpeg); break; case ImageType.GIF: _sourceimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Gif); break; case ImageType.PNG: _sourceimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Png); break; } //释放 _sourceimg_common.Dispose(); water.Dispose(); _g_common.Dispose(); //处理原文件 int filecachecode = filecache.GetHashCode(); //删除原文件 if (filecachecode == 1) { System.IO.File.Delete(_sourceimg_common_mappath); } warning = ""; return(spath); } #endregion //释放 _sourceimg_common.Dispose(); water.Dispose(); warning = checkmessage.ToString().TrimEnd(';'); return(""); }
public void Dispose() { container?.Dispose(); }
/// <summary> /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸 /// </summary> /// <param name="initImage">原始图片</param> /// <param name="fileSaveUrl">要保存的路径</param> /// <param name="maxWidth">最大宽度px</param> /// <param name="maxHeight">最大高度px</param> /// <param name="quality">图片质量(范围0-100)</param> public static void CutForCustom(System.Drawing.Image initImage, string fileSaveUrl, int maxWidth, int maxHeight, int quality, float dpi = 96) { //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= maxWidth && initImage.Height <= maxHeight) { initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //模版的宽高比例 double templateRate = (double)maxWidth / maxHeight; //原图片的宽高比例 double initRate = (double)initImage.Width / initImage.Height; Bitmap templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight); //按模版大小生成最终图片 templateImage.SetResolution(dpi, dpi); //原图与模版比例相等,直接缩放 if (templateRate == initRate) { System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } //原图与模版比例不等,裁剪后缩放 else { //裁剪对象 System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; //定位 Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位 Rectangle toR = new Rectangle(0, 0, 0, 0); //目标定位 //宽为标准进行裁剪 if (templateRate > initRate) { //裁剪对象实例化 pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)System.Math.Floor(initImage.Width / templateRate)); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //裁剪源定位 fromR.X = 0; fromR.Y = (int)System.Math.Floor((initImage.Height - initImage.Width / templateRate) / 2); fromR.Width = initImage.Width; fromR.Height = (int)System.Math.Floor(initImage.Width / templateRate); //裁剪目标定位 toR.X = 0; toR.Y = 0; toR.Width = initImage.Width; toR.Height = (int)System.Math.Floor(initImage.Width / templateRate); } //高为标准进行裁剪 else { pickedImage = new System.Drawing.Bitmap((int)System.Math.Floor(initImage.Height * templateRate), initImage.Height); pickedG = System.Drawing.Graphics.FromImage(pickedImage); fromR.X = (int)System.Math.Floor((initImage.Width - initImage.Height * templateRate) / 2); fromR.Y = 0; fromR.Width = (int)System.Math.Floor(initImage.Height * templateRate); fromR.Height = initImage.Height; toR.X = 0; toR.Y = 0; toR.Width = (int)System.Math.Floor(initImage.Height * templateRate); toR.Height = initImage.Height; } //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //裁剪 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel); ////保存缩略图 //templateImage.Save(fileSaveUrl, ici, ep); EncoderParameters paras = new EncoderParameters(1); paras.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); templateImage.Save(fileSaveUrl, GetEncoderInfo("image/jpeg"), paras); //释放资源 templateG.Dispose(); templateImage.Dispose(); pickedG.Dispose(); pickedImage.Dispose(); } } }
/// <summary> /// /// </summary> /// <param name="Width"></param> /// <param name="Height"></param> /// <returns></returns> public Image GetSelectImage1(int Width, int Height) { Image initImage = this.pictureBox1.Image; //Image initImage = Bi; //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= Width && initImage.Height <= Height) { //initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); return(initImage); } else { //原始图片的宽、高 int initWidth = initImage.Width; int initHeight = initImage.Height; //非正方型先裁剪为正方型 if (initWidth != initHeight) { //截图对象 System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; //宽大于高的横图 if (initWidth > initHeight) { //对象实例化 pickedImage = new System.Drawing.Bitmap(initHeight, initHeight); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //定位 Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight); Rectangle toR = new Rectangle(0, 0, initHeight, initHeight); //画图 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //重置宽 initWidth = initHeight; } //高大于宽的竖图 else { //对象实例化 pickedImage = new System.Drawing.Bitmap(initWidth, initWidth); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //定位 Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth); Rectangle toR = new Rectangle(0, 0, initWidth, initWidth); //画图 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //重置高 initHeight = initWidth; } initImage = (System.Drawing.Image)pickedImage.Clone(); //释放截图资源 pickedG.Dispose(); pickedImage.Dispose(); } return(initImage); } }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalimagepath">源图路径(物理路径)</param> /// <param name="thumbnailpath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> public static void MakeThumbNail(string originalimagepath, string thumbnailpath, int width, int height, string mode) { System.Drawing.Image originalimage = System.Drawing.Image.FromFile(originalimagepath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalimage.Width; int oh = originalimage.Height; switch (mode) { case "hw": //指定高宽缩放(可能变形) break; case "w": //指定宽,高按比例 toheight = originalimage.Height * width / originalimage.Width; break; case "h": //指定高,宽按比例 towidth = originalimage.Width * height / originalimage.Height; break; case "cut": //指定高宽裁减(不变形) if ((double)originalimage.Width / (double)originalimage.Height > (double)towidth / (double)toheight) { oh = originalimage.Height; ow = originalimage.Height * towidth / toheight; y = 0; x = (originalimage.Width - ow) / 2; } else { ow = originalimage.Width; oh = originalimage.Width * height / towidth; x = 0; y = (originalimage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(System.Drawing.Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalimage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { //以jpg格式保存缩略图 bitmap.Save(thumbnailpath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { originalimage.Dispose(); bitmap.Dispose(); g.Dispose(); } }
private void SaveThumbnailCompress(string orginalname, string folder, bool isserverimage) { // IMAGE Compression string ext = Path.GetExtension(orginalname); ImageCodecInfo jgpEncoder; switch (ext.ToUpper()) { case ".JPEG": jgpEncoder = GetEncoder(ImageFormat.Jpeg); break; case ".JPG": jgpEncoder = GetEncoder(ImageFormat.Jpeg); break; case ".PNG": jgpEncoder = GetEncoder(ImageFormat.Png); break; default: jgpEncoder = GetEncoder(ImageFormat.Jpeg); break; } System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 90L); myEncoderParameters.Param[0] = myEncoderParameter; // END COMPRESSION string imgpath = folder + orginalname; string albumPath = folder; //TN IMAGE START if (isserverimage) { imgpath = folder + orginalname; //albumPath = GetNewImagePathForSave(); } int iwidth = System.Drawing.Image.FromFile(imgpath).Width; int iheight = System.Drawing.Image.FromFile(imgpath).Height; int twidth = 300; int theight = 300; if (iwidth < twidth) { twidth = iwidth; } if (iheight < theight) { theight = iheight; } if (iheight > iwidth) { double xx = (iwidth * theight) / iheight; twidth = int.Parse(xx.ToString()); } else { double xx = (iheight * twidth) / iwidth; theight = int.Parse(xx.ToString()); } string uriName = System.IO.Path.GetFileName(imgpath); string fnameTN = "TN_" + orginalname; Bitmap SourceBitmap = null; // create image object System.Drawing.Image thmimage = System.Drawing.Image.FromFile(imgpath); // new code for smooth thumbnail try { //new code for thumbnail SourceBitmap = new Bitmap(twidth, theight); //new code for smooth image System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(SourceBitmap); gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, twidth, theight); gr.DrawImage(thmimage, rectDestination, 0, 0, iwidth, iheight, GraphicsUnit.Pixel); string filename = albumPath + fnameTN; SourceBitmap.Save(filename, jgpEncoder, myEncoderParameters); SourceBitmap.Dispose(); thmimage.Dispose(); gr.Dispose(); SourceBitmap = null; thmimage = null; gr = null; } catch (Exception ex) { CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Admin, "", ex); } finally { } //change here on 25 jan ---- fr displaying thumbnails on home page right corner [top stories] // TN_TN IMAGE START try { /*--------------------------------------------------------*/ /*int jheight=105; * int jwidth=148;*/ int jheight = 95; int jwidth = 128; if (iwidth < jwidth) { jwidth = iwidth; } if (iheight < jheight) { jheight = iheight; } if (iheight > iwidth) { double xx = (iwidth * jheight) / iheight; jwidth = int.Parse(xx.ToString()); } else { double xx = (iheight * jwidth) / iwidth; jheight = int.Parse(xx.ToString()); } Bitmap SourceBitmap1 = null; // create image object System.Drawing.Image thmcomimage = System.Drawing.Image.FromFile(imgpath); /*******************************************************************/ try { //new code for smooth image SourceBitmap1 = new Bitmap(jwidth, jheight); System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(SourceBitmap1); gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(0, 0, jwidth, jheight); gr.DrawImage(thmcomimage, rectDestination, 0, 0, iwidth, iheight, GraphicsUnit.Pixel); //pass destination of file string compfilename = albumPath + "TN_" + fnameTN; SourceBitmap1.Save(compfilename, jgpEncoder, myEncoderParameters); SourceBitmap1.Dispose(); thmcomimage.Dispose(); gr.Dispose(); SourceBitmap1 = null; thmcomimage = null; gr = null; } catch (Exception ex) { CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Admin, "", ex); } finally { } } catch (Exception ex) { CommonLib.ExceptionHandler.WriteLog(CommonLib.Sections.Admin, "", ex); } }
/// <summary> /// 按照比例裁剪方形 /// </summary> public static void CutSquareScale(Stream sourcefile, string savefilepath, double cutwidthscale, double cutheightscale = 0, int quality = 100) { //正方形裁剪 if (cutheightscale == 0) { cutheightscale = cutwidthscale; } //创建目录 —— 保存文件 string dir = Path.GetDirectoryName(savefilepath); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromStream(sourcefile, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= cutwidthscale && initImage.Height <= cutheightscale) { initImage.Save(savefilepath, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //原始图片的宽、高 int initWidth = initImage.Width; int initHeight = initImage.Height; //目标图的宽高比例 double templateRate = (double)cutwidthscale / cutheightscale; //原图片的宽高比例 double initRate = (double)initImage.Width / initImage.Height; //截图对象 System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; //定位 Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位 Rectangle toR = new Rectangle(0, 0, 0, 0); //目标定位 //宽为标准进行裁剪 if (templateRate > initRate) { //对象实例化 pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)Math.Floor(initImage.Width / templateRate)); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //定位 fromR = new Rectangle(0, (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2), initImage.Width, (int)Math.Floor(initImage.Width / templateRate)); toR = new Rectangle(0, 0, initImage.Width, (int)Math.Floor(initImage.Width / templateRate)); //重置宽 // initWidth = initHeight; } //高为标准进行裁剪 else { //对象实例化 pickedImage = new System.Drawing.Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //定位 fromR = new Rectangle((int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2), 0, (int)Math.Floor(initImage.Height * templateRate), initImage.Height); toR = new Rectangle(0, 0, (int)Math.Floor(initImage.Height * templateRate), initImage.Height); //重置高 // initHeight = initWidth; } //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //画图——裁剪 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //将截图对象赋给原图 initImage = (System.Drawing.Image)pickedImage.Clone(); //释放截图资源 pickedG.Dispose(); pickedImage.Dispose(); ////缩略图对象 //System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side); //System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage); ////设置质量 //resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; ////用指定背景色清空画布 //resultG.Clear(Color.White); ////绘制缩略图 //resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel); //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo i in icis) { if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif") { ici = i; } } EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); //保存裁剪后的图 initImage.Save(savefilepath, ici, ep); //释放关键质量控制所用资源 ep.Dispose(); //释放缩略图资源 //resultG.Dispose(); //resultImage.Dispose(); //释放原始图片资源 initImage.Dispose(); } }
/// <summary> /// 添加水印 /// </summary> /// <param name="sourcefile"></param> /// <param name="savefilepath"></param> /// <param name="watermarkText"></param> /// <param name="watermarkImagepath"></param> public static void AddWatermark(Stream sourcefile, string savefilepath, string watermarkText = "", string watermarkImagepath = "") { if (string.IsNullOrWhiteSpace(watermarkText) && string.IsNullOrWhiteSpace(watermarkImagepath)) { //未指定添加什么水印 return; } //创建目录 string dir = Path.GetDirectoryName(savefilepath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromStream(sourcefile, true); //文字水印 if (watermarkText != "") { using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage)) { System.Drawing.Font fontWater = new Font("宋体", 10); System.Drawing.Brush brushWater = new SolidBrush(Color.White); gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10); gWater.Dispose(); } } //透明图片水印 if (watermarkImagepath != "") { if (File.Exists(watermarkImagepath)) { //获取水印图片 using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImagepath)) { //水印绘制条件:原始图片宽高均大于或等于水印图片 if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height) { Graphics gWater = Graphics.FromImage(initImage); //透明属性 ImageAttributes imgAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f }, //透明度:0.5 new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes); gWater.Dispose(); } wrImage.Dispose(); } } } //保存缩略图 initImage.Save(savefilepath, System.Drawing.Imaging.ImageFormat.Jpeg); //释放资源 initImage.Dispose(); }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> /// <param name="mode1">HW/指定高宽缩放(可能变形)</param> /// <param name="mode2">W/指定宽,高按比例</param> /// <param name="mode3">H/指定高,宽按比例</param> /// <param name="mode4">Cut/指定高宽裁减(不变形)</param> /// <param name="mode5">DB/等比缩放(不变形,如果高大按高,宽大按宽缩放)</param> public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode, string type) { Image originalImage = Image.FromFile(originalImagePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "HW": //指定高宽缩放(可能变形) break; case "W": //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H": //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut": //指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; case "DB": //等比缩放(不变形,如果高大按高,宽大按宽缩放) if ((double)originalImage.Width / (double)towidth < (double)originalImage.Height / (double)toheight) { toheight = height; towidth = originalImage.Width * height / originalImage.Height; } else { towidth = width; toheight = originalImage.Height * width / originalImage.Width; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); g.CompositingMode = CompositingMode.SourceCopy; g.CompositingQuality = CompositingQuality.HighQuality; //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(System.Drawing.Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { //保存缩略图 if (type == ".jpg") { bitmap.Save(thumbnailPath, ImageFormat.Jpeg); } if (type == ".bmp") { bitmap.Save(thumbnailPath, ImageFormat.Bmp); } if (type == ".gif") { bitmap.Save(thumbnailPath, ImageFormat.Gif); } if (type == ".png") { bitmap.Save(thumbnailPath, ImageFormat.Png); } } catch (Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> private void MakeThumbnail(string originalImagePath, int width, int height, string mode, string type) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case "HW": //指定高宽缩放(可能变形) break; case "W": //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H": //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut": //指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; case "DB": //等比缩放(不变形,如果高大按高,宽大按宽缩放) if ((double)originalImage.Width / (double)towidth < (double)originalImage.Height / (double)toheight) { toheight = height; towidth = originalImage.Width * height / originalImage.Height; } else { towidth = width; toheight = originalImage.Height * width / originalImage.Width; } break; default: break; } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(System.Drawing.Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); //System.Drawing.Font f = new System.Drawing.Font("Verdana", 12); //System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Gray); //g.DrawString(addText, f, b, 5, height - 40); System.IO.MemoryStream ms = new System.IO.MemoryStream(); try { //保存缩略图 if (type == "JPG") { bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); } if (type == "BMP") { bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); } if (type == "GIF") { bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); } if (type == "PNG") { bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png); } Response.ClearContent(); Response.ContentType = "Image/Gif"; Response.BinaryWrite(ms.ToArray()); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } }
/// <SUMMARY> /// 生成缩略图//带压缩图片不压缩22k压缩2k /// </SUMMARY> /// <PARAM name="originalImagePath" />原始路径 /// <PARAM name="thumbnailPath" />生成缩略图路径 /// <PARAM name="width" />缩略图的宽 /// <PARAM name="height" />缩略图的高 //是否压缩图片质量 public static void MakeThumbnail(Stream sFile, string thumbnailPath, int width, int height, bool Ys) { //获取原始图片 Image originalImage = Image.FromStream(sFile); //缩略图画布宽高 int towidth = 0; int toheight = 0; if (originalImage.Width > 1800) //图片像素大于1800,则缩放四倍 { width = originalImage.Width / 4; height = originalImage.Height / 4; towidth = width; toheight = height; } else if (originalImage.Width > 800) //图片像素大于800,则缩放2倍 { width = originalImage.Width / 2; height = originalImage.Height / 2; towidth = width; toheight = height; } else //图片不是太大,则保持原大小 { towidth = originalImage.Width; //width; toheight = originalImage.Height; //height; width = towidth; height = toheight; } //原始图片写入画布坐标和宽高(用来设置裁减溢出部分) int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放) int bg_x = 0; int bg_y = 0; int bg_w = towidth; int bg_h = toheight; //倍数变量 double multiple = 0; //获取宽长的或是高长与缩略图的倍数 if (originalImage.Width >= originalImage.Height) { multiple = (double)originalImage.Width / (double)width; } else { multiple = (double)originalImage.Height / (double)height; } //上传的图片的宽和高小等于缩略图 if (ow <= width && oh <= height) { //缩略图按原始宽高 bg_w = originalImage.Width; bg_h = originalImage.Height; //空白部分用背景色填充 bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2); bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2); } //上传的图片的宽和高大于缩略图 else { //宽高按比例缩放 bg_w = Convert.ToInt32((double)originalImage.Width / multiple); bg_h = Convert.ToInt32((double)originalImage.Height / multiple); //空白部分用背景色填充 bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2); bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2); } //新建一个bmp图片,并设置缩略图大小. System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并设置背景色 g.Clear(System.Drawing.ColorTranslator.FromHtml("#FFF")); //在指定位置并且按指定大小绘制原图片的指定部分 //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素 g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); if (Ys) { System.Drawing.Imaging.ImageCodecInfo encoder = GetEncoderInfo("image/jpeg"); try { if (encoder != null) { System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1); //设置 jpeg 质量为 60 encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)50); bitmap.Save(thumbnailPath, encoder, encoderParams); encoderParams.Dispose(); } } catch (System.Exception e) { //throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } } else { try { //获取图片类型 string fileExtension = ".jpg"; //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题. switch (fileExtension) { case ".gif": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Gif); break; case ".jpg": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg); break; case ".bmp": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Bmp); break; case ".png": bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Png); break; } } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } } }
private void MapImage_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { if (_Map != null) { SharpMap.Geometries.Point p = this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y)); if (MouseMove != null) { MouseMove(p, e); } if (Image != null && e.Location != mousedrag && !mousedragging && e.Button == MouseButtons.Left) { mousedragImg = this.Image.Clone() as Image; mousedragging = true; } if (mousedragging) { if (MouseDrag != null) { MouseDrag(p, e); } if (this.ActiveTool == Tools.Pan) { System.Drawing.Image img = new System.Drawing.Bitmap(this.Size.Width, this.Size.Height); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(img); g.Clear(Color.Transparent); g.DrawImageUnscaled(mousedragImg, new System.Drawing.Point(e.Location.X - mousedrag.X, e.Location.Y - mousedrag.Y)); g.Dispose(); this.Image = img; } else if (this.ActiveTool == Tools.ZoomIn || this.ActiveTool == Tools.ZoomOut) { System.Drawing.Image img = new System.Drawing.Bitmap(this.Size.Width, this.Size.Height); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(img); g.Clear(Color.Transparent); float scale = 0; if (e.Y - mousedrag.Y < 0) //Zoom out { scale = (float)Math.Pow(1 / (float)(mousedrag.Y - e.Y), 0.5); } else //Zoom in { scale = 1 + (e.Y - mousedrag.Y) * 0.1f; } RectangleF rect = new RectangleF(0, 0, this.Width, this.Height); if (_Map.Zoom / scale < _Map.MinimumZoom) { scale = (float)Math.Round(_Map.Zoom / _Map.MinimumZoom, 4); } rect.Width *= scale; rect.Height *= scale; rect.Offset(this.Width / 2 - rect.Width / 2, this.Height / 2 - rect.Height / 2); g.DrawImage(mousedragImg, rect); g.Dispose(); this.Image = img; if (MapZooming != null) { MapZooming(scale); } } } } }
// --- functions --- /// <summary>Gets the texture from this origin.</summary> /// <param name="texture">Receives the texture.</param> /// <returns>Whether the texture could be obtained successfully.</returns> public override bool GetTexture(out Texture texture) { Bitmap bitmap = this.Bitmap; Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); /* * If the bitmap format is not already 32-bit BGRA, * then convert it to 32-bit BGRA. * */ Color24[] p = null; if (bitmap.PixelFormat != PixelFormat.Format32bppArgb && bitmap.PixelFormat != PixelFormat.Format24bppRgb) { /* Only store the color palette data for * textures using a restricted palette * With a large number of textures loaded at * once, this can save a decent chunk of memory * */ p = new Color24[bitmap.Palette.Entries.Length]; for (int i = 0; i < bitmap.Palette.Entries.Length; i++) { p[i] = bitmap.Palette.Entries[i]; } } if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) { Bitmap compatibleBitmap = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format32bppArgb); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(compatibleBitmap); graphics.DrawImage(bitmap, rect, rect, GraphicsUnit.Pixel); graphics.Dispose(); bitmap = compatibleBitmap; } /* * Extract the raw bitmap data. * */ BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat); if (data.Stride == 4 * data.Width) { /* * Copy the data from the bitmap * to the array in BGRA format. * */ byte[] raw = new byte[data.Stride * data.Height]; System.Runtime.InteropServices.Marshal.Copy(data.Scan0, raw, 0, data.Stride * data.Height); bitmap.UnlockBits(data); int width = bitmap.Width; int height = bitmap.Height; /* * Change the byte order from BGRA to RGBA. * */ for (int i = 0; i < raw.Length; i += 4) { byte temp = raw[i]; raw[i] = raw[i + 2]; raw[i + 2] = temp; } texture = new Texture(width, height, 32, raw, p); texture = texture.ApplyParameters(this.Parameters); return(true); } /* * The stride is invalid. This indicates that the * CLI either does not implement the conversion to * 32-bit BGRA correctly, or that the CLI has * applied additional padding that we do not * support. * */ bitmap.UnlockBits(data); texture = null; return(false); }
public void ResizeImageAndRatio(string origFileLocation, string newFileLocation, string origFileName, string newFileName, int newWidth, int newHeight, bool resizeIfWider) { System.Drawing.Image initImage = System.Drawing.Image.FromFile(origFileLocation + origFileName); int templateWidth = newWidth; int templateHeight = newHeight; double templateRate = double.Parse(templateWidth.ToString()) / templateHeight; double initRate = double.Parse(initImage.Width.ToString()) / initImage.Height; if (templateRate == initRate) { System.Drawing.Image templateImage = new System.Drawing.Bitmap(templateWidth, templateHeight); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, templateWidth, templateHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); templateImage.Save(newFileLocation + newFileName, System.Drawing.Imaging.ImageFormat.Jpeg); } else { System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; Rectangle fromR = new Rectangle(0, 0, 0, 0); Rectangle toR = new Rectangle(0, 0, 0, 0); if (templateRate > initRate) { pickedImage = new System.Drawing.Bitmap(initImage.Width, int.Parse(Math.Floor(initImage.Width / templateRate).ToString())); pickedG = System.Drawing.Graphics.FromImage(pickedImage); fromR.X = 0; fromR.Y = int.Parse(Math.Floor((initImage.Height - initImage.Width / templateRate) / 2).ToString()); fromR.Width = initImage.Width; fromR.Height = int.Parse(Math.Floor(initImage.Width / templateRate).ToString()); toR.X = 0; toR.Y = 0; toR.Width = initImage.Width; toR.Height = int.Parse(Math.Floor(initImage.Width / templateRate).ToString()); } else { pickedImage = new System.Drawing.Bitmap(int.Parse(Math.Floor(initImage.Height * templateRate).ToString()), initImage.Height); pickedG = System.Drawing.Graphics.FromImage(pickedImage); fromR.X = int.Parse(Math.Floor((initImage.Width - initImage.Height * templateRate) / 2).ToString()); fromR.Y = 0; fromR.Width = int.Parse(Math.Floor(initImage.Height * templateRate).ToString()); fromR.Height = initImage.Height; toR.X = 0; toR.Y = 0; toR.Width = int.Parse(Math.Floor(initImage.Height * templateRate).ToString()); toR.Height = initImage.Height; } pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); System.Drawing.Image templateImage = new System.Drawing.Bitmap(templateWidth, templateHeight); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, templateWidth, templateHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel); templateImage.Save(newFileLocation + newFileName, System.Drawing.Imaging.ImageFormat.Jpeg); templateG.Dispose(); templateImage.Dispose(); pickedG.Dispose(); pickedImage.Dispose(); } initImage.Dispose(); }
/// <summary> /// 根据指定:缩略宽、高,缩略图片并保存 /// 返回图片虚拟路径,和一个警告信息,可根据此信息获取图片合成信息 /// </summary> /// <param name="picpath">原图路径</param> /// <param name="model">缩略模式[X,Y,XY](默认XY模式)</param> /// <param name="spath">文件保存路径(默认跟路径)</param> /// <param name="imgtype">图片保存类型</param> /// <param name="mwidth">缩略宽度(默认原图高度)</param> /// <param name="mheight">缩略高度(默认原图高度)</param> /// <param name="filecache">原文件处理方式</param> /// <param name="warning">处理警告信息</param> /// <returns>错误,返回错误信息;成功,返回图片路径</returns> public static string Resizepic(string picpath, ResizeType model, string spath, ImageType imgtype, double?mwidth, double?mheight, FileCache filecache, out string warning) { //反馈信息 System.Text.StringBuilder checkmessage = new System.Text.StringBuilder(); //文件保存路径 spath = string.IsNullOrEmpty(spath) ? "/" : spath; //缩略宽度 double swidth = mwidth.HasValue ? double.Parse(mwidth.ToString()) : 0; //缩略高度 double sheight = mheight.HasValue ? double.Parse(mheight.ToString()) : 0; //从指定源图片,创建image对象 string _sourceimg_common_mappath = ""; //检测源文件 bool checkfile = false; checkfile = FileExistMapPath(picpath, FileCheckModel.C, out _sourceimg_common_mappath); System.Drawing.Image _sourceimg_common = null; System.Drawing.Bitmap _currimg_common = null; System.Drawing.Graphics _g_common = null; if (checkfile == true) { //从源文件创建imgage _sourceimg_common = System.Drawing.Image.FromFile(_sourceimg_common_mappath); #region 缩略模式 //缩略模式 switch (model) { case ResizeType.X: #region X模式 //根据给定尺寸,获取绘制比例 double _width_scale = swidth / _sourceimg_common.Width; //高着比例 sheight = _sourceimg_common.Height * _width_scale; #endregion ; break; case ResizeType.Y: #region Y模式 //根据给定尺寸,获取绘制比例 double _height_scale = sheight / _sourceimg_common.Height; //宽着比例 swidth = _sourceimg_common.Width * _height_scale; #endregion ; break; case ResizeType.XY: #region XY模式 //当选择XY模式时,mwidth,mheight为必须值 if (swidth < 0 || sheight < 0) { checkmessage.Append("error:XY模式,mwidth,mheight为必须值;"); } #endregion ; break; default: #region 默认XY模式 //当默认XY模式时,mwidth,mheight为必须值 if (swidth < 0 || sheight < 0) { checkmessage.Append("error:你当前未选择缩略模式,系统默认XY模式,mwidth,mheight为必须值;"); } ; break; #endregion } #endregion } else { checkmessage.Append("error:未能找到缩略原图片," + picpath + ";"); } if (string.IsNullOrEmpty(checkmessage.ToString())) { //创建bitmap对象 _currimg_common = new System.Drawing.Bitmap((int)swidth, (int)sheight); _g_common = Graphics.FromImage(_currimg_common); //设置画笔 _g_common.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; _g_common.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; _g_common.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; //绘制图片 _g_common.DrawImage(_sourceimg_common, new Rectangle(0, 0, (int)swidth, (int)sheight), new Rectangle(0, 0, _sourceimg_common.Width, _sourceimg_common.Height), GraphicsUnit.Pixel); //保存图片 string _spath_common_mappath = ""; //获取图片类型的hashcode值,生成图片后缀名 int extro = imgtype.GetHashCode(); string extend = extro == 0 ? ".jpg" : (extro == 1 ? ".gif" : (extro == 2 ? ".png" : ".jpg")); //全局文件名 spath = spath + Guid.NewGuid().ToString() + extend; FileExistMapPath(spath, FileCheckModel.M, out _spath_common_mappath); switch (imgtype) { case ImageType.JPEG: _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Jpeg); break; case ImageType.GIF: _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Gif); break; case ImageType.PNG: _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Png); break; } //释放 _sourceimg_common.Dispose(); _currimg_common.Dispose(); _g_common.Dispose(); //处理原文件 int filecachecode = filecache.GetHashCode(); //文件缓存方式:Delete,删除原文件 if (filecachecode == 1) { System.IO.File.Delete(_sourceimg_common_mappath); } //返回相对虚拟路径 warning = ""; return(spath); } //释放 if (_sourceimg_common != null) { _sourceimg_common.Dispose(); } if (_currimg_common != null) { _currimg_common.Dispose(); } if (_g_common != null) { _g_common.Dispose(); } warning = checkmessage.ToString().TrimEnd(';'); return(""); }
/// <summary> /// 正方型裁剪 /// 以图片中心为轴心,截取正方型,然后等比缩放 /// 用于头像处理 /// </summary> /// <param name="fromFile">原图Stream对象</param> /// <param name="fileSaveUrl">缩略图存放地址</param> /// <param name="side">指定的边长(正方型)</param> /// <param name="quality">质量(范围0-100)</param> public static void CutForSquare(System.IO.Stream fromFile, string fileSaveUrl, int side, int quality) { //创建目录 string dir = Path.GetDirectoryName(fileSaveUrl); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= side && initImage.Height <= side) { initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //原始图片的宽、高 int initWidth = initImage.Width; int initHeight = initImage.Height; //非正方型先裁剪为正方型 if (initWidth != initHeight) { //截图对象 System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; //宽大于高的横图 if (initWidth > initHeight) { //对象实例化 pickedImage = new System.Drawing.Bitmap(initHeight, initHeight); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //定位 Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight); Rectangle toR = new Rectangle(0, 0, initHeight, initHeight); //画图 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //重置宽 initWidth = initHeight; } //高大于宽的竖图 else { //对象实例化 pickedImage = new System.Drawing.Bitmap(initWidth, initWidth); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //定位 Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth); Rectangle toR = new Rectangle(0, 0, initWidth, initWidth); //画图 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //重置高 initHeight = initWidth; } //将截图对象赋给原图 initImage = (System.Drawing.Image)pickedImage.Clone(); //释放截图资源 pickedG.Dispose(); pickedImage.Dispose(); } //缩略图对象 System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side); System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage); //设置质量 resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //用指定背景色清空画布 resultG.Clear(Color.White); //绘制缩略图 resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel); //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo i in icis) { if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif") { ici = i; } } EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); //保存缩略图 resultImage.Save(fileSaveUrl, ici, ep); //释放关键质量控制所用资源 ep.Dispose(); //释放缩略图资源 resultG.Dispose(); resultImage.Dispose(); //释放原始图片资源 initImage.Dispose(); } }
/// <summary> /// Takes in an image, scales it maintaining the proper aspect ratio of the image such it fits in the PictureBox's canvas size and loads the image into picture box. /// Has an optional param to center the image in the picture box if it's smaller then canvas size. /// </summary> /// <param name="image">The Image you want to load, see LoadPicture</param> /// <param name="canvas">The canvas you want the picture to load into</param> /// <param name="centerImage"></param> /// <returns></returns> public static Image ResizeImage(Image image, PictureBox canvas, bool centerImage) { if (image == null || canvas == null) { return(null); } int canvasWidth = canvas.Size.Width; int canvasHeight = canvas.Size.Height; int originalWidth = image.Size.Width; int originalHeight = image.Size.Height; System.Drawing.Image thumbnail = new Bitmap(canvasWidth, canvasHeight); // changed parm names System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(thumbnail); graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; graphic.CompositingQuality = CompositingQuality.HighQuality; /* ------------------ new code --------------- */ // Figure out the ratio double ratioX = (double)canvasWidth / (double)originalWidth; double ratioY = (double)canvasHeight / (double)originalHeight; double ratio = ratioX < ratioY ? ratioX : ratioY; // use whichever multiplier is smaller // now we can get the new height and width int newHeight = Convert.ToInt32(originalHeight * ratio); int newWidth = Convert.ToInt32(originalWidth * ratio); // Now calculate the X,Y position of the upper-left corner // (one of these will always be zero) int posX = Convert.ToInt32((canvasWidth - (image.Width * ratio)) / 2); int posY = Convert.ToInt32((canvasHeight - (image.Height * ratio)) / 2); if (!centerImage) { posX = 0; posY = 0; } graphic.Clear(Color.White); // white padding graphic.DrawImage(image, posX, posY, newWidth, newHeight); /* ------------- end new code ---------------- */ System.Drawing.Imaging.ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); Stream s = new System.IO.MemoryStream(); thumbnail.Save(s, info[1], encoderParameters); Image img = Image.FromStream(s); //Disposal of unmanaged resources if (s != null) { s.Dispose(); } if (encoderParameters != null) { encoderParameters.Dispose(); } if (graphic != null) { graphic.Dispose(); } if (thumbnail != null) { thumbnail.Dispose(); } return(img); }
/// <summary> /// Constructs a new brush form /// </summary> /// <param name="background">The background to render from</param> /// <param name="brush">Brush to save</param> /// <param name="tileSize">Size of a single tile</param> public SaveBrushForm(Bitmap background, GMareBrush brush, Size tileSize) { InitializeComponent(); // Create new graphics object Bitmap image = new Bitmap(brush.Width, brush.Height); System.Drawing.Graphics gfx = System.Drawing.Graphics.FromImage(image); // Iterate through tiles horizontally for (int col = 0; col < brush.Columns; col++) { // Iterate through tiles vertically for (int row = 0; row < brush.Rows; row++) { // If the tile is empty, continue looping if (brush.Tiles[col, row].TileId == -1) { continue; } // Calculate source point Rectangle source = new Rectangle(GMareBrush.TileIdToSourcePosition(brush.Tiles[col, row].TileId, background.Width, tileSize), tileSize); Rectangle dest = new Rectangle(new Point(col * tileSize.Width, row * tileSize.Height), tileSize); // Get tile Bitmap temp = Graphics.PixelMap.PixelDataToBitmap(Graphics.PixelMap.GetPixels(background, source)); Color color = brush.Tiles[col, row].Blend; float red = color.R / 255.0f; float green = color.G / 255.0f; float blue = color.B / 255.0f; // Alpha changing color matrix ColorMatrix cm = new ColorMatrix(new float[][] { new float[] { red, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, green, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, blue, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }); // Create new image attributes ImageAttributes ia = new ImageAttributes(); ia.SetColorMatrix(cm); // Flip tile switch (brush.Tiles[col, row].FlipMode) { case FlipType.Horizontal: temp.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case FlipType.Vertical: temp.RotateFlip(RotateFlipType.RotateNoneFlipY); break; case FlipType.Both: temp.RotateFlip(RotateFlipType.RotateNoneFlipX); temp.RotateFlip(RotateFlipType.RotateNoneFlipY); break; } // Draw tile gfx.DrawImage(temp, dest, 0, 0, tileSize.Width, tileSize.Height, GraphicsUnit.Pixel, ia); // Dispose temp.Dispose(); ia.Dispose(); } } // Set brush image pnlBrush.Image = image; // Dispose of the graphics gfx.Dispose(); // Validate CheckText(); }