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(); }
private void EnsureTemporaryBitmap( int width, int height ) { if( bmp != null ) { if( bmp.Width >= width && bmp.Height >= height ) { g.Clear( Color.Black ); return; } width = Math.Max( width, bmp.Width ); height = Math.Max( height, bmp.Height ); } Helpers.DisposeAndClear( ref g ); Helpers.DisposeAndClear( ref bmp ); bmp = new Bitmap( width, height, PixelFormat.Format32bppRgb ); g = Graphics.FromImage( bmp ); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; g.Clear( Color.Black ); }
public RectangleTransparent() { clearPen = new Pen(Color.FromArgb(1, 0, 0, 0)); borderDotPen = new Pen(Color.Black, 1); borderDotPen2 = new Pen(Color.White, 1); borderDotPen2.DashPattern = new float[] { 5, 5 }; penTimer = Stopwatch.StartNew(); ScreenRectangle = CaptureHelpers.GetScreenBounds(); surface = new Bitmap(ScreenRectangle.Width, ScreenRectangle.Height); gSurface = Graphics.FromImage(surface); gSurface.InterpolationMode = InterpolationMode.NearestNeighbor; gSurface.SmoothingMode = SmoothingMode.HighSpeed; gSurface.CompositingMode = CompositingMode.SourceCopy; gSurface.CompositingQuality = CompositingQuality.HighSpeed; gSurface.Clear(Color.FromArgb(1, 0, 0, 0)); StartPosition = FormStartPosition.Manual; Bounds = ScreenRectangle; Text = "ShareX - " + Resources.RectangleTransparent_RectangleTransparent_Rectangle_capture_transparent; Shown += RectangleLight_Shown; KeyUp += RectangleLight_KeyUp; MouseDown += RectangleLight_MouseDown; MouseUp += RectangleLight_MouseUp; using (MemoryStream cursorStream = new MemoryStream(Resources.Crosshair)) { Cursor = new Cursor(cursorStream); } timer = new Timer { Interval = 10 }; timer.Tick += timer_Tick; timer.Start(); }
public void DrawPieChart() { g = Graphics.FromImage(bitmapd); g.Clear(System.Drawing.Color.AliceBlue); int a = db.getCountFromDB("select count(*) from music"); DataTable dt = db.getQueryFromDB("select distinct Genre from music"); int index = 0; int[] myPiePercent = new int[dt.Rows.Count]; string [] values=new string[dt.Rows.Count]; foreach (DataRow r in dt.Rows) { string s = r[0].ToString(); int b = db.getCountFromDB(string.Format("select count(*) from music where Genre='{0}'", s)); myPiePercent[index] = (int)Math.Ceiling(((double)b * 100 / a)); values[index] = s; index++; } System.Drawing.Color[] myPieColors = { c1, c2, c3, c4 }; g.Clear(System.Drawing.Color.AliceBlue); System.Drawing.Size myPieSize ; System.Drawing.Point myPieLocation ; if (x < y) { myPieSize= new System.Drawing.Size(x - 50, x - 50); myPieLocation = new System.Drawing.Point(x / 2, x / 2); } else { myPieSize = new System.Drawing.Size(y - 50, y - 50); myPieLocation = new System.Drawing.Point(y / 2, y / 2); } int PiePercentTotal = 0; for (int PiePercents = 0; PiePercents < myPiePercent.Length; PiePercents++) { using (SolidBrush brush = new SolidBrush(myPieColors[PiePercents])) { g.FillPie(brush, new System.Drawing.Rectangle(new System.Drawing.Point(10, 10), myPieSize), Convert.ToSingle(PiePercentTotal * 360 / 100), Convert.ToSingle(myPiePercent[PiePercents] * 360 / 100)); } PiePercentTotal += myPiePercent[PiePercents]; } double xx = 0, yy = 0; for (int k = 0; k < index; k ++) { yy = Math.Sin(100*k*Math.PI/180) * 90; xx = Math.Cos(k*100 * Math.PI / 180) * 90; //g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black), myPieLocation.X+(int)xx,myPieLocation.Y+ (int)yy, 5, 5); g.DrawString(values[k], new System.Drawing.Font("Sans", 10), System.Drawing.Brushes.Black, myPieLocation.X-30+(float)xx, myPieLocation.Y+(float)yy); } }
private void CreateImage(string checkCode) { int iwidth = (int)(checkCode.Length * 25); System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 30); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); System.Drawing.Font f = new System.Drawing.Font("Arial", 20, System.Drawing.FontStyle.Bold); System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.White); //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height); g.Clear(System.Drawing.Color.Blue); g.DrawString(checkCode, f, b, 3, 3); System.Drawing.Pen blackPen = new System.Drawing.Pen(System.Drawing.Color.Black, 0); Random rand = new Random(); for (int i = 0; i < 5; i++) { int y = rand.Next(image.Height); g.DrawLine(blackPen, 0, y, image.Width, y); } System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); Response.ClearContent(); Response.ContentType = "image/Jpeg"; Response.BinaryWrite(ms.ToArray()); g.Dispose(); image.Dispose(); }
public void DrawPDF417(ref Graphics g) { g.Clear(this.backcolor); SolidBrush brush = new SolidBrush(this.forecolor); int x = this.leftmargin; int y = this.topmargin; SizeF ef = g.MeasureString(this.bottomcomment, this.txtFont, 0x7fffffff, StringFormat.GenericTypographic); for (int i = 0; i < this.encodebinarystr.Length; i++) { char ch = this.encodebinarystr[i]; switch (ch) { case '0': x += this.modulewidth; break; case '1': g.FillRectangle(brush, x, y, this.modulewidth, this.moduleheight); x += this.modulewidth; break; default: if (ch == 'Z') { y += this.moduleheight; x = this.leftmargin; } break; } } g.DrawString(this.topcomment, this.txtFont, brush, (float) this.topcommentleftmargin, (float) this.topcommenttopmargin); //g.DrawString(" ", this.txtFont, brush, (float) 0f, (float) (this.symbolheight - ef.Height)); brush.Dispose(); }
Bitmap drawBattleDice(Graphics gDice, Bitmap diceBitmap, Pen myPen, Brush myBrush, int level, int randomNumber) { gDice.Clear(Color.Transparent); PointF[] Verticies; Verticies = new PointF[3]; Verticies[0] = new PointF(0, pbDice.Height - 1); Verticies[1] = new PointF(pbDice.Width - 1, pbDice.Height - 1); Verticies[2] = new PointF(pbDice.Width / 2.0f, (float)(pbDice.Height - 1 - pbDice.Height / 2 * Math.Sqrt(3))); if (level == 1) gDice.FillPolygon(new SolidBrush(Color.Green), Verticies); else if(level==2) gDice.FillPolygon(new SolidBrush(Color.Red), Verticies); else if (level == 3) gDice.FillPolygon(new SolidBrush(Color.Blue), Verticies); else if (level == 4) gDice.FillPolygon(new SolidBrush(Color.Purple), Verticies); myPen.Color = Color.Black; gDice.DrawPolygon(myPen, Verticies); Font font = new Font("Times New Roman", 16, FontStyle.Bold); StringFormat format = new StringFormat(); Brush whiteBrush = new SolidBrush(Color.White); format.Alignment = StringAlignment.Center; RectangleF rect = new RectangleF(pbDice.Width / 2 - 20 , pbDice.Height / 2 - 4 , 40 , 25); if (randomNumber == 0) { rect.Y = pbDice.Height / 2 + 6; gDice.DrawString("Roll", new Font("Times New Roman", 14, FontStyle.Italic), whiteBrush, rect, format); } else { gDice.DrawString(randomNumber.ToString(), font, whiteBrush, rect, format); } return diceBitmap; }
///<summary> /// 对给定的一个图片(Image对象)生成一个指定大小的缩略图。 ///</summary> ///<param name="originalImage">原始图片</param> ///<param name="thumMaxWidth">缩略图的宽度</param> ///<param name="thumMaxHeight">缩略图的高度</param> ///<returns>返回缩略图的Image对象</returns> public static System.Drawing.Image GetThumbNailImage(System.Drawing.Image originalImage, int thumMaxWidth, int thumMaxHeight) { System.Drawing.Size thumRealSize = System.Drawing.Size.Empty; System.Drawing.Image newImage = originalImage; System.Drawing.Graphics graphics = null; try { thumRealSize = GetNewSize(thumMaxWidth, thumMaxHeight, originalImage.Width, originalImage.Height); newImage = new System.Drawing.Bitmap(thumRealSize.Width, thumRealSize.Height); graphics = System.Drawing.Graphics.FromImage(newImage); graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.Clear(System.Drawing.Color.Transparent); graphics.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, thumRealSize.Width, thumRealSize.Height), new System.Drawing.Rectangle(0, 0, originalImage.Width, originalImage.Height), System.Drawing.GraphicsUnit.Pixel); } catch { } finally { if (graphics != null) { graphics.Dispose(); graphics = null; } } return(newImage); }
void Former.new84file() { pixels = new PixelButton[256, 128]; map = new Bitmap(256, 128); gra = Graphics.FromImage(map); gra.Clear(Color.Transparent); }
void Former.new42file() { pixels = new PixelButton[128, 64]; map = new Bitmap(128, 64); gra = Graphics.FromImage(map); gra.Clear(Color.Transparent); }
int x1 = 0, y1 = 0; // для рисования линии #endregion Fields #region Constructors public Form1() { InitializeComponent(); this.Height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height; this.Width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width; imageBox.Width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width - 200; imageBox.Height = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height - 200; panel3.Width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width - 195; imagePanel.Width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Height - 180; imagePanel.Height = imageBox.Width = System.Windows.Forms.SystemInformation.PrimaryMonitorSize.Width - 180; imagePanel.AutoSize = true; imagePanel.AutoScroll = true; DoubleBuffered = true; g = imageBox.CreateGraphics(); g.Clear(foneColor); //// Тест //bmp = new Bitmap(imageBox.Width, imageBox.Height); //g = Graphics.FromImage(bmp); //g.Clear(foneColor); //g.FillRectangle(new SolidBrush(Color.Gainsboro), 0, 0, bmp.Width, bmp.Height); //g.DrawLine(blackPen, 0, 0, bmp.Width, bmp.Height); //g.DrawLine(blackPen, 0, bmp.Height, bmp.Width, 0); //g.Dispose(); //this.imageBox.Image = bmp; //this.imageBox.Size = bmp.Size; //this.vScrollBar1.Maximum = bmp.Height + this.ClientSize.Height; //this.hScrollBar1.Maximum = bmp.Width + this.ClientSize.Width; //this.hScrollBar1.Value = 0; //this.Text = "x = 0, y = 0"; }
public CDrawWinForm() { this.Icon = new System.Drawing.Icon(Path.Combine(System.Environment.CurrentDirectory, CSettings.sIcon)); _Textures = new List<STexture>(); _Bitmaps = new List<Bitmap>(); _Keys = new CKeys(); _Mouse = new CMouse(); this.ClientSize = new Size(1280, 720); this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.Opaque, true); // Create the backbuffer _backbuffer = new Bitmap(CSettings.iRenderW, CSettings.iRenderH); _g = Graphics.FromImage(_backbuffer); _g.Clear(Color.DarkBlue); this.Paint += new PaintEventHandler(this.OnPaintEvent); this.Closing += new CancelEventHandler(this.OnClosingEvent); this.KeyDown += new KeyEventHandler(this.OnKeyDownEvent); this.KeyPress += new KeyPressEventHandler(this.OnKeyPressEvent); this.KeyUp += new KeyEventHandler(this.OnKeyUpEvent); this.Resize += new EventHandler(this.OnResizeEvent); this.MouseMove += new MouseEventHandler(this.OnMouseMove); this.MouseDown += new MouseEventHandler(this.OnMouseDown); this.MouseUp += new MouseEventHandler(this.OnMouseUp); FlipBuffer(); Cursor.Show(); }
public FormMain() { InitializeComponent(); BGpath = currentDir + @"DATA\IMG\background.jpg"; CHpath = currentDir + @"DATA\IMG\actor.png"; btnSTART.Enabled = false; btnStep.Enabled = false; checkBG.Checked = checkCH.Checked = checkTXT.Checked = true; btnBackColor.BackColor = Color.White; btnForeColor.ForeColor = Color.White; btnBackColor.ForeColor = Color.Black; btnForeColor.BackColor = Color.Black; Label lab = new Label(); lab.BackColor = Color.Transparent; ThumbPicCH.Controls.Add(lab); btnStep.Text = "��ʼ��������"; GThumb = panel1.CreateGraphics(); GThumb.Clear(Color.White); LoadFile(); }
/// <summary> /// Constructs a new instance. /// </summary> /// <param name="width">The width of the backing store in pixels.</param> /// <param name="height">The height of the backing store in pixels.</param> /// <param name="renderer">GWEN renderer.</param> public TextRenderer(int width, int height, FreezingArcherGwenRenderer renderer) { if (width <= 0) throw new ArgumentOutOfRangeException("width"); if (height <= 0) throw new ArgumentOutOfRangeException("height"); bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); gfx = Graphics.FromImage(bmp); gfx.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; gfx.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gfx.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // NOTE: TextRenderingHint.AntiAliasGridFit looks sharper and in most cases better // but it comes with a some problems. // // 1. Graphic.MeasureString and format.MeasureCharacterRanges // seem to return wrong values because of this. // // 2. While typing the kerning changes in random places in the sentence. // // Until 1st problem is fixed we should use TextRenderingHint.AntiAlias... :-( gfx.TextRenderingHint = TextRenderingHint.AntiAlias; gfx.Clear(Color.Transparent); texture = new Texture(renderer) {Width = width, Height = height}; }
public static void Draw(ref List<long> Data, Graphics g) { List<double> normalized_data = new List<double>(); lock (Data) { if (Data.Count > 100) { for (int remove = 1; remove <= 10; remove++) { Data.RemoveAt((Data.Count - 1) / remove); } } long max = 0; for (int d = 0; d < Data.Count; d++) if (Data[d] > max) max = Data[d]; for (int d = 0; d < Data.Count; d++) normalized_data.Add((double)Data[d] / Math.Max((double)max, 0.0000001)); } RectangleF bounds = g.VisibleClipBounds; g.Clear(Color.DarkGray); for (int d = 0; d < normalized_data.Count - 1; d++) { g.DrawLine(Pens.White, ((float)d / (float)normalized_data.Count) * bounds.Width, bounds.Height - ((float)normalized_data[d] * bounds.Height), (((float)d + 1) / (float)normalized_data.Count) * bounds.Width, bounds.Height - ((float)normalized_data[d + 1] * bounds.Height)); } }
// ���»��� public void PaintPalette(Graphics gp) { gp.Clear(this._bgColor); this._food.Paint(gp); foreach (Block b in this._blocks) b.Paint(gp); }
public IDisposable CreateContext() { _gfx = Graphics.FromImage(_bitmap); _gfx.Init(); _gfx.Clear(System.Drawing.Color.Transparent); return _gfx; }
}//end constructor //call the paint method public override void paint (Graphics graphics) { try { //save the old value of the circle position previousLeftPosition = leftPosition; previousTopPosition = topPosition; //put this thread to sleep Thread.Sleep(speed); //lock thread to prevent thread from running back on itself lock (typeof(Thread)) { leftPosition = leftPosition + base.directionX; topPosition = topPosition + base.directionY; base.CheckCoordinates(); //grouped the drawing functions together like this to slightly reduce flickering graphics.DrawEllipse(new System.Drawing.Pen(Color.White), previousLeftPosition, previousTopPosition, width, height); graphics.DrawEllipse(new System.Drawing.Pen(shapeColor), leftPosition, topPosition, width, height); } } catch { //force the thread to end, but only after removing the shape from the screen graphics.Clear(Color.White); Thread.CurrentThread.Abort(); } }//end paint
/// <summary> /// Constructs a new instance. /// </summary> /// <param name="width">The width of the backing store in pixels.</param> /// <param name="height">The height of the backing store in pixels.</param> /// <param name="renderer">GWEN renderer.</param> public TextRenderer(int width, int height, Renderer.OpenTK renderer) { if (width <= 0) throw new ArgumentOutOfRangeException("width"); if (height <= 0) throw new ArgumentOutOfRangeException("height"); if (GraphicsContext.CurrentContext == null) throw new InvalidOperationException("No GraphicsContext is current on the calling thread."); bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); gfx = Graphics.FromImage(bmp); // NOTE: TextRenderingHint.AntiAliasGridFit looks sharper and in most cases better // but it comes with a some problems. // // 1. Graphic.MeasureString and format.MeasureCharacterRanges // seem to return wrong values because of this. // // 2. While typing the kerning changes in random places in the sentence. // // Until 1st problem is fixed we should use TextRenderingHint.AntiAlias... :-( gfx.TextRenderingHint = TextRenderingHint.AntiAlias; gfx.Clear(Color.Transparent); texture = new Texture(renderer) {Width = width, Height = height}; }
//Render a Drawing public static void Render(DnaDrawing drawing,Graphics g,int scale) { g.Clear(Color.Black); foreach (DnaPolygon polygon in drawing.Polygons) Render(polygon, g, scale); }
//Render a Drawing public static void Render(DnaDrawing drawing,Graphics g,int scale) { g.Clear(Color.Black); foreach (DnaShape s in drawing.Shapes) s.Render(g, scale); }
void Former.new21file() { pixels = new PixelButton[64, 32]; map = new Bitmap(64,32); gra = Graphics.FromImage(map); gra.Clear(Color.Transparent); }
public void Draw(Graphics g) { g.Clear(Color.Gray); PointF cellSize = new PointF((float)Size.X / (ChessGameField.FIELD_SIZE), (float)Size.Y / (ChessGameField.FIELD_SIZE)); for (int i = 0; i <= ChessGameField.FIELD_SIZE; ++i) { g.DrawLine(Pens.Black, Pos.X + i * cellSize.X, Pos.Y, Pos.X + i * cellSize.X, Pos.Y + Size.Y); } for (int i = 0; i <= ChessGameField.FIELD_SIZE; ++i) { g.DrawLine(Pens.Black, Pos.X, Pos.Y + i * cellSize.Y, Pos.X + Size.X, Pos.Y + i * cellSize.Y); } Field.ForEachCell((pos, cell) => { if (cell.figure != null) cell.figure.Draw(g, GetColor(cell.figure.GetOwner()), GetCellPos(pos, cellSize), cellSize); return true; }); if (State == ActionState.Selected) { PointF pos = GetCellPos(SelectedPoint, cellSize); Pen pen = new Pen(Brushes.Green, 2); int border = 4; g.DrawRectangle(pen, new Rectangle((int)pos.X + border + 1, (int)pos.Y + border + 1, (int)cellSize.X - border*2, (int)cellSize.Y - border*2)); } }
void Galattron_Load(object sender, EventArgs e) { b=new Bitmap(484,461); g=Graphics.FromImage(b); g.Clear(Color.Black); pictureBox1.Image=b; }
private void wypelniony() { bmp = new Bitmap((int)pbWIDTH, (int)pbHEIGHT); Point p1 = new Point((int)(pbWIDTH / 6), (int)(pbHEIGHT / 2)); Point p2 = new Point((int)(pbWIDTH * 5 / 6), (int)(pbHEIGHT / 2)); Point p1_25 = new Point(pbWIDTH / 3, pbHEIGHT / 4 * 3); Point p2_25 = new Point((int)(pbWIDTH / 3 * 2), (int)(pbHEIGHT / 4 * 3)); Point p1_75 = new Point((int)(pbWIDTH / 3), (int)(pbHEIGHT / 4)); Point p2_75 = new Point((int)(pbWIDTH / 3 * 2), (int)(pbHEIGHT / 4)); Pen pen1 = new Pen(Brushes.Black, width_pen1); Pen pen2 = new Pen(Brushes.Black, width_pen2); g = Graphics.FromImage(bmp); g.Clear(Color.CornflowerBlue); g.FillRectangle(Brushes.White, new Rectangle(0, 0, pbWIDTH, pbHEIGHT - (int)(pbComplete * pbUnit))); g.DrawRectangle(pen1, 0, 0, pbWIDTH, pbHEIGHT); g.DrawLine(pen2, p1, p2); g.DrawLine(pen2, p1_25, p2_25); g.DrawLine(pen2, p1_75, p2_75); //g.DrawString(pbComplete + "%", new Font("Arial", pbHEIGHT / 5),Brushes.Black,new PointF(pbWIDTH/12,pbHEIGHT/4)); this.Image = bmp; //return bmp; }
//Render a Drawing public static void Render(DnaDrawing drawing,Graphics g,int scale) { g.Clear(Tools.avgColour); foreach (DnaPolygon polygon in drawing.Polygons) Render(polygon, g, scale); }
public void DrawInto(Graphics g) { int cellWidth = Width / puzzle.Size; int cellHeight = Height / puzzle.Size; g.Clear(Color.White); for (int x = 1; x <= puzzle.Size - 1; x++) { g.DrawLine(Pens.Black, new Point(cellWidth * x, 0), new Point(cellWidth * x, Height)); g.DrawLine(Pens.Black, new Point(0, cellHeight * x), new Point(Width, cellHeight * x)); } for (int i = 0; i < puzzle.Size; i++) { for (int j = 0; j < puzzle.Size; j++) { float y = cellHeight * i + cellHeight / 2 - font.Height / 2; float x = cellWidth * j + cellWidth / 2 - font.Size / 2; if (showSolution && puzzle.IsSolution(j, i)) g.FillRectangle(new SolidBrush(Color.FromArgb(100, Color.Yellow)), new Rectangle(new Point(cellWidth * j, cellHeight * i), new Size(cellWidth, cellHeight))); g.DrawString(puzzle[i, j].ToString(), font, Brushes.Black, new PointF(x, y)); } } }
public void DrawTitle(Graphics g, List<byte> data) { _currentData = data; _drawKind = DrawKind.Title; g.Clear(SystemColors.Control); Brush brush = new SolidBrush(Color.Gray); int x = _XOffset; int y = 0; int scale = Scale; int pos = 0; int length = data.Count; while (pos < length) { byte b1 = data[pos]; ++pos; y += scale; if (b1 == 11) { g.FillRectangle(brush, x, y, scale, scale); } if (b1 == 200) { y = 0; x += scale; } } }
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 (); }
/// <summary> /// 压缩图片,返回map /// </summary> /// <param name="width">宽度</param> /// <param name="height">高度</param> /// <returns></returns> public Bitmap ResizeImg(int width, int height) { if (_oldImg == null) return null; int ow = _oldImg.Width, oh = _oldImg.Height; //原始大小 if (height == -2) { var rale = (double)width / Math.Max(ow, oh); //压缩比例 width = (int)Math.Ceiling(ow * rale); height = (int)Math.Ceiling(oh * rale); } else { width = (width != -1 ? width : ow); height = (height != -1 ? height : oh); } var bm = new Bitmap(width, height, PixelFormat.Format32bppRgb); _newGraphics = Graphics.FromImage(bm); //呈现质量 _newGraphics.CompositingQuality = CompositingQuality.HighQuality; //像素偏移方式 _newGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality; //平滑处理 _newGraphics.SmoothingMode = SmoothingMode.HighQuality; //插补模式,双三次插值法 _newGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; _newGraphics.Clear(Color.Transparent); _newGraphics.DrawImage(_oldImg, new Rectangle(0, 0, width, height), new Rectangle(0, 0, ow, oh), GraphicsUnit.Pixel); //return "处理成功"; return bm; }
public void new22file() { pixels = new PixelButton[64, 64]; map = new Bitmap(64, 64); gra = Graphics.FromImage(map); gra.Clear(Color.Transparent); }
public override void DrawRect(System.Drawing.RectangleF dirtyRect) { Graphics g = new Graphics(); g.Clear(Color.White); int width = 30; int height = 128; int y = 10; // Create opaque color maps with alpha = 255: ColorMap cm = new ColorMap(); Font aFont = new Font("Arial", 20, FontStyle.Bold); g.DrawString("OPAQUE COLOR", aFont, Brushes.Black, 10, 60); DrawColorBar(g, 10, y, width, height, cm, "Spring"); DrawColorBar(g, 10 + 40, y, width, height, cm, "Summer"); DrawColorBar(g, 10 + 2 * 40, y, width, height, cm, "Autumn"); DrawColorBar(g, 10 + 3 * 40, y, width, height, cm, "Winter"); DrawColorBar(g, 10 + 4 * 40, y, width, height, cm, "Jet"); DrawColorBar(g, 10 + 5 * 40, y, width, height, cm, "Gray"); DrawColorBar(g, 10 + 6 * 40, y, width, height, cm, "Hot"); DrawColorBar(g, 10 + 7 * 40, y, width, height, cm, "Cool"); y = y + 150; // Create transparent color maps with alpha = 150: ColorMap cm1 = new ColorMap(64, 150); g.DrawString("TRANSPARENT COLOR", aFont, Brushes.Black, 10, 210); DrawColorBar(g, 10, y, width, height, cm1, "Spring"); DrawColorBar(g, 10 + 40, y, width, height, cm1, "Summer"); DrawColorBar(g, 10 + 2 * 40, y, width, height, cm1, "Autumn"); DrawColorBar(g, 10 + 3 * 40, y, width, height, cm1, "Winter"); DrawColorBar(g, 10 + 4 * 40, y, width, height, cm1, "Jet"); DrawColorBar(g, 10 + 5 * 40, y, width, height, cm1, "Gray"); DrawColorBar(g, 10 + 6 * 40, y, width, height, cm1, "Hot"); DrawColorBar(g, 10 + 7 * 40, y, width, height, cm1, "Cool"); }
//פונקציה שמשנה גודל לתמונות static System.Drawing.Image FixedSize(System.Drawing.Image imgPhoto, int Width, int Height) { int sourceWidth = Convert.ToInt32(imgPhoto.Width); int sourceHeight = Convert.ToInt32(imgPhoto.Height); int sourceX = 0; int sourceY = 0; int destX = 0; int destY = 0; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; nPercentW = ((float)Width / (float)sourceWidth); nPercentH = ((float)Height / (float)sourceHeight); if (nPercentH < nPercentW) { nPercent = nPercentH; destX = System.Convert.ToInt16((Width - (sourceWidth * nPercent)) / 2); } else { nPercent = nPercentW; destY = System.Convert.ToInt16((Height - (sourceHeight * nPercent)) / 2); } int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); System.Drawing.Bitmap bmPhoto = new System.Drawing.Bitmap(Width, Height, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); System.Drawing.Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto); grPhoto.Clear(System.Drawing.Color.White); grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new System.Drawing.Rectangle(destX, destY, destWidth, destHeight), new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), System.Drawing.GraphicsUnit.Pixel); grPhoto.Dispose(); return(bmPhoto); }
private static System.Drawing.Bitmap RotateImg (System.Drawing.Bitmap bmp, float angle) { angle = angle % 360; if (angle > 180) { angle -= 360; } float sin = (float)Math.Abs(Math.Sin(angle * Math.PI / 180.0)); // this function takes radians float cos = (float)Math.Abs(Math.Cos(angle * Math.PI / 180.0)); // this one too float newImgWidth = sin * bmp.Height + cos * bmp.Width; float newImgHeight = sin * bmp.Width + cos * bmp.Height; float originX = 0f; float originY = 0f; if (angle > 0) { if (angle <= 90) { originX = sin * bmp.Height; } else { originX = newImgWidth; originY = newImgHeight - sin * bmp.Width; } } else { if (angle >= -90) { originY = sin * bmp.Width; } else { originX = newImgWidth - sin * bmp.Height; originY = newImgHeight; } } System.Drawing.Bitmap newImg = new System.Drawing.Bitmap((int)newImgWidth, (int)newImgHeight); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newImg); g.Clear(System.Drawing.Color.White); g.TranslateTransform(originX, originY); // offset the origin to our calculated values g.RotateTransform(angle); // set up rotate g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; g.DrawImageUnscaled(bmp, 0, 0); // draw the image at 0, 0 g.Dispose(); return(newImg); }
public void makeThumbnail(string it, string Imageurl) { if (File.Exists(Server.MapPath("~/images/" + it + ".jpg"))) { return; } else { try { System.Net.WebRequest request = System.Net.WebRequest.Create(Imageurl); request.Timeout = 10000; System.Net.HttpWebResponse httpresponse = (System.Net.HttpWebResponse)request.GetResponse(); Stream s = httpresponse.GetResponseStream(); System.Drawing.Image img = System.Drawing.Image.FromStream(s); int towidth = 135; int toheight = 80; int x = 0; int y = 0; int ow = img.Width; int oh = img.Height; 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(img, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); try { bitmap.Save(Server.MapPath("~/images/" + it + ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { img.Dispose(); bitmap.Dispose(); g.Dispose(); } return; } catch { return; } } }
public static string createModel(String[] array) { if (array.Length > 0) { System.Drawing.Bitmap bm = new System.Drawing.Bitmap(400, array.Length * 90); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bm); g.Clear(System.Drawing.Color.White); int x = 100; int y = 10; System.Drawing.StringFormat f = new System.Drawing.StringFormat(); f.Alignment = System.Drawing.StringAlignment.Center; f.LineAlignment = System.Drawing.StringAlignment.Center; System.Drawing.Font font; System.Drawing.Drawing2D.LinearGradientBrush b = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Point(0, 40), new System.Drawing.Point(30, 130), System.Drawing.Color.GreenYellow, System.Drawing.Color.LemonChiffon); for (int i = 0; i < array.Length; i++) { font = new System.Drawing.Font("Arial Unicode MS", 10, System.Drawing.FontStyle.Regular); g.DrawImageUnscaled(System.Drawing.Image.FromFile(HttpContext.Current.Request.MapPath("tskOval.png")), x, y); g.DrawString(array[i].Substring(0, (array[i].Length > 52 ? 52 : array[i].Length)), font, System.Drawing.Brushes.Black, new System.Drawing.Rectangle(x + 30, y + 6, 172, 40), f); y += 85; } x = 100; y = 10; int y1, y2; for (int i = 1; i < array.Length; i++) { System.Drawing.Pen p = new System.Drawing.Pen(System.Drawing.Color.Black); p.Width = 1.5F; y1 = (((i) * 50) + y + ((i - 1) * 35)); y2 = (((i) * 50) + y + ((i) * 35)); g.DrawLine(p, 200, y1 + 2, 200, y2); System.Drawing.Point[] pns = new System.Drawing.Point[4]; pns[0] = new System.Drawing.Point(195, y2 - 5); pns[1] = new System.Drawing.Point(200, y2); pns[2] = new System.Drawing.Point(205, y2 - 5); pns[3] = new System.Drawing.Point(195, y2 - 5); g.FillPolygon(System.Drawing.Brushes.Black, pns); // g.DrawString(((Node)SessionClass.Flow[i-1]).decision.Equals("True")?"Yes":"No", new System.Drawing.Font("Arial Unicode MS", 9, System.Drawing.FontStyle.Regular), System.Drawing.Brushes.Black, new System.Drawing.Point(205, y1 +6)); } string res = HttpContext.Current.Server.MapPath("Results") + "\\User" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".png"; bm.Save(res, System.Drawing.Imaging.ImageFormat.Png); return("Results/" + res.Replace(HttpContext.Current.Server.MapPath("Results") + "\\", "")); } else { return(""); } }
//另存图片,并修改大小。 public static void SaveImage(string fromFile, string toFile, double newWidth, double newHeight) { try { System.Drawing.Image myimage = System.Drawing.Image.FromStream(new MemoryStream(File.ReadAllBytes(fromFile))); double oldWidth = myimage.Width; double oldHeight = myimage.Height; if (oldWidth > newWidth || oldHeight > newHeight) { if (myimage.Width >= myimage.Height) { oldHeight = newHeight; oldWidth = newHeight / myimage.Height * myimage.Width; } else { oldWidth = newWidth; oldHeight = newWidth / myimage.Width * myimage.Height; } } System.Drawing.Size mysize = new System.Drawing.Size((int)oldWidth, (int)oldHeight); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(mysize.Width, mysize.Height); 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(myimage, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(0, 0, myimage.Width, myimage.Height), System.Drawing.GraphicsUnit.Pixel); bitmap.Save(toFile, System.Drawing.Imaging.ImageFormat.Jpeg); g.Dispose(); bitmap.Dispose(); myimage.Dispose(); } catch { } }
public void AutoImage(string strCompanyName) { Int16 swidth = Convert.ToInt16(strCompanyName.Length * 13); System.Drawing.Bitmap objBMP = new System.Drawing.Bitmap(swidth, 30); System.Drawing.Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP); objGraphics.Clear(System.Drawing.Color.White); objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; //' Configure font to use for text System.Drawing.Font objFont = new System.Drawing.Font("Arial", 15, System.Drawing.FontStyle.Bold); string randomStr = strCompanyName; int[] myIntArray = new int[6]; int x; //That is to create the random # and add it to our string //Random autoRand = new Random(); //for (x = 0; x < 6; x++) //{ // myIntArray[x] = System.Convert.ToInt32(autoRand.Next(0, 9)); // randomStr += (myIntArray[x].ToString()); //} //This is to add the string to session cookie, to be compared later //' Write out the text objGraphics.DrawString(strCompanyName, objFont, System.Drawing.Brushes.Black, 3, 3); //' Set the content type and return the image //Response.ContentType = "image/GIF"; File.Delete(HttpContext.Current.Server.MapPath("~\\provider\\LogoImages\\Default.jpg")); objBMP.Save(HttpContext.Current.Server.MapPath("~\\provider\\LogoImages\\Default.jpg"), objBMP.RawFormat); objFont.Dispose(); objGraphics.Dispose(); objBMP.Dispose(); }
//图片上传 protected void btnSubmit_Click(object sender, EventArgs e) { ClearMethod(); HttpPostedFile hpf = uploadImage.PostedFile; //取得文件名,不含路径 char[] splitChar = { '\\' }; string[] FilenameArray = hpf.FileName.Split(splitChar); string Filename = FilenameArray[FilenameArray.Length - 1].ToLower(); //将用户输入的水印文字处理 //string sMessage = lineStr(TextBox3.Text.Trim().ToString(), 20); if (hpf.FileName.Length < 1) { panelAttention.Visible = true; lbAttention.Text = "请选择你要上传的图片文件"; return; } if (hpf.ContentType != "image/jpeg" && hpf.ContentType != "image/gif") { panelAttention.Visible = true; lbAttention.Text = "只允许上传JPEG GIF文件"; return; } else { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(DateTime.Now.Year.ToString()); sb.Append(DateTime.Now.Month.ToString()); sb.Append(DateTime.Now.Day.ToString()); sb.Append(DateTime.Now.Hour.ToString()); sb.Append(DateTime.Now.Minute.ToString()); sb.Append(DateTime.Now.Second.ToString()); if (Filename.ToLower().EndsWith("gif")) { sb.Append(".gif"); } else if (Filename.ToLower().EndsWith("jpg")) { sb.Append(".jpg"); } else if (Filename.ToLower().EndsWith("jpeg")) { sb.Append(".jpeg"); } Filename = sb.ToString(); //保存图片到服务器上 try { hpf.SaveAs(Server.MapPath("~") + "/images/onsale/wear/big_" + Filename); } catch (Exception ee) { panelAttention.Visible = true; lbAttention.Text = "上传图片失败,原因:" + ee.Message; return; } //生成缩略图 //原始图片名称 string originalFilename = hpf.FileName; //生成高质量图片名称 string strFile = Server.MapPath("~") + "/images/onsale/wear/small/small_" + Filename; //从文件获取图片对象 System.Drawing.Image image = System.Drawing.Image.FromStream(hpf.InputStream, true); Double Width = Double.Parse(TextBox1.Text.Trim()); Double Height = Double.Parse(TextBox2.Text.Trim()); System.Double newWidth, newHeight; if (image.Width > image.Height) { newWidth = Width; newHeight = image.Height * (newWidth / image.Width); } else { newHeight = Height; newWidth = image.Width * (newHeight / image.Height); } if (newWidth > Width) { newWidth = Width; } if (newHeight > Height) { newHeight = Height; } System.Drawing.Size size = new System.Drawing.Size((int)newWidth, (int)newHeight); //设置图片的宽度和高度 System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height); //新建bmp图片 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.White); //清空画布 //在制定位置画图 g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.GraphicsUnit.Pixel); //文字水印 System.Drawing.Graphics testGrahpics = System.Drawing.Graphics.FromImage(bitmap); System.Drawing.Font font = new System.Drawing.Font("宋体", 10); System.Drawing.Brush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); //分行 string sInput = TextBox3.Text.Trim().ToString(); //获取输入的水印文字 int coloum = Convert.ToInt32(TextBox4.Text); //获取每行的字符数 //利用循环,来依次输出 for (int i = 0, j = 0; i < sInput.Length; i += coloum, j++) { //若要修改水印文字在照片上的位置,可将20修改成你想要的任何值 if (j != sInput.Length / coloum) { string s = sInput.Substring(i, coloum); testGrahpics.DrawString(s, font, brush, 20, 20 * (i / coloum + 1)); } else { string s = sInput.Substring(i, sInput.Length % coloum); testGrahpics.DrawString(s, font, brush, 20, 20 * (j + 1)); } } testGrahpics.Dispose(); //保存缩略图c try { bitmap.Save(strFile, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception ex) { paneInfo.Visible = true; lbInfo.Text = "保存缩略图失败" + ex.Message; } //释放资源 g.Dispose(); bitmap.Dispose(); image.Dispose(); } Entity.PicturesItem pic = new Entity.PicturesItem(); pic.setItemID(int.Parse(lbItemId.Text)); // pic.setIntImageID(int.Parse(lbImageID.Text)); pic.setBigImg("images/onsale/wear/big_" + Filename); pic.setSmallImg("images/onsale/wear/small/small_" + Filename); pic.setAlt(""); switch (btnSubmit.Text) { case "新增": //新增模式 if (picture.InserItemsPic(pic)) { panelSuccess.Visible = true; lbSuccess.Text = "新增图片成功!"; } else { panelError.Visible = true; lbError.Text = "新增图片失败!"; } break; case "修改": //修改模式 //int.Parse(lbImageID.Text), int.Parse(lbItemId.Text), "images/onsale/wear/big_" + Filename, "images/onsale/wear/small/small_" + Filename, "" if (picture.UpdatePicByID(pic)) { panelSuccess.Visible = true; lbSuccess.Text = "修改图片成功!"; } else { panelError.Visible = true; lbError.Text = "修改图片失败!"; } break; } }
/// <summary> /// 图片等比缩放并添加水印 /// </summary> /// <param name="postedFile">原图HttpPostedFile对象</param> /// <param name="savePath">缩略图存放地址</param> /// <param name="targetWidth">指定的最大宽度</param> /// <param name="targetHeight">指定的最大高度</param> /// <param name="watermarkText">水印文字(为""表示不使用水印)</param> /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param> /// <param name="waterTextFont">文字水印字体</param> public static void ZoomAuto(System.Web.HttpPostedFile postedFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText, string watermarkImage, Font waterTextFont) { //创建目录 string dir = Path.GetDirectoryName(savePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } if (waterTextFont == null) { waterTextFont = new Font("黑体", 14, GraphicsUnit.Pixel); } //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= targetWidth && initImage.Height <= targetHeight) { //文字水印 if (watermarkText != "") { using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage)) { System.Drawing.Font fontWater = waterTextFont; 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 = waterTextFont; 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="bitmap"></param> /// <param name="w"></param> /// <param name="h"></param> /// <param name="mode"></param> /// <returns></returns> public static Image TBScaleBitmap(Image bitmap, int w, int h, string mode) { Bitmap map = new Bitmap(w, h); System.Drawing.Graphics gra = System.Drawing.Graphics.FromImage(map); gra.Clear(System.Drawing.Color.Transparent); //清空画布并以透明背景色填充 gra.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //使绘图质量最高,即消除锯齿 gra.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; gra.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gra.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; gra.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; int towidth = w; int toheight = h; int x = 0; int y = 0; int ow = bitmap.Width; int oh = bitmap.Height; switch (mode) { case "HW": //指定高宽缩放(可能变形) break; case "W": //指定宽,高按比例 toheight = bitmap.Height * w / bitmap.Width; break; case "H": //指定高,宽按比例 towidth = bitmap.Width * h / bitmap.Height; break; case "Cut": //指定高宽裁减(不变形) if ((double)bitmap.Width / (double)bitmap.Height > (double)towidth / (double)toheight) { oh = bitmap.Height; ow = bitmap.Height * towidth / toheight; y = 0; x = (bitmap.Width - ow) / 2; } else { ow = bitmap.Width; oh = bitmap.Width * h / towidth; x = 0; y = (bitmap.Height - oh) / 2; } break; case "MaxHW": //最大宽高比例缩放,比如原100*50->50*30,则结果是50*25 var rmaxhw_d1w = bitmap.Width * 1.0 / w; var rmaxhw_d2h = bitmap.Height * 1.0 / h; if (rmaxhw_d1w > rmaxhw_d2h) { if (rmaxhw_d1w <= 1) { towidth = bitmap.Width; h = bitmap.Height; goto case "HW"; } towidth = w; goto case "W"; } if (rmaxhw_d2h <= 1) { towidth = bitmap.Width; h = bitmap.Height; goto case "HW"; } toheight = h; goto case "H"; default: break; } gra.DrawImage(bitmap, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); gra.Flush(); gra.Dispose(); bitmap.Dispose(); return(map); }
public override System.Drawing.Bitmap GetNext() { System.Drawing.Bitmap result; lock (this.newBitmap) { lock (this.oldBitmap) { if (this.nowState == MarqueeDisplayState.First) { this.nowPositionF += this.step; if (this.nowPositionF > (float)((this.newBitmap.Height + this.newBitmap.Width) / 2)) { this.nowState = MarqueeDisplayState.Stay; } this.nowPosition = (int)this.nowPositionF; this.getPoint1(this.nowPosition); this.getPoint2(this.nowPosition); this.getPoint3(this.nowPosition); this.getPoint4(this.nowPosition); } else { if (this.nowState == MarqueeDisplayState.Stay) { this.StayNum += 42; if (this.StayNum > this.effect.Stay) { if (this.effect.ExitMode == 0) { result = null; return(result); } this.nowState = MarqueeDisplayState.Exit; } result = new System.Drawing.Bitmap(this.newBitmap); return(result); } if (this.nowState == MarqueeDisplayState.Exit) { result = this.Exit.GetNext(); return(result); } } System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(this.oldBitmap); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap); System.Drawing.Bitmap image = new System.Drawing.Bitmap(this.newBitmap); System.Drawing.Graphics graphics2 = System.Drawing.Graphics.FromImage(image); System.Drawing.Drawing2D.GraphicsPath graphicsPath = new System.Drawing.Drawing2D.GraphicsPath(); graphicsPath.AddPolygon(this.pa1); graphics2.SetClip(graphicsPath); graphics2.Clear(System.Drawing.Color.Transparent); graphicsPath.ClearMarkers(); graphicsPath.AddPolygon(this.pa2); graphics2.SetClip(graphicsPath); graphics2.Clear(System.Drawing.Color.Transparent); graphicsPath.ClearMarkers(); graphicsPath.AddPolygon(this.pa3); graphics2.SetClip(graphicsPath); graphics2.Clear(System.Drawing.Color.Transparent); graphicsPath.ClearMarkers(); graphicsPath.AddPolygon(this.pa4); graphics2.SetClip(graphicsPath); graphics2.Clear(System.Drawing.Color.Transparent); graphics.DrawImage(image, new System.Drawing.Point(0, 0)); result = bitmap; } } return(result); }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="thumbnailMode">生成缩略图的方式</param> public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, ThumbnailMode thumbnailMode) { 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 (thumbnailMode) { case ThumbnailMode.None: if (ow > oh) { toheight = originalImage.Height * width / originalImage.Width; } else if (oh > ow) { towidth = originalImage.Width * height / originalImage.Height; } break; case ThumbnailMode.HW: //指定高宽缩放(可能变形) break; case ThumbnailMode.W: //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case ThumbnailMode.H: //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case ThumbnailMode.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; } 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 { thumbnailPath = thumbnailPath.Replace("/", "\\"); string savePath = thumbnailPath.Substring(0, thumbnailPath.LastIndexOf("\\")); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } bitmap.Save(thumbnailPath, GetImageFormat(thumbnailPath)); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } }
/// <summary> /// 生成缩略图(最终图片固定大小,图片按比例缩小,并为缩略图加上边框,以jpg格式保存) /// </summary> /// <param name="sourceImg">原图片(物理路径)</param> /// <param name="toPath">缩略图存放地址(物理路径,带文件名)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="backColor">如果图片按比例缩小后不能填充满缩略图,则使用此颜色填充(比如"#FFFFFF")</param> public static void MakePic(string sourceImg, string toPath, int width, int height, string backColor) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(sourceImg); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; string mode; if (ow < towidth && oh < toheight) { towidth = ow; toheight = oh; } else { if (originalImage.Width / originalImage.Height >= width / height) { mode = "W"; } else { mode = "H"; } switch (mode) { case "W": //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H": //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; default: break; } } //新建一个bmp图片 System.Drawing.Image bitmap = new System.Drawing.Bitmap(width, height); //新建一个画板 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(ColorTranslator.FromHtml(backColor)); //在指定位置并且按指定大小绘制原图片的指定部分 int top = (height - toheight) / 2; int left = (width - towidth) / 2; g.DrawImage(originalImage, new System.Drawing.Rectangle(left, top, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); //Pen pen = new Pen(ColorTranslator.FromHtml(borderColor)); //g.DrawRectangle(pen, 0, 0, width - 1, height - 1); try { //以jpg格式保存缩略图 bitmap.Save(toPath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (System.Exception e) { throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } }
/// <summary> /// 正方型裁剪 /// 以图片中心为轴心,截取正方型,然后等比缩放 /// 用于头像处理 /// </summary> /// <param name="postedFile">原图HttpPostedFile对象</param> /// <param name="fileSaveUrl">缩略图存放地址</param> /// <param name="side">指定的边长(正方型)</param> /// <param name="quality">质量(范围0-100)</param> public static void CutForSquare(System.Web.HttpPostedFile postedFile, 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(postedFile.InputStream, 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> /// Draw all entities stored in buffer /// </summary> public void Flush() { // initialize Vector3D vLight = _vCameraPos - _vTarget; vLight.Normalize(); _boxDrawingCounter = 0; _currentTransf = null; System.Drawing.Graphics g = Graphics; g.Clear(_backgroundColor); if (EnableFaceSorting) { // sort face list FaceComparison faceComparer = new FaceComparison(GetWorldToEyeTransformation()); _faces.Sort(faceComparer); } // draw background segments foreach (Segment s in _segmentsBackground) { Draw(s); } // draw background faces foreach (Face face in _facesBackground) { Draw(face, FaceDir.FRONT); } // draw all faces using solid / transparency depending on foreach (Face face in _faces) { Draw(face, FaceDir.BACK); } // sort box list if (_useBoxelOrderer) { BoxelOrderer boxelOrderer = new BoxelOrderer(_boxes); boxelOrderer.Direction = _vTarget - _vCameraPos; _boxes = boxelOrderer.GetSortedList(); } else { _boxes.Sort(new BoxComparerSimplifiedPainterAlgo(GetWorldToEyeTransformation())); } // sort cylinder list _cylinders.Sort(new CylinderComparerSimplifiedPainterAlgo(GetWorldToEyeTransformation())); if (_cylinders.Count > 0) { // sort by Z List <Drawable> drawableList = new List <Drawable>(); drawableList.AddRange(_boxes); drawableList.AddRange(_cylinders); drawableList.Sort(new DrawableComparerSimplifiedPainterAlgo()); List <Box> boxes = new List <Box>(); List <Cylinder> cylinders = new List <Cylinder>(); bool processingBox = drawableList[0] is Box; foreach (Drawable drawable in drawableList) { Box b = drawable as Box; Cylinder c = drawable as Cylinder; if ((null != b) && processingBox) { boxes.Add(b); } else if ((null == b) && !processingBox) { cylinders.Add(c); } else { if (boxes.Count > 0) { BoxelOrderer boxelOrderer = new BoxelOrderer(boxes); boxelOrderer.Direction = _vTarget - _vCameraPos; boxes = boxelOrderer.GetSortedList(); // draw boxes foreach (Box bb in boxes) { Draw(bb); } // clear boxes.Clear(); } if (cylinders.Count > 0) { cylinders.Sort(new CylinderComparerSimplifiedPainterAlgo(GetWorldToEyeTransformation())); // draw cylinders foreach (Cylinder cc in cylinders) { Draw(cc); } // clear cylinders.Clear(); } if (null != b) { boxes.Add(b); processingBox = true; } else { cylinders.Add(c); processingBox = false; } } } // remaining boxes BoxelOrderer boxelOrdererRem = new BoxelOrderer(boxes); boxelOrdererRem.Direction = _vTarget - _vCameraPos; boxes = boxelOrdererRem.GetSortedList(); // draw boxes foreach (Box bb in boxes) { Draw(bb); } // remaining cylinders cylinders.Sort(new CylinderComparerSimplifiedPainterAlgo(GetWorldToEyeTransformation())); // draw cylinders foreach (Cylinder cc in cylinders) { Draw(cc); } // clear boxes.Clear(); } else { // draw all boxes foreach (Box box in _boxes) { Draw(box); } } // images inst if (_listImageInst.Count > 0) { // --- sort image inst Analysis analysis = _listImageInst[0].Analysis; BBox3D bbox = analysis.Solution.BBoxGlobal; List <Box> boxesImage = new List <Box>(); foreach (ImageInst imageInst in _listImageInst) { boxesImage.Add(imageInst.ToBox()); } if (_useBoxelOrderer && false) // NOT WORKING ? { BoxelOrderer boxelOrderer = new BoxelOrderer(boxesImage); boxelOrderer.TuneParam = 10.0; boxelOrderer.Direction = _vTarget - _vCameraPos; boxesImage = boxelOrderer.GetSortedList(); } else { boxesImage.Sort(new BoxComparerSimplifiedPainterAlgo(GetWorldToEyeTransformation())); } // --- List <ImageInst> listImageInstSorted = new List <ImageInst>(); foreach (Box b in boxesImage) { listImageInstSorted.Add(new ImageInst(analysis, new Vector3D(b.Length, b.Width, b.Height), b.BPosition)); } // draw image inst foreach (ImageInst im in listImageInstSorted) { Draw(im); } } // draw faces : end foreach (Face face in _faces) { Draw(face, FaceDir.FRONT); } // draw segment list (e.g. hatching) foreach (Segment seg in _segments) { Draw(seg); } // draw cotation cubes if (ShowDimensions) { foreach (DimensionCube qc in _dimensions) { qc.Draw(this); } } }
// originally from https://stackoverflow.com/questions/2042155/high-quality-graph-waveform-display-component-in-c-sharp, // adapted to use the pcm_f32le format and replace GDI+ with WPF drawing private BitmapSource _Draw_GDI(CancellationToken ct, double height, double width) { isDrawing = true; reader.Position = 0; int bytesPerSample = (reader.WaveFormat.BitsPerSample / 8) * reader.WaveFormat.Channels; //Give a size to the bitmap; either a fixed size, or something based on the length of the audio System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)width, (int)height); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed; graphics.Clear(System.Drawing.Color.Transparent); System.Drawing.Pen bluePen = new System.Drawing.Pen(Constants.Editor.Waveform.ColourGDI); int samplesPerPixel = (int)(reader.Length / (double)(height * bytesPerSample)); int bytesPerPixel = bytesPerSample * samplesPerPixel; int bytesRead; byte[] waveData = new byte[bytesPerPixel]; // draw each pixel of height for (int y = 0; y < height; y++) { bytesRead = reader.Read(waveData, 0, bytesPerPixel); if (bytesRead == 0) { break; } float low = 0; float high = 0; // read all samples for this pixel and take the extreme values for (int n = 0; n < bytesRead; n += bytesPerSample) { float sample = BitConverter.ToSingle(waveData, n); if (sample < low) { low = sample; } if (sample > high) { high = sample; } if (ct.IsCancellationRequested) { isDrawing = false; return(null); } } float lowPercent = (low + 1) / 2; float highPercent = (high + 1) / 2; float lowValue = (float)width * lowPercent; float highValue = (float)width * highPercent; graphics.DrawLine(bluePen, lowValue, (int)height - y, highValue, (int)height - y); } //bitmap.Save("out.bmp"); // https://stackoverflow.com/questions/94456/load-a-wpf-bitmapimage-from-a-system-drawing-bitmap#1069509 BitmapSource b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight((int)width, (int)height)); b.Freeze(); isDrawing = false; return(b); }
private void CreateCheckCodeImage(string checkCode) { if (checkCode == null || checkCode.Trim() == String.Empty) { return; } System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 15.0 + 40)), 23); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); try { //生成随机生成器 Random random = new Random(); //清空图片背景色 g.Clear(System.Drawing.Color.White); //画图片的背景噪音线 for (int i = 0; i < 25; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2); } System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true); int cySpace = 16; for (int i = 0; i < validateCodeCount; i++) { g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1); } //画图片的前景噪音点 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next())); } //画图片的边框线 g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); Response.ClearContent(); Response.ContentType = "image/Gif"; Response.BinaryWrite(ms.ToArray()); } finally { g.Dispose(); image.Dispose(); } }
/// <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(); } }
void Pbox_RandomMouseLeave(object sender, EventArgs e) { formGraphics.Clear(this.BackColor); }
/// <summary> /// 指定长宽裁剪 /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸 /// </summary> /// <param name="postedFile">原图HttpPostedFile对象</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.Web.HttpPostedFile postedFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality) { //从文件获取原始图片,并使用流中嵌入的颜色管理信息 System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, 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)Math.Floor(initImage.Width / templateRate)); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //裁剪源定位 fromR.X = 0; fromR.Y = (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2); fromR.Width = initImage.Width; fromR.Height = (int)Math.Floor(initImage.Width / templateRate); //裁剪目标定位 toR.X = 0; toR.Y = 0; toR.Width = initImage.Width; toR.Height = (int)Math.Floor(initImage.Width / templateRate); } //高为标准进行裁剪 else { pickedImage = new System.Drawing.Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height); pickedG = System.Drawing.Graphics.FromImage(pickedImage); fromR.X = (int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2); fromR.Y = 0; fromR.Width = (int)Math.Floor(initImage.Height * templateRate); fromR.Height = initImage.Height; toR.X = 0; toR.Y = 0; toR.Width = (int)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> /// Paint. /// </summary> /// <param name="g"></param> /// <param name="w"></param> /// <param name="h"></param> protected void paintGraph(System.Drawing.Graphics g, int w, int h) { short ux = 0; short lx = 0; short uy = 0; short ly = 0; bool foundFirst = false; List <string> legend = new List <string>(); List <Color> colors = new List <Color>(); for (int i = 0; i < Lines.Count; i++) { if (Lines[i] == null) { continue; } if (Lines[i].Show == false) { continue; } if (!foundFirst) { ux = Lines[i].MaxX; lx = Lines[i].MinX; uy = Lines[i].MaxY; ly = Lines[i].MinY; foundFirst = true; } legend.Add(Lines[i].Name); colors.Add(Lines[i].LineColor); ux = ux > Lines[i].MaxX ? ux : Lines[i].MaxX; lx = lx < Lines[i].MinX ? lx : Lines[i].MinX; uy = uy > Lines[i].MaxY ? uy : Lines[i].MaxY; ly = ly < Lines[i].MinY ? ly : Lines[i].MinY; } g.Clear(BackColor);//??? Rectangle drawRectangle = new Rectangle(0, 0, w, h); if (ShowLegend) { int legendHeight = 5 + (int)g.MeasureString("AjtW", Font).Height; if (h - legendHeight > 10) { drawRectangle = new Rectangle(0, 0, w, h - legendHeight); Rectangle legendRectangle = new Rectangle(0, h - legendHeight + 2, w, legendHeight - 2); drawLegend(g, legendRectangle, legend, colors); } } if (ShowAxis) { Font font = new Font("Arial", 9, FontStyle.Regular); LinearGradientBrush lgBrush = new LinearGradientBrush(drawRectangle, Color.Gray, Color.Gray, 1.2f, true); Pen darkPen = new Pen(Color.Gray, 2); Pen lightPen = new Pen(Color.Gray, 1); Pen axisPen = new Pen(Color.Black, 3); Pen buildPen = new Pen(lgBrush, 1); // 画纵线以及X轴坐标 int leftX = 60; //最左边的纵线距离图像左边的距离 g.DrawLine(axisPen, leftX, 50, leftX, drawRectangle.Height - 32); //Y轴 g.DrawString("0", font, Brushes.Black, leftX, drawRectangle.Height - 24); for (int i = 1; i <= 640 / 16; i++) { leftX += 16; if (i % 4 == 0) { g.DrawLine(darkPen, leftX, 50, leftX, drawRectangle.Height - 32); g.DrawString((i * 16).ToString(), font, Brushes.Black, leftX - 10, drawRectangle.Height - 24); } else { g.DrawLine(lightPen, leftX, 50, leftX, drawRectangle.Height - 32); } } // 画横线及Y轴坐标 int topY = 50; //最上边的横线距离图像顶部的距离 string[] y = new string[] { "35000", "30000", "25000", "20000", "15000", "10000", "5000", " 0", "-5000" }; for (int i = 0; i < 28; i++) { g.DrawLine(buildPen, 60, topY, 720, topY); if (i % 4 == 0) { g.DrawLine(darkPen, 60, topY, 720, topY); g.DrawString(y[i / 4], font, Brushes.Black, 10, topY); } else { g.DrawLine(lightPen, 60, topY, 720, topY); } topY += (drawRectangle.Height - 50 - 30) / 32; } g.DrawLine(axisPen, 20, topY, 720, topY); //X轴 //g.DrawString("0", font, Brushes.Black, 10, topY); topY += (drawRectangle.Height - 50 - 30) / 32; for (int i = 29; i < 33; i++) { if (i % 4 == 0) { g.DrawString(y[i / 4], font, Brushes.Black, 10, topY); g.DrawLine(darkPen, 60, topY, 720, topY); } else { g.DrawLine(lightPen, 60, topY, 720, topY); } topY += (drawRectangle.Height - 50 - 30) / 32; } //g.DrawLine(buildPen, 60, topY, 760, topY); //最底下的横线 //g.DrawString(y[8].ToString(), font, Brushes.Black, 10, topY); } if (!foundFirst) { return; } for (int i = 0; i < Lines.Count; i++) { if (Lines[i] == null) { continue; } if (Lines[i].Show == false) { continue; } Lines[i].Draw(g, drawRectangle, lx, ux, ly, uy); } }
private void kola(int n, int [,] A) { System.Drawing.Graphics formGraphics = this.CreateGraphics(); System.Drawing.Graphics formGraphics1 = this.CreateGraphics(); formGraphics.Clear(System.Drawing.Color.White); System.Drawing.Pen myPen; System.Drawing.Pen myPen1; myPen = new System.Drawing.Pen(System.Drawing.Color.Black); myPen1 = new System.Drawing.Pen(System.Drawing.Color.Red); int[] a = new int[2]; a[0] = 20; a[1] = 100; int[] b = new int[2]; b[0] = 70; b[1] = 50; int[] c = new int[2]; c[0] = 70; c[1] = 150; int [] L = new int[2 * n]; int k = 0; System.Drawing.Font drawFont = new System.Drawing.Font( "Arial", 16); System.Drawing.SolidBrush drawBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Black); string txt; for (int i = 0; i < n; i += 0) { if (i == 0 || i == n - 1) { formGraphics.DrawEllipse(myPen, a[0], a[1], 30, 30); ++i; txt = i.ToString(); formGraphics.DrawString(txt, drawFont, drawBrush, a[0], a[1]); L[k] = a[0]; L[k + 1] = a[1]; k += 2; } else { formGraphics.DrawEllipse(myPen, b[0], b[1], 30, 30); ++i; txt = i.ToString(); formGraphics.DrawString(txt, drawFont, drawBrush, b[0], b[1]); L[k] = b[0]; L[k + 1] = b[1]; k += 2; formGraphics.DrawEllipse(myPen, c[0], c[1], 30, 30); ++i; txt = i.ToString(); formGraphics.DrawString(txt, drawFont, drawBrush, c[0], c[1]); L[k] = c[0]; L[k + 1] = c[1]; k += 2; a[0] += 100; b[0] += 100; c[0] += 100; } } drawFont.Dispose(); drawBrush.Dispose(); for (int i = 0; i < n; i += 2) { Parallel.Invoke( () => { for (int j = 0; j < n; ++j) { if (i == j) { continue; } if (A[i, j] == 1) { formGraphics.DrawLine(myPen, L[2 * i] + 15, L[2 * i + 1] + 15, L[2 * j] + 15, L[2 * j + 1] + 15); } } }, () => { for (int j = 0; j < n; ++j) { if (i == j) { continue; } if (A[i, j] == 1) { formGraphics1.DrawLine(myPen1, L[2 * (i + 1)] + 15, L[2 * (i + 1) + 1] + 15, L[2 * j] + 15, L[2 * j + 1] + 15); } } } ); } myPen.Dispose(); myPen1.Dispose(); formGraphics.Dispose(); formGraphics1.Dispose(); }
/// <summary> /// 生成图片验证码 /// </summary> /// <param name="checkCode"></param> public void CreateCheckCodeImage(string[] checkCode) { if (checkCode == null || checkCode.Length <= 0) { return; } System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 32.5)), 30); System.Drawing.Graphics g = Graphics.FromImage(image); try { Random random = new Random(); //清空图片背景色 g.Clear(Color.White); //画图片的背景噪音线 for (int i = 0; i < 20; i++) { int x1 = random.Next(image.Width); int x2 = random.Next(image.Width); int y1 = random.Next(image.Height); int y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } //定义颜色 Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple }; //定义字体 string[] f = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; for (int k = 0; k <= checkCode.Length - 1; k++) { int cindex = random.Next(7); int findex = random.Next(5); Font drawFont = new Font(f[findex], 16, (System.Drawing.FontStyle.Bold)); SolidBrush drawBrush = new SolidBrush(c[cindex]); float x = 5.0F; float y = 0.0F; float width = 20.0F; float height = 25.0F; int sjx = random.Next(10); int sjy = random.Next(image.Height - (int)height); RectangleF drawRect = new RectangleF(x + sjx + (k * 25), y + sjy, width, height); StringFormat drawFormat = new StringFormat(); drawFormat.Alignment = StringAlignment.Center; g.DrawString(checkCode[k], drawFont, drawBrush, drawRect, drawFormat); } //画图片的前景噪音点 for (int i = 0; i < 100; i++) { int x = random.Next(image.Width); int y = random.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(random.Next())); } //画图片的边框线 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //System.Web.HttpContext.Current.Response.ClearContent(); System.Web.HttpContext.Current.Response.ContentType = "image/Gif"; System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray()); } finally { g.Dispose(); image.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); return(Image.FromStream(s)); }
public Form1() { InitializeComponent(); g = pictureBox1.CreateGraphics(); g.Clear(Color.White); }
/// <summary> /// 指定长宽裁剪 /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸 /// </summary> /// <remarks>吴剑 2010-11-15</remarks> /// <param name="postedFile">原图HttpPostedFile对象</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) { //从文件获取原始图片,并使用流中嵌入的颜色管理信息 //System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width < maxWidth && initImage.Height < maxHeight) { Bitmap _newBitmap = new Bitmap(maxWidth, maxHeight); // _newBitmap.MakeTransparent(Color.White); // _newBitmap.(Color.Transparent); Graphics _graphics = Graphics.FromImage(_newBitmap); _graphics.Clear(Color.White); //_graphics.DrawImage(Image.FromFile(@"F:\backImage.bmp"), 0, 0, 240, 320); // Image sourceImg = initImage; _graphics.DrawImage(initImage, (maxWidth - initImage.Width) / 2, (maxHeight - initImage.Height) / 2); // _graphics.DrawString("菜鸟先飞",new Font( FontFamily.GenericMonospace,12), Brushes.Yellow, 0, 0); //_graphics.Clear(Color.White); //_graphics.Save(); _newBitmap.Save(fileSaveUrl, ImageFormat.Jpeg); _graphics.Dispose(); _newBitmap.Dispose(); } 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.Png); } //原图与模版比例不等,裁剪后缩放 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)Math.Floor(initImage.Width / templateRate)); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //裁剪源定位 fromR.X = 0; fromR.Y = (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2); fromR.Width = initImage.Width; fromR.Height = (int)Math.Floor(initImage.Width / templateRate); //裁剪目标定位 toR.X = 0; toR.Y = 0; toR.Width = initImage.Width; toR.Height = (int)Math.Floor(initImage.Width / templateRate); } //高为标准进行裁剪 else { pickedImage = new System.Drawing.Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height); pickedG = System.Drawing.Graphics.FromImage(pickedImage); fromR.X = (int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2); fromR.Y = 0; fromR.Width = (int)Math.Floor(initImage.Height * templateRate); fromR.Height = initImage.Height; toR.X = 0; toR.Y = 0; toR.Width = (int)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); SetPicThumbnail(templateImage, fileSaveUrl, quality); //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); //释放资源 templateG.Dispose(); templateImage.Dispose(); pickedG.Dispose(); pickedImage.Dispose(); } } //释放资源 initImage.Dispose(); }
/// asp.net上传图片并生成缩略图 /// </summary> /// <param name="upImage">HtmlInputFile控件</param> /// <param name="sSavePath">保存的路径,些为相对服务器路径的下的文件夹</param> /// <param name="sThumbExtension">缩略图的thumb</param> /// <param name="intThumbWidth">生成缩略图的宽度</param> /// <param name="intThumbHeight">生成缩略图的高度</param> /// <returns>缩略图名称</returns> public string UpLoadImage(HttpPostedFile myFile, string sSavePath, int intThumbWidth, int intThumbHeight, string ofileName) { string sFilename = ""; if (myFile != null && myFile.ContentLength > 0) { // HttpPostedFile myFile = upImage.PostedFile; int nFileLen = myFile.ContentLength; // if (nFileLen == 0) // return "没有选择上传图片"; //获取upImage选择文件的扩展名 string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower(); //判断是否为图片格式 if (extendName != ".jpg" && extendName != ".jpge" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png") { return("false"); } byte[] myData = new Byte[nFileLen]; myFile.InputStream.Read(myData, 0, nFileLen); //保存文件名 sFilename = ofileName + extendName;// System.IO.Path.GetFileName(myFile.FileName); string datetime = DateTime.Now.ToString("yyyy-MM"); if (!System.IO.Directory.Exists(sSavePath + datetime + "/")) { System.IO.Directory.CreateDirectory(sSavePath + datetime + "/"); } int file_append = 0; //检查当前文件夹下是否有同名图片,有则在文件名+1 while (System.IO.File.Exists(sSavePath + datetime + "/" + sFilename)) { File.Delete(StringPlus.MapPath(sSavePath + datetime + "/" + sFilename)); //file_append++; //sFilename = System.IO.Path.GetFileNameWithoutExtension(sFilename) // + file_append.ToString() + extendName; } System.IO.FileStream newFile = new System.IO.FileStream((sSavePath + datetime + "/" + sFilename), System.IO.FileMode.Create, System.IO.FileAccess.Write); newFile.Write(myData, 0, myData.Length); newFile.Close(); //以上为上传原图 try { //原图加载 using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(sSavePath + datetime + "/" + sFilename)) { //原图宽度和高度 int width = sourceImage.Width; int height = sourceImage.Height; int smallWidth; int smallHeight; //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽 和 原图的高/缩略图的高) if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight) { smallWidth = intThumbWidth; smallHeight = intThumbWidth * height / width; } else { smallWidth = intThumbHeight * width / height; smallHeight = intThumbHeight; } //判断缩略图在当前文件夹下是否同名称文件存在 file_append = 0; // sThumbFile =myFile.FileName ; sFilename = "s_" + sFilename; if (!System.IO.Directory.Exists(sSavePath + datetime + "/")) { System.IO.Directory.CreateDirectory(sSavePath + datetime + "/"); } while (System.IO.File.Exists(sSavePath + datetime + "/" + sFilename)) { file_append++; sFilename = System.IO.Path.GetFileNameWithoutExtension(sFilename) + file_append.ToString() + extendName; } //缩略图保存的绝对路径 string smallImagePath = sSavePath + datetime + "/" + sFilename; //新建一个图板,以最小等比例压缩大小绘制原图 using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight)) { //绘制中间图 using (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(Color.Black); g.DrawImage( sourceImage, new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight), new System.Drawing.Rectangle(0, 0, width, height), System.Drawing.GraphicsUnit.Pixel ); } //新建一个图板,以缩略图大小绘制中间图 using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight)) { //绘制缩略图 http://www.cnblogs.com/sosoft/ using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1)) { //高清,平滑 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.Clear(Color.Black); int lwidth = (smallWidth - intThumbWidth) / 2; int bheight = (smallHeight - intThumbHeight) / 2; g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel); g.Dispose(); bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg); } } } } } catch { //出错则删除 System.IO.File.Delete((sSavePath + sFilename)); return("false"); } //返回缩略图名称 return(sFilename); } return("false"); }
/// <summary> /// 生成图片缩略文件 /// </summary> /// <param name="originalImage">图片源文件</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式</param> /// <returns>缩率处理后图片文件</returns> public static Image MakeThumbnail(Image originalImage, int width, int height, ThumbnailModel mode) { int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; switch (mode) { case ThumbnailModel.HighWidth: //指定高宽缩放(可能变形) break; case ThumbnailModel.Width: //指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case ThumbnailModel.Hight: //指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case ThumbnailModel.Default: //指定高,宽按比例 if (ow <= towidth && oh <= toheight) { x = -(towidth - ow) / 2; y = -(toheight - oh) / 2; ow = towidth; oh = toheight; } else { if (ow > oh) //宽大于高 { x = 0; y = -(ow - oh) / 2; oh = ow; } else //高大于宽 { y = 0; x = -(oh - ow) / 2; ow = oh; } } break; case ThumbnailModel.Auto: if (originalImage.Width / originalImage.Height >= width / height) { if (originalImage.Width > width) { towidth = width; toheight = (originalImage.Height * width) / originalImage.Width; } else { towidth = originalImage.Width; toheight = originalImage.Height; } } else { if (originalImage.Height > height) { toheight = height; towidth = (originalImage.Width * height) / originalImage.Height; } else { towidth = originalImage.Width; toheight = originalImage.Height; } } break; case ThumbnailModel.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.White); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel); return(bitmap); }
public void GetCroppedImage(string inPath, string outPath, int maxWidth, int maxHeight) { using (var imgOriginal = System.Drawing.Image.FromFile(inPath)) { ImageFormat tFormat = imgOriginal.RawFormat; //get original width and height of the incoming image var originalWidth = imgOriginal.Width; // 1000 var originalHeight = imgOriginal.Height; // 800 //裁剪对象 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); //目标定位 //模版的宽高比例 double templateRate = (double)maxWidth / maxHeight; //原图片的宽高比例 double initRate = (double)imgOriginal.Width / imgOriginal.Height; //宽为标准进行裁剪 if (templateRate > initRate) { //裁剪对象实例化 pickedImage = new System.Drawing.Bitmap(imgOriginal.Width, (int)System.Math.Floor(imgOriginal.Width / templateRate)); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //裁剪源定位 fromR.X = 0; fromR.Y = (int)System.Math.Floor((imgOriginal.Height - imgOriginal.Width / templateRate) / 2); fromR.Width = imgOriginal.Width; fromR.Height = (int)System.Math.Floor(imgOriginal.Width / templateRate); //裁剪目标定位 toR.X = 0; toR.Y = 0; toR.Width = imgOriginal.Width; toR.Height = (int)System.Math.Floor(imgOriginal.Width / templateRate); } //高为标准进行裁剪 else { pickedImage = new System.Drawing.Bitmap((int)System.Math.Floor(imgOriginal.Height * templateRate), imgOriginal.Height); pickedG = System.Drawing.Graphics.FromImage(pickedImage); fromR.X = (int)System.Math.Floor((imgOriginal.Width - imgOriginal.Height * templateRate) / 2); fromR.Y = 0; fromR.Width = (int)System.Math.Floor(imgOriginal.Height * templateRate); fromR.Height = imgOriginal.Height; toR.X = 0; toR.Y = 0; toR.Width = (int)System.Math.Floor(imgOriginal.Height * templateRate); toR.Height = imgOriginal.Height; } //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //裁剪 pickedG.DrawImage(imgOriginal, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //按模版大小生成最终图片 using (var resizedBmp = new System.Drawing.Bitmap(maxWidth, maxHeight)) { using (var graphics = Graphics.FromImage((Image)resizedBmp)) { graphics.InterpolationMode = InterpolationMode.Default; graphics.DrawImage(imgOriginal, 0, 0, maxWidth, maxHeight); } using (System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(resizedBmp)) { templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(Color.White); var rectangle = new Rectangle(0, 0, maxWidth, maxHeight); //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); //crop using (var croppedBmp = resizedBmp.Clone(rectangle, resizedBmp.PixelFormat)) { //get the codec needed var imgCodec = ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == tFormat.Guid); //make a paramater to adjust quality var codecParams = new EncoderParameters(1); //reduce to quality of 80 (from range of 0 (max compression) to 100 (no compression)) codecParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)this.Quality); EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = this.Quality;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; //save to the memorystream - convert it to an array and send it back as a byte[] croppedBmp.Save(outPath, imgCodec, ep); } } } } }