DrawImage() публичный метод

Draws the specified Image at the specified location and with the specified shape and size. The destPoints parameter specifies three points of a parallelogram. The three Point structures represent the upper-left, upper-right, and lower-left corners of the parallelogram. The fourth point is extrapolated from the first three to form a parallelogram. The image represented by the image parameter is scaled and sheared to fit the shape of the parallelogram specified by the destPoints parameters.
public DrawImage ( Image image, Point destPoints ) : void
image Image Image.
destPoints Point Destination points.
Результат void
Пример #1
0
 public void _drawTabHeader(Graphics nGraphics, Font nFont, Rectangle nRectangle)
 {
     int width_ = nRectangle.Height - 2;
     switch (mSideTabStatus)
     {
         case SideTabStatus_.mNormal_:
             ControlPaint.DrawBorder3D(nGraphics, nRectangle, Border3DStyle.RaisedInner);
             nGraphics.DrawImage(mSideTabImage, nRectangle.X + 1, nRectangle.Y + 1, width_, width_);
             nGraphics.DrawString(mSideTabName, nFont, SystemBrushes.ControlText, new PointF(nRectangle.X + width_ + 2, nRectangle.Y + 2));
             break;
         case SideTabStatus_.mSelected_:
             ControlPaint.DrawBorder3D(nGraphics, nRectangle, Border3DStyle.Sunken);
             nGraphics.DrawImage(mSideTabImage, nRectangle.X + 1, nRectangle.Y + 1, width_, width_);
             nGraphics.DrawString(mSideTabName, nFont, SystemBrushes.ControlText, new PointF(nRectangle.X + width_ + 2, nRectangle.Y + 2));
             break;
         case SideTabStatus_.mDragged_:
             ControlPaint.DrawBorder3D(nGraphics, nRectangle, Border3DStyle.RaisedInner);
             nRectangle.X += 1;
             nRectangle.Y += 1;
             nRectangle.Width -= 2;
             nRectangle.Height -= 2;
             nGraphics.FillRectangle(SystemBrushes.ControlDarkDark, nRectangle);
             nGraphics.DrawString(mSideTabName, nFont, SystemBrushes.HighlightText, new PointF(nRectangle.X + width_ , nRectangle.Y));
             break;
     }
 }
Пример #2
0
 public void drawGame(Graphics boardGr)
 {
     for (int i = 0; i < board.Width; i += gridSize)
     {
         for (int j = 0; j < board.Width; j += gridSize)
         {
             boardGr.DrawImage(ImageProvider.getTileTexture(TileType.None), new Rectangle(j, i, gridSize, gridSize));
         }
     }
     foreach (Tile tile in town.tiles)
     {
         boardGr.DrawImage(ImageProvider.getTileTexture(tile.type), new Rectangle(tile.getLocation().x, tile.getLocation().y, gridSize, gridSize));
     }
     for (int i = 0; i < board.Width; i += gridSize)
     {
         for (int j = 0; j < board.Width; j += gridSize)
         {
             boardGr.DrawRectangle(new Pen(Color.Black), new Rectangle(j, i, gridSize, gridSize));
         }
     }
     foreach (Entity entity in town.entities)
     {
         entity.draw(boardGr);
     }
 }
 public static void DrawBackgroundImage(Graphics g, Image backgroundImage, Color backColor, ImageLayout backgroundImageLayout, Rectangle bounds, Rectangle clipRect, Point scrollOffset, RightToLeft rightToLeft)
 {
     if (g == null)
     {
         throw new ArgumentNullException("g");
     }
     if (backgroundImageLayout == ImageLayout.Tile)
     {
         using (TextureBrush brush = new TextureBrush(backgroundImage, WrapMode.Tile))
         {
             if (scrollOffset != Point.Empty)
             {
                 Matrix transform = brush.Transform;
                 transform.Translate((float) scrollOffset.X, (float) scrollOffset.Y);
                 brush.Transform = transform;
             }
             g.FillRectangle(brush, clipRect);
             return;
         }
     }
     Rectangle rect = CalculateBackgroundImageRectangle(bounds, backgroundImage, backgroundImageLayout);
     if ((rightToLeft == RightToLeft.Yes) && (backgroundImageLayout == ImageLayout.None))
     {
         rect.X += clipRect.Width - rect.Width;
     }
     using (SolidBrush brush2 = new SolidBrush(backColor))
     {
         g.FillRectangle(brush2, clipRect);
     }
     if (!clipRect.Contains(rect))
     {
         if ((backgroundImageLayout == ImageLayout.Stretch) || (backgroundImageLayout == ImageLayout.Zoom))
         {
             rect.Intersect(clipRect);
             g.DrawImage(backgroundImage, rect);
         }
         else if (backgroundImageLayout == ImageLayout.None)
         {
             rect.Offset(clipRect.Location);
             Rectangle destRect = rect;
             destRect.Intersect(clipRect);
             Rectangle rectangle3 = new Rectangle(Point.Empty, destRect.Size);
             g.DrawImage(backgroundImage, destRect, rectangle3.X, rectangle3.Y, rectangle3.Width, rectangle3.Height, GraphicsUnit.Pixel);
         }
         else
         {
             Rectangle rectangle4 = rect;
             rectangle4.Intersect(clipRect);
             Rectangle rectangle5 = new Rectangle(new Point(rectangle4.X - rect.X, rectangle4.Y - rect.Y), rectangle4.Size);
             g.DrawImage(backgroundImage, rectangle4, rectangle5.X, rectangle5.Y, rectangle5.Width, rectangle5.Height, GraphicsUnit.Pixel);
         }
     }
     else
     {
         ImageAttributes imageAttr = new ImageAttributes();
         imageAttr.SetWrapMode(WrapMode.TileFlipXY);
         g.DrawImage(backgroundImage, rect, 0, 0, backgroundImage.Width, backgroundImage.Height, GraphicsUnit.Pixel, imageAttr);
         imageAttr.Dispose();
     }
 }
Пример #4
0
 /// <summary>
 /// Draws the trophy
 /// </summary>
 /// <param name="g">The graphics object to draw the trophy on</param>
 public override void Draw(Graphics g)
 {
     switch (this.Colour)
     {
         case Colours.Red:
             g.DrawImage(Balloon_Cup.Properties.Resources.ballooncup_trophyred, _rekt);
             break;
         case Colours.Blue:
             g.DrawImage(Balloon_Cup.Properties.Resources.ballooncup_trophyblue, _rekt);
             break;
         case Colours.Green:
             g.DrawImage(Balloon_Cup.Properties.Resources.ballooncup_trophygreen, _rekt);
             break;
         case Colours.Grey:
             g.DrawImage(Balloon_Cup.Properties.Resources.ballooncup_trophygrey, _rekt);
             break;
         case Colours.Yellow:
             g.DrawImage(Balloon_Cup.Properties.Resources.ballooncup_trophygold, _rekt);
             break;
         case Colours.White:
             g.FillRectangle(Brushes.White, _rekt);
             break;
         default:
             throw new Exception("Trophy colour not found.");
     }
 }
Пример #5
0
 public override void Draw(Graphics g)
 {
     if (borntime < Borntime) {
         switch (borntime % 8)
         {
             case 0:
             case 1:
                 g.DrawImage(bornImages[0], this.X, this.Y);
                 break;
             case 2:
             case 3:
                 g.DrawImage(bornImages[1], this.X, this.Y);
                 break;
             case 4:
             case 5:
                 g.DrawImage(bornImages[2], this.X, this.Y);
                 break;
             case 6:
             case 7:
                 g.DrawImage(bornImages[3], this.X, this.Y);
                 break;
         }
         borntime++;
         return;
     }
     g.DrawImage(img, this.X, this.Y);
 }
Пример #6
0
        public void DrawCandy(Graphics g)
        {
            sliki[0] = new Bitmap(Resources.candy1);
            sliki[1] = new Bitmap(Resources.candy2);
            sliki[2] = new Bitmap(Resources.candy3);
            sliki[3] = new Bitmap(Resources.candy4);
            for (int i = 0; i < KockiRec.Length; i += 4)
            {
                g.DrawImage(sliki[0], KockiRec[i]);

            }
            for (int j = 1; j < KockiRec.Length; j += 4)
            {
                g.DrawImage(sliki[1], KockiRec[j]);

            }
            for (int m = 2; m < KockiRec.Length; m += 4)
            {
                g.DrawImage(sliki[2], KockiRec[m]);

            }
            for (int n = 3; n < KockiRec.Length; n += 4)
            {
                g.DrawImage(sliki[3], KockiRec[n]);

            }
        }
Пример #7
0
        public void Draw(Graphics g)
        {
            if (State == Constants.Empty || State == Constants.Undefined)
            {
                return;
            }

            Image tmp;

            if (State == Constants.Free)
            {
                if (Hovered)
                {
                    tmp = Resources.selected;
                }
                else
                {
                    tmp = Resources.free;
                }
            }
            else
            {
                tmp = Resources.filled;
            }

            g.DrawImage(tmp, Position.X, Position.Y, 50, 50);

            // If State is not Filled or Free, then it has a Bee in it. Draw the bee.
            if (HasBee())
            {
                g.DrawImage(Game.getResourceImage(State), Position.X + 10, Position.Y + 10, 30, 30);
            }
        }
Пример #8
0
        public override void Draw(Graphics g)
        {
            UpdateBounds();

            if (BeenHit)
            {
                DrawExplosion(g);
                return;
            }

            if (Counter % 2 == 0)
                g.DrawImage(TheImage, MovingBounds, 0, 0, ImageBounds.Width, ImageBounds.Height, GraphicsUnit.Pixel);
            else
                g.DrawImage(OtherImage, MovingBounds, 0, 0, ImageBounds.Width, ImageBounds.Height, GraphicsUnit.Pixel);

            if (ActiveBomb)
            {
              TheBomb.Draw(g);
                if (Form1.ActiveForm != null)
                {
                    if (TheBomb.Position.Y > Form1.ActiveForm.ClientRectangle.Height)
                    {
                        ActiveBomb = false;
                    }
                }
            }

            if ((ActiveBomb == false) && (Counter % kBombInterval == 0))
            {
                ActiveBomb = true;
                TheBomb.Position.X = MovingBounds.X + MovingBounds.Width/2;
                TheBomb.Position.Y = MovingBounds.Y + 5;
            }
        }
Пример #9
0
		/// <summary>
		/// </summary>
		/// <exception cref="ArgumentNullException">
		/// <para>
		///		<paramref name="g"/> is <see langword="null"/>.
		/// </para>
		/// -or-
		/// <para>
		///		<paramref name="image"/> is <see langword="null"/>.
		/// </para>
		/// </exception>
		public void DrawImage(Graphics g, Rectangle bounds, NuGenControlState state, Image image)
		{
			if (g == null)
			{
				throw new ArgumentNullException("g");
			}

			if (image == null)
			{
				throw new ArgumentNullException("image");
			}

			switch (state)
			{
				case NuGenControlState.Disabled:
				{
					g.DrawImage(
						image,
						bounds,
						0, 0, image.Width, image.Height,
						GraphicsUnit.Pixel,
						NuGenControlPaint.GetDesaturatedImageAttributes()
					);
					break;
				}
				default:
				{
					g.DrawImage(image, bounds);
					break;
				}
			}
		}
Пример #10
0
        public void Draw(Graphics g)
        {
            if (selected)
            {
                //If the hotspot is currently selected displaying the active image
                g.DrawImage(activeImage, hotspotRect);
            }
            else
            {
                //If the hotspot is not selected displaying the inactive image
                g.DrawImage(inactiveImage, hotspotRect);

                //Getting how big the progress circle will be
                int fillWidth = (hotspotRect.Width / 100) * counter;
                int fillHeight = (hotspotRect.Width / 100) * counter;

                //Make the progress circle centered to the hotspot rectangle
                int xPos = (hotspotRect.Width - fillWidth) / 2 + hotspotRect.X;
                int yPos = (hotspotRect.Width - fillHeight) / 2 + hotspotRect.Y;

                //Displaying how close they are to activating the state
                g.FillEllipse(brush, xPos, yPos, fillWidth, fillHeight);

            }
        }
Пример #11
0
 protected void DrawNormalState(Graphics g)
 {
     if (!facingDown)
         g.DrawImage(SimpleAlarm.Properties.Resources.upButton, this.Bounds);
     else
         g.DrawImage(SimpleAlarm.Properties.Resources.downButton, this.Bounds);
 }
Пример #12
0
        public override void Draw(Graphics g, int target)
        {
            Image head = PicLoader.Read("NPC", string.Format("{0}.PNG", Figue));
            int ty = Y + 50;
            int ty2 = ty;
            if (target == Id)
            {
                g.DrawImage(head, X - 5, ty - 5, Width*5/4, Width * 5 / 4);
                ty2 -= 2;
            }
            else
            {
                g.DrawImage(head, X, ty, Width, Width);
            }

            head.Dispose();

            Font font = new Font("΢ÈíÑźÚ", 12*1.33f, FontStyle.Bold, GraphicsUnit.Pixel);
            g.DrawString(Name, font, Brushes.Black, X + 3, Y + Height + 30);
            g.DrawString(Name, font, Brushes.White, X, Y + Height + 27);
            font.Dispose();

            if (taskFinishs.Count > 0)
            {
                Image img = PicLoader.Read("System", "MarkTaskEnd.PNG");
                g.DrawImage(img, X + 15, ty2 - 35, 21, 30);
                img.Dispose();
            }
            else if (taskAvails.Count > 0)
            {
                Image img = PicLoader.Read("System", "MarkTaskBegin.PNG");
                g.DrawImage(img, X + 15, ty2 - 35, 24, 30);
                img.Dispose();
            }
        }
        public void draw(Graphics g)
        {
            Bitmap t = SpaceInvaders.Properties.Resources.titleMenu;

            g.DrawImage(t,Game.gameSize.Width/2-t.Width/2, 1,t.Width,t.Height);

            g.DrawImage(SpaceInvaders.Properties.Resources.ship1,new Point(200,200));
            g.DrawImage(SpaceInvaders.Properties.Resources.ship2, new Point(500, 500));
            g.DrawImage(SpaceInvaders.Properties.Resources.ship3, new Point(400, 50));
            g.DrawImage(SpaceInvaders.Properties.Resources.ship4, new Point(100, 300));
            g.DrawImage(SpaceInvaders.Properties.Resources.ship5, new Point(40, 40));
            g.DrawImage(SpaceInvaders.Properties.Resources.ship6, new Point(50, 150));
            g.DrawImage(SpaceInvaders.Properties.Resources.ship7, new Point(500, 400));
            g.DrawImage(SpaceInvaders.Properties.Resources.ship8, new Point(100, 500));
            g.DrawImage(SpaceInvaders.Properties.Resources.ship9, new Point(300, 450));

            int x = Game.gameSize.Width / 2;
            int y = Game.gameSize.Height / 2 - (this.items.Count/2 * this.espace );
            int dy = 0;
            g.DrawString(">", Game.defaultFont, Game.blackBrush, x-50 , y + this.espace *this.currentChose );
            g.DrawString(items[this.currentChose].Info ,new  Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Pixel),Game.blackBrush, x - 50, y +30 + this.espace * this.currentChose);
            foreach (MenuItem mi in items) {
                g.DrawString(mi.Name, Game.defaultFont, Game.blackBrush,x,y + dy);

                dy += this.espace;

            }
        }
Пример #14
0
        public override void Draw(Graphics g)
        {
            if (nid > 0)
            {
                int itemCount = UserProfile.Profile.InfoBag.GetItemCount(nid);
                bool isEnough = itemCount >= need;

                g.DrawImage(DataType.Items.HItemBook.GetHItemImage(nid), x, y, width, height);
                if (IsIn && isEnough)
                {
                    g.DrawImage(DataType.Items.HItemBook.GetHItemImage(nid), x+3, y+3, width-6, height-6);
                }
                if (!isEnough)
                {//灰色遮罩
                    Brush brush = new SolidBrush(Color.FromArgb(120, Color.Black));
                    g.FillRectangle(brush, x, y, width, height);
                    brush.Dispose();
                }

                Font fontsong = new Font("宋体", 7*1.33f, FontStyle.Regular, GraphicsUnit.Pixel);
                g.DrawString(string.Format("{0}/{1}", need, itemCount), fontsong, isEnough ? Brushes.White : Brushes.Red, x + 1, y + 18);
                fontsong.Dispose();
            }

            foreach (IRegionDecorator decorator in decorators)
            {
                decorator.Draw(g, x, y, width, height);
            }
        }
Пример #15
0
        /// <summary>
        /// 绘制图元自身
        /// </summary>
        /// <param name="g">图形对象</param>
        public override void Paint(Graphics g)
        {
            RefreshImages();

            Rectangle rectangle = new Rectangle(location, elementSize);
            Rectangle hoverRectangle = new Rectangle(new Point(location.X, location.Y - 1),
                new Size(elementSize.Width + 3, elementSize.Height + 2));
            Image image;

            if (selected) // 图元被选中
            {
                image = selectedImage;
                g.DrawImage(image, hoverRectangle);
            }
            else if (activated) // 图元被激活
            {
                image = activatedImage;
                g.DrawImage(image, hoverRectangle);
            }
            else // 图元没有被选中和激活
            {
                image = normalImage;
                g.DrawImage(image, rectangle);
            }
        }
Пример #16
0
        public void lineDrawing(String colorve, Graphics g, int xa, int ya, int xb, int yb)
        {
            int dx = xb - xa, dy = yb - ya, steps;
            float xIncrement, yIncrement, x = xa, y = ya;

            if (Math.Abs(dx) > Math.Abs(dy))
                steps = Math.Abs(dx);
            else
                steps = Math.Abs(dy);

            xIncrement = dx / (float)steps;
            yIncrement = dy / (float)steps;

            Bitmap bmp = new Bitmap(1, 1);
            bmp.SetPixel(0, 0, Color.FromName(colorve));

            g.DrawImage(bmp, round(x), round(y));

            for (int k = 0; k < steps; k++)
            {
                x += xIncrement;
                y += yIncrement;

                g.DrawImage(bmp, round(x), round(y));
            }
        }
Пример #17
0
        public static void DrawImage(Graphics g, Image image, ImageLayoutMode layoutMode, Rectangle rect)
        {
            // Graphics g = Graphics.FromHwnd(IntPtr.Zero);

            if (layoutMode == ImageLayoutMode.None)
            {
                Rectangle tempRect = new Rectangle(rect.X, rect.Y, image.Width, image.Height);
                g.SetClip(rect);
                g.DrawImage(image, tempRect);
                g.ResetClip();
            }
            else if (layoutMode == ImageLayoutMode.Stretch)
            {
                g.DrawImage(image, rect);
            }
            else if (layoutMode == ImageLayoutMode.FitToWidth)
            {
                g.SetClip(rect);
                Size newSize = new Size(rect.Width, rect.Width * image.Height / image.Width);
                g.DrawImage(image, new Rectangle(rect.Location, newSize));
                g.ResetClip();
            }
            else if (layoutMode == ImageLayoutMode.FitToHeight)
            {
                g.SetClip(rect);
                Size newSize = new Size(rect.Height * image.Width / image.Height, rect.Height);
                g.DrawImage(image, new Rectangle(rect.Location, newSize));
                g.ResetClip();
            }
        }
Пример #18
0
        public void Draw(Graphics g, bool enable)
        {
            Image back = PicLoader.Read("System", "ItemGrid.JPG");
            g.DrawImage(back, x+3, y+3, 32, 32);
            back.Dispose();

            if (itemPos >= 0)
            {
                Font font = new Font("Aril", 11*1.33f, FontStyle.Bold, GraphicsUnit.Pixel);
                if (enable)
                {
                    g.DrawImage(HItemBook.GetHItemImage(UserProfile.InfoBag.Items[itemPos].Type), x + 3, y + 3, 32, 32);
                }
                else
                {
                    Rectangle ret = new Rectangle(x + 3, y + 3, 32, 32);
                    g.DrawImage(HItemBook.GetHItemImage(UserProfile.InfoBag.Items[itemPos].Type), ret, 0, 0, 64, 64, GraphicsUnit.Pixel, HSImageAttributes.ToGray);
                }

                g.DrawString(UserProfile.InfoBag.Items[itemPos].Value.ToString(), font, Brushes.Black, x + 4, y + 4);
                g.DrawString(UserProfile.InfoBag.Items[itemPos].Value.ToString(), font, Brushes.White, x + 3, y + 3);

                if (percent>1)
                {
                    Brush brush = new SolidBrush(Color.FromArgb(200, Color.Black));
                    g.FillRectangle(brush, x, y, 35, 35*percent/100);
                    brush.Dispose();
                }

                font.Dispose();
            }
        }
Пример #19
0
    protected override void DrawComboBoxItem(Graphics g, Rectangle bounds, int Index, bool selected, bool editSel)
    {
      // Call base class to do the "Flat ComboBox" drawing
      // Draw bitmap
      base.DrawComboBoxItem(g, bounds, Index, selected, editSel);
      if ( Index != -1) 
      {
        Brush brush;
        brush = new SolidBrush(SystemColors.MenuText);
        
        if ( useImageList == false )
          g.DrawImage(bitmapsArray[Index], bounds.Left+2, bounds.Top+2, PREVIEW_BOX_WIDTH, bounds.Height-4);
        else
          g.DrawImage(imageList.Images[Index], bounds.Left+2, bounds.Top+2, PREVIEW_BOX_WIDTH, bounds.Height-4);

        g.DrawRectangle(Pens.Black, new Rectangle(bounds.Left+1, bounds.Top+1, PREVIEW_BOX_WIDTH+1, bounds.Height-3));

        Size textSize = TextUtil.GetTextSize(g, Items[Index].ToString(), Font);
        int top = bounds.Top + (bounds.Height - textSize.Height)/2;
        g.DrawString(Items[Index].ToString(), Font, brush,
          new Point(bounds.Left + 28, top));
        brush.Dispose();

      }
    }
Пример #20
0
 //vẽ lại hình ảnh con rắn khi di chuyển xuống
 public void drawDown(Graphics paper)
 {
     paper.DrawImage(downHead, snakeRec[0]);//vẽ hình ảnh đầu dưới
     for (int i = 1; i < snakeRec.Length; i++)
     {
         paper.DrawImage(down, snakeRec[i]);//vẽ hình ảnh thân dưới
     }
 }
Пример #21
0
 //vẽ lại con rắn bên phải
 public void drawSnake(Graphics paper)
 {
     paper.DrawImage(rightHead, snakeRec[0]);//vẽ đầu phải
     for (int i = 1; i < snakeRec.Length; i++)
     {
         paper.DrawImage(image, snakeRec[i]);//vẽ thân phải
     }
 }
Пример #22
0
 //vẽ lại hình ảnh con rắn khi di chuyển qua trái
 public void drawLeft(Graphics paper)
 {
     paper.DrawImage(leftHead, snakeRec[0]);//vẽ hình ảnh đầu trái
     for (int i = 1; i < snakeRec.Length; i++)
     {
         paper.DrawImage(left, snakeRec[i]);//vẽ hình ảnh thân trái
     }
 }
Пример #23
0
 public override void DrawToMap(Graphics g, int sizeField, int marginH, int marginV)
 {
     if( this.wait > 0) return;
     if( this.revenge)
         g.DrawImage( this.ghostR, this.position.X * sizeField + marginH,
             this.position.Y * sizeField + marginV);
     else
         g.DrawImage(this.ghost, this.position.X * sizeField + marginH,
             this.position.Y * sizeField + marginV);
 }
Пример #24
0
 void DrawMap(Graphics g, int row, int col)
 {
     Game.Tile t = game.map[row, col];
     Bitmap b = game.tile[t];
     Bitmap green = game.tile[Game.Tile.SPACE];
     int x = col * TSIZE;
     int y = row * TSIZE;
     g.DrawImage(green, dx + x, dy + y, TSIZE, TSIZE);
     g.DrawImage(b, dx +x,dy +  y,TSIZE,TSIZE);
 }
Пример #25
0
 public void DrawSelf(Graphics g,ImageAttributes attribute)
 {
     if (attribute != null)
     {
         g.DrawImage(BackgroundBitmap, Rectangle, 0, 0, Width, Height, GraphicsUnit.Pixel, attribute);
     }
     else
     {
         g.DrawImage(BackgroundBitmap, Rectangle);
     }
 }
Пример #26
0
 public static void DrawImageCenteredDpiAware(Graphics g, Image image, Rectangle r)
 {
     if (g.DpiX != 96f || g.DpiY != 96f)
     {
         float scaleX = g.DpiX / 96f;
         float scaleY = g.DpiY / 96f;
         g.DrawImage(image, r.X + (r.Width - image.Width * scaleX) / 2, r.Y + (r.Height - image.Height * scaleY) / 2);
     }
     else
         g.DrawImage(image, r.X + (r.Width - image.Width) / 2, r.Y + (r.Height - image.Height) / 2);
 }
Пример #27
0
 public override void Draw(Graphics g)
 {
     if (seDvizi)
     {
         rotatedImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
         g.DrawImage(rotatedImage, X, Y);
     }
     else
     {
         g.DrawImage(image, X, Y);
     }
 }
Пример #28
0
 public void drawMenu(Graphics g, MenuFactory menuFactory)
 {
     if (menuFactory.getCurrentMenu().isAnimationFinished())
     {
         g.DrawImage(menuFactory.getCurrentMenu().getMenuImage(), MENU_DRAW_LOCATION);
     }
     else
     {
         g.DrawImage(menuFactory.getCurrentMenu().getAnimationImages()[menuFactory.getCurrentMenu().getAnimationIndex()], MENU_DRAW_LOCATION);
         menuFactory.getCurrentMenu().advanceAnimation();
     }
 }
Пример #29
0
		public void DrawHigh(Graphics g, int x, int y, int i,bool over,bool top)
		{
			if(top && state!=CursorState.Aim)
			{
				if(over)				
					g.DrawImage(cursorFile[1].Image,x,y);
				else
					g.DrawImage(cursorFile[0].Image,x,y);
			}
			else
				g.DrawImage(cursorFile[2].Image,x,y);
		}
Пример #30
0
 public void draw(Graphics g, Size screenSize, string drawMode)
 {
     float screenWidth = (float)(screenSize.Width/ 40.00);
             float screenHeight = (float)(screenSize.Height / 20.00);
     if (drawMode == "Game")
     {
         g.DrawImage(getImage(), this.x, this.y, screenWidth, screenHeight);
     }else if (drawMode == "Designer")
     {
         g.DrawImage(getImage(), this.x * screenWidth, this.y * screenHeight, screenWidth, screenHeight);
     }
 }
Пример #31
0
        /// <summary>
        /// 生成缩略图,并把缩略图缩放到指定的大小,缩放要求不变形、不裁剪
        /// </summary>
        /// <param name="srcImage">来源图片</param>
        /// <param name="destWidth">目标宽度</param>
        /// <param name="destHeight">目标高度</param>
        public static Image CreateThumbnail(Image srcImage, int destWidth, int destHeight)
        {
            if (destWidth == 0 || destHeight == 0 || srcImage == null)
            {
                return(null);
            }

            bool   wasDispose = true;
            Bitmap bmp        = null;

            System.Drawing.Graphics g = null;

            try
            {
                //原始图片的宽和高
                int srcWidth  = srcImage.Width;
                int srcHeight = srcImage.Height;
                //如果不需要缩放,直接返回图片
                if (srcWidth <= destWidth && srcHeight <= destHeight)
                {
                    wasDispose = false;
                    return(srcImage);
                }

                //由于原始图片的长宽比例跟指定缩略图的长宽比例可能不一样,所以最后缩放出来的图片的大小跟指定的长宽不一定
                //这个要根据原始图片和要求缩略图的比例来决定
                if ((float)srcWidth / (float)srcHeight >= (float)destWidth / (float)destHeight)
                {
                    destHeight = srcHeight * destWidth / srcWidth; //先乘后整除
                }
                else
                {
                    destWidth = srcWidth * destHeight / srcHeight;
                }


                //接着创建一个System.Drawing.Bitmap对象,并设置你希望的缩略图的宽度和高度。
                bmp = new Bitmap(destWidth, destHeight);

                //从Bitmap创建一个System.Drawing.Graphics对象,用来绘制高质量的缩小图。
                g = System.Drawing.Graphics.FromImage(bmp);
                //设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality
                g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.High;
                //把原始图像绘制成上面所设置宽高的缩小图
                System.Drawing.Rectangle desRec = new System.Drawing.Rectangle(0, 0, destWidth, destHeight);
                g.DrawImage(srcImage, desRec, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (g != null)
                {
                    g.Dispose();
                }
                if (srcImage != null && wasDispose)
                {
                    srcImage.Dispose();
                }
            }

            return(bmp);
        }
Пример #32
0
        /**/
        /// <param name="SavePath">原始路径</param>
        /// <param name="pathDate">添加的月份路径</param>
        /// <param name="picFilePath">保存的文件名</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        public byte[] GetThumbnailImage(string fileExtension, double percent)
        {
            Bitmap img = new Bitmap(this.ResourceImage);  //read picture to memory

            int    h = img.Height;
            int    w = img.Width;
            int    ss, os;// source side and objective side
            double temp1, temp2;

            //compute the picture's proportion
            temp1 = (h * 1.0D) / (h * percent);
            temp2 = (w * 1.0D) / (w * percent);
            if (temp1 < temp2)
            {
                ss = w;
                os = (int)(w * percent);
            }
            else
            {
                ss = h;
                os = (int)(h * percent);
            }

            double per = (os * 1.0D) / ss;

            if (per < 1.0D)
            {
                h = (int)(h * per);
                w = (int)(w * per);
            }
            // create the thumbnail image
            System.Drawing.Image imag2 = img.GetThumbnailImage(w, h,
                                                               new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback),
                                                               IntPtr.Zero);
            Bitmap tempBitmap = new Bitmap(w, h);

            System.Drawing.Image    tempImg = System.Drawing.Image.FromHbitmap(tempBitmap.GetHbitmap());
            System.Drawing.Graphics g       = System.Drawing.Graphics.FromImage(tempImg);
            g.Clear(Color.White);

            int x, y;

            x = (tempImg.Width - imag2.Width) / 2;
            y = (tempImg.Height - imag2.Height) / 2;

            g.DrawImage(imag2, x, y, imag2.Width, imag2.Height);

            try
            {
                if (img != null)
                {
                    img.Dispose();
                }
                if (imag2 != null)
                {
                    imag2.Dispose();
                }
                if (tempBitmap != null)
                {
                    tempBitmap.Dispose();
                }

                MemoryStream ms        = new MemoryStream();
                byte[]       imagedata = null;
                //按原图片类型保存缩略图片,不按原格式图片会出现模糊,锯齿等问题.
                switch (fileExtension)
                {
                case "gif": tempImg.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); break;

                case "jpg": tempImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); break;

                case "bmp": tempImg.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); break;

                case "png": tempImg.Save(ms, System.Drawing.Imaging.ImageFormat.Png); break;
                }

                imagedata = ms.GetBuffer();
                ms.Close();
                return(imagedata);
            }
            catch
            {
                throw new Exception("图片上传失败");
            }
            finally
            {
                //释放内存
                if (tempImg != null)
                {
                    tempImg.Dispose();
                }
                if (g != null)
                {
                    g.Dispose();
                }
            }
        }
Пример #33
0
        /// <summary>
        ///   根据Url图片网址,裁剪
        /// </summary>
        /// <param name="picUrl">图片Url</param>
        /// <param name="x">裁剪后,距离左侧像素</param>
        /// <param name="y">裁剪后,距离头部像素</param>
        /// <param name="w">裁剪后,图片宽度</param>
        /// <param name="h">裁剪后,图片高度</param>
        public static string Cutting(string picUrl, int x, int y, int w, int h, string saveUrl = "/upfile/")
        {
            if (!System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~" + saveUrl)))
            {
                System.IO.Directory.CreateDirectory(@System.Web.HttpContext.Current.Server.MapPath("~" + saveUrl));
            }
            WebRequest  webrequest  = WebRequest.Create(picUrl);//图片完整地址 包含http
            WebResponse webresponse = webrequest.GetResponse();
            //文件流获取图片操作
            Stream reader      = webresponse.GetResponseStream();
            string webFilePath = System.Web.HttpContext.Current.Server.MapPath("~/" + saveUrl);

            string[] temp    = picUrl.Split('.');
            string   imgname = DateTime.Now.ToString("ddHHmmssssffff") + "." + temp[temp.Length - 1].ToLower();
            string   path    = webFilePath + imgname;//图片路径命名

            saveUrl = saveUrl + imgname;
            //从文件取得图片对象,并使用流中嵌入的颜色管理信息
            System.Drawing.Image myImage = System.Drawing.Image.FromStream(reader, true);
            //取得图片大小
            System.Drawing.Size mySize = new Size(w, h);//截取的图片的宽和高
            //新建一个bmp图片
            System.Drawing.Image 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(Color.White);
            //在指定位置画图
            g.DrawImage(myImage,
                        new System.Drawing.Rectangle(0, 0, myImage.Width, myImage.Height),
                        new System.Drawing.Rectangle(x, y, myImage.Width, myImage.Height),
                        System.Drawing.GraphicsUnit.Pixel);

            //保存缩略图
            if (File.Exists(path))
            {
                File.SetAttributes(path, FileAttributes.Normal);
                File.Delete(path);
            }

            bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
            g.Dispose();
            myImage.Dispose();
            bitmap.Dispose();


            //FileStream writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            //try
            //{
            //    byte[] buff = new byte[1024];
            //    int c = 0;//实际读取的字节数
            //    while ((c = reader.Read(buff, 0, buff.Length)) > 0)
            //    {
            //        writer.Write(buff, 0, c);
            //    }
            //}
            //catch (Exception)
            //{
            //    //释放资源
            //    writer.Close();
            //    writer.Dispose();
            //    reader.Close();
            //    reader.Dispose();
            //    webresponse.Close();
            //}
            ////释放资源
            //writer.Close();
            //writer.Dispose();
            //reader.Close();
            //reader.Dispose();
            //webresponse.Close();

            //上传成功
            return(saveUrl);
        }
Пример #34
0
        protected override void OnPaint(PaintEventArgs pevent)
        {
            const int CORNER_SIZE = 11;
            const int IMAGE_WIDTH = 32;

            this.OnPaintBackground(pevent);
            System.Drawing.Graphics g = pevent.Graphics;

            int w = this.Width;
            int h = this.Height;

            Brush bkg = new SolidBrush(m_swatch_colour);

            if ((w < 2 * CORNER_SIZE) || (h < 2 * CORNER_SIZE))
            {
                g.FillRectangle(bkg, 0, 0, w, h);
                return;
            }

            // rounded rectangle in the swatch's colour
            g.FillRectangle(bkg, 3, 1, w - 6, 1);
            g.FillRectangle(bkg, 2, 2, w - 4, 1);
            g.FillRectangle(bkg, 1, 3, w - 2, h - 6);
            g.FillRectangle(bkg, 2, h - 3, w - 4, 1);
            g.FillRectangle(bkg, 3, h - 2, w - 6, 1);

            // borders. Think "css border image"
            int ct = m_hover ? 2 : 1;

            for (int x = 0; x < ct; x++)
            {
                // corners
                g.DrawImage(corner, new Rectangle(0, 0, CORNER_SIZE, CORNER_SIZE),
                            new Rectangle(0, 0, CORNER_SIZE, CORNER_SIZE), GraphicsUnit.Pixel);

                g.DrawImage(corner, new Rectangle(w - CORNER_SIZE, 0, CORNER_SIZE, CORNER_SIZE),
                            new Rectangle(IMAGE_WIDTH - CORNER_SIZE, 0, CORNER_SIZE, CORNER_SIZE), GraphicsUnit.Pixel);

                g.DrawImage(corner, new Rectangle(0, h - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE),
                            new Rectangle(0, IMAGE_WIDTH - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE), GraphicsUnit.Pixel);

                g.DrawImage(corner, new Rectangle(w - CORNER_SIZE, h - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE),
                            new Rectangle(IMAGE_WIDTH - CORNER_SIZE, IMAGE_WIDTH - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE), GraphicsUnit.Pixel);

                // sides
                g.DrawImage(corner, new Rectangle(CORNER_SIZE, 0, w - 2 * CORNER_SIZE, CORNER_SIZE),
                            new Rectangle(CORNER_SIZE, 0, IMAGE_WIDTH - 2 * CORNER_SIZE, CORNER_SIZE), GraphicsUnit.Pixel);

                g.DrawImage(corner, new Rectangle(0, CORNER_SIZE, CORNER_SIZE, h - 2 * CORNER_SIZE),
                            new Rectangle(0, CORNER_SIZE, CORNER_SIZE, IMAGE_WIDTH - 2 * CORNER_SIZE), GraphicsUnit.Pixel);

                g.DrawImage(corner, new Rectangle(CORNER_SIZE, h - CORNER_SIZE, w - 2 * CORNER_SIZE, CORNER_SIZE),
                            new Rectangle(CORNER_SIZE, IMAGE_WIDTH - CORNER_SIZE, IMAGE_WIDTH - 2 * CORNER_SIZE, CORNER_SIZE), GraphicsUnit.Pixel);

                g.DrawImage(corner, new Rectangle(w - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE, h - 2 * CORNER_SIZE),
                            new Rectangle(IMAGE_WIDTH - CORNER_SIZE, CORNER_SIZE, CORNER_SIZE, IMAGE_WIDTH - 2 * CORNER_SIZE), GraphicsUnit.Pixel);
            }

            Brush        fore   = new SolidBrush(this.ForeColor);
            Brush        shadow = new SolidBrush(Color.FromArgb(191, 0, 0, 0));
            StringFormat fmt    = new StringFormat();

            fmt.Alignment     = StringAlignment.Center;
            fmt.LineAlignment = StringAlignment.Center;

            Point text_pos = new Point(w / 2, h / 2);

            g.DrawString(this.Text, this.Font, shadow, new Point(text_pos.X, text_pos.Y + 1), fmt);
            g.DrawString(this.Text, this.Font, fore, text_pos, fmt);
        }
Пример #35
0
        public MarqueeDisplay131(LedPictureText pContent)
        {
            this.content = pContent;
            LedElement ledElement = this.content.Elements[0];

            System.Drawing.Size size = this.content.GetSize();
            this.pageCount  = ledElement.PageCount;
            this.nowLoopNum = 1;
            int num;

            if (this.pageCount >= 3)
            {
                num             = 3;
                this.pageNumber = 3;
            }
            else
            {
                num             = this.pageCount;
                this.pageNumber = this.pageCount;
            }
            int  num2 = size.Width * num;
            bool flag = false;

            if (num2 > pContent.EffectiveLength)
            {
                num2 = pContent.EffectiveLength;
            }
            if (pContent.EffectiveLength < size.Width)
            {
                num2 = (size.Width / pContent.EffectiveLength + 1) * num2;
                flag = true;
            }
            this.AllBit = new System.Drawing.Bitmap(num2, size.Height);
            System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(this.AllBit);
            int num3 = size.Width * (num - 1);

            for (int i = 0; i < num; i++)
            {
                System.Drawing.Bitmap bmpFromFile = LedGraphics.GetBmpFromFile(size, this.pageCount - 1 - i, this.content.GetFileFullPath());
                if (i == 0)
                {
                    if (flag)
                    {
                        for (int j = 0; j < num2; j += pContent.EffectiveLength)
                        {
                            graphics.DrawImage(bmpFromFile, new System.Drawing.Rectangle(j, 0, pContent.EffectiveLength, size.Height), new System.Drawing.Rectangle(0, 0, pContent.EffectiveLength, size.Height), System.Drawing.GraphicsUnit.Pixel);
                        }
                    }
                    else
                    {
                        graphics.DrawImage(bmpFromFile, new System.Drawing.Point(num3, 0));
                    }
                }
                else
                {
                    graphics.DrawImage(bmpFromFile, new System.Drawing.Point(num3, 0));
                }
                num3 -= bmpFromFile.Width;
                bmpFromFile.Dispose();
            }
            this.nowPositionF = (float)this.AllBit.Width;
        }
Пример #36
0
    /// <summary>
    /// 水印图片
    /// 【如果图片需要缩略,请使用skeletonize.Resizepic()方法对图片进行缩略】
    /// 返回图片虚拟路径,和一个警告信息,可根据此信息获取图片合成信息
    /// </summary>
    /// <param name="picpath">需要水印的图片路径</param>
    /// <param name="waterspath">水印图片(Image)</param>
    /// <param name="watermodel">水印模式</param>
    /// <param name="spath">文件保存路径,带文件名</param>
    /// <param name="imgtype">保存文件类型</param>
    /// <param name="filecache">原文件处理方式</param>
    /// <param name="warning">处理警告信息</param>
    /// <returns>错误,返回错误信息;成功,返回图片路径</returns>
    public static string makewatermark(string picpath, System.Drawing.Image water, WaterType watermodel, string spath, ImageType imgtype, FileCache filecache, out string warning, int trans = 100)
    {
        #region
        //反馈信息
        System.Text.StringBuilder checkmessage = new System.Text.StringBuilder();

        //检测源文件
        string _sourceimg_common_mappath = "";
        bool   checkfile = false;
        checkfile = FileExistMapPath(picpath, FileCheckModel.C, out _sourceimg_common_mappath);

        System.Drawing.Image _sourceimg_common = null;

        if (checkfile == true)
        {
            //从指定源文件,创建image对象
            _sourceimg_common = System.Drawing.Image.FromFile(_sourceimg_common_mappath);
        }
        else
        {
            checkmessage.Append("error:找不到需要的水印图片!" + picpath + ";");
        }
        #endregion

        #region
        if (string.IsNullOrEmpty(checkmessage.ToString()))
        {
            //源图宽、高
            int _sourceimg_common_width  = _sourceimg_common.Width;
            int _sourceimg_common_height = _sourceimg_common.Height;

            //水印图片宽、高
            int _sourceimg_water_width  = water.Width;
            int _sourceimg_water_height = water.Height;

            #region 水印坐标
            //水印坐标
            int _sourceimg_water_point_x = 0;
            int _sourceimg_water_point_y = 0;

            switch (watermodel)
            {
            case WaterType.Center:
                _sourceimg_water_point_x = (_sourceimg_common_width - _sourceimg_water_width) / 2;
                _sourceimg_water_point_y = (_sourceimg_common_height - _sourceimg_water_height) / 2;
                ; break;

            case WaterType.CenterDown:
                _sourceimg_water_point_x = (_sourceimg_common_width - _sourceimg_water_width) / 2;
                _sourceimg_water_point_y = _sourceimg_common_height - _sourceimg_water_height;
                ; break;

            case WaterType.CenterUp:
                _sourceimg_water_point_x = (_sourceimg_common_width - _sourceimg_water_width) / 2;
                _sourceimg_water_point_y = 0;
                ; break;

            case WaterType.LeftDown:
                _sourceimg_water_point_x = 0;
                _sourceimg_water_point_y = _sourceimg_common_height - _sourceimg_water_height;
                ; break;

            case WaterType.LeftUp:
                ; break;

            case WaterType.Random:
                Random r        = new Random();
                int    x_random = r.Next(0, _sourceimg_common_width);
                int    y_random = r.Next(0, _sourceimg_common_height);

                _sourceimg_water_point_x = x_random > (_sourceimg_common_width - _sourceimg_water_width)
                            ? _sourceimg_common_width - _sourceimg_water_width : x_random;

                _sourceimg_water_point_y = y_random > (_sourceimg_common_height - _sourceimg_water_height)
                            ? _sourceimg_common_height - _sourceimg_water_height : y_random;

                ; break;

            case WaterType.RightDown:
                _sourceimg_water_point_x = _sourceimg_common_width - _sourceimg_water_width;
                _sourceimg_water_point_y = _sourceimg_common_height - _sourceimg_water_height;
                ; break;

            case WaterType.RightUp:
                _sourceimg_water_point_x = _sourceimg_common_width - _sourceimg_water_width;
                _sourceimg_water_point_y = 0;
                ; break;
            }
            #endregion

            //从源图创建画板
            System.Drawing.Graphics _g_common = Graphics.FromImage(_sourceimg_common);

            //设置画笔
            _g_common.CompositingMode   = System.Drawing.Drawing2D.CompositingMode.SourceOver;
            _g_common.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            _g_common.PixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.Half;

            #region  设置透明
            int ap = trans;
            if (ap > 100 || ap < 0)
            {
                ap = 100;
            }
            float alpha = (float)ap / (float)100;
            //包含有关在呈现时如何操作位图和图元文件颜色的信息。
            ImageAttributes imageAttributes = new ImageAttributes();
            //Colormap: 定义转换颜色的映射
            ColorMap colorMap = new ColorMap();
            //我的水印图被定义成拥有绿色背景色的图片被替换成透明
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };
            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float[][] colorMatrixElements =
            {
                new float[] { 1.0f, 0.0f, 0.0f,  0.0f, 0.0f }, // red红色
                new float[] { 0.0f, 1.0f, 0.0f,  0.0f, 0.0f }, //green绿色
                new float[] { 0.0f, 0.0f, 1.0f,  0.0f, 0.0f }, //blue蓝色
                new float[] { 0.0f, 0.0f, 0.0f, alpha, 0.0f }, //透明度
                new float[] { 0.0f, 0.0f, 0.0f,  0.0f, 1.0f }
            };                                                 //
            //  ColorMatrix:定义包含 RGBA 空间坐标的 5 x 5 矩阵。
            //  ImageAttributes 类的若干方法通过使用颜色矩阵调整图像颜色。
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            #endregion

            //绘制水印图片
            // g.DrawImage(copyImage, new Rectangle(postx, posty, copyImage.Width, copyImage.Height), 0, 0, copyImage.Width, copyImage.Height, GraphicsUnit.Pixel, imageAttributes);
            //new Rectangle(0, 0, _sourceimg_water_width, _sourceimg_water_height)
            _g_common.DrawImage(water, new Rectangle(_sourceimg_water_point_x, _sourceimg_water_point_y, _sourceimg_water_width, _sourceimg_water_height), 0, 0, _sourceimg_water_width, _sourceimg_water_height, GraphicsUnit.Pixel, imageAttributes);

            //保存图片
            string _spath_common_mappath = "";
            //全局文件名

            //获取图片类型的hashcode值,生成图片后缀名
            //int extro = imgtype.GetHashCode();
            //string extend = extro == 0 ? ".jpg" : (extro == 1 ? ".gif" : (extro == 2 ? ".png" : ".jpg"));
            //spath = spath + Guid.NewGuid().ToString() + extend;

            FileExistMapPath(spath, FileCheckModel.M, out _spath_common_mappath);

            switch (imgtype)
            {
            case ImageType.JPEG: _sourceimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Jpeg); break;

            case ImageType.GIF: _sourceimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Gif); break;

            case ImageType.PNG: _sourceimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Png); break;
            }


            //释放
            _sourceimg_common.Dispose();
            water.Dispose();
            _g_common.Dispose();

            //处理原文件
            int filecachecode = filecache.GetHashCode();
            //删除原文件
            if (filecachecode == 1)
            {
                System.IO.File.Delete(_sourceimg_common_mappath);
            }

            warning = "";
            return(spath);
        }
        #endregion
        //释放
        _sourceimg_common.Dispose();
        water.Dispose();
        warning = checkmessage.ToString().TrimEnd(';');
        return("");
    }
Пример #37
0
    /// <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 MakeThumbPhoto(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格式Save缩略图
            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
        }
    }
Пример #38
0
        /// <summary>
        /// Renders the layer
        /// </summary>
        /// <param name="g">Graphics object reference</param>
        /// <param name="map">Map which is rendered</param>
        public override void OnRender(System.Drawing.Graphics g, Map map)
        {
            SharpMap.Web.Wms.Client.WmsOnlineResource resource = GetPreferredMethod();
            Uri myUri = new Uri(GetRequestUrl(map.Envelope, map.Size));

            System.Net.WebRequest myWebRequest = System.Net.WebRequest.Create(myUri);
            myWebRequest.Method  = resource.Type;
            myWebRequest.Timeout = timeOut;
            if (credentials != null)
            {
                myWebRequest.Credentials = credentials;
            }
            else
            {
                myWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            }

            if (proxy != null)
            {
                myWebRequest.Proxy = proxy;
            }

            try
            {
                System.Net.HttpWebResponse myWebResponse = (System.Net.HttpWebResponse)myWebRequest.GetResponse();
                System.IO.Stream           dataStream    = myWebResponse.GetResponseStream();

                if (myWebResponse.ContentType.StartsWith("image"))
                {
                    System.Drawing.Image img = System.Drawing.Image.FromStream(myWebResponse.GetResponseStream());
                    if (imageAttributes != null)
                    {
                        g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0,
                                    img.Width, img.Height, GraphicsUnit.Pixel, this.ImageAttributes);
                    }
                    else
                    {
                        g.DrawImageUnscaled(img, 0, 0, map.Size.Width, map.Size.Height);
                    }
                }
                dataStream.Close();
                myWebResponse.Close();
            }
            catch (System.Net.WebException webEx)
            {
                if (!continueOnError)
                {
                    throw (new SharpMap.Rendering.Exceptions.RenderException("There was a problem connecting to the WMS server when rendering layer '" + this.Name + "'", webEx));
                }
                else
                {
                    //Write out a trace warning instead of throwing an error to help debugging WMS problems
                    System.Diagnostics.Trace.Write("There was a problem connecting to the WMS server when rendering layer '" + this.Name + "': " + webEx.Message);
                }
            }
            catch (System.Exception ex)
            {
                if (!continueOnError)
                {
                    throw (new SharpMap.Rendering.Exceptions.RenderException("There was a problem rendering layer '" + this.Name + "'", ex));
                }
                else
                {
                    //Write out a trace warning instead of throwing an error to help debugging WMS problems
                    System.Diagnostics.Trace.Write("There was a problem connecting to the WMS server when rendering layer '" + this.Name + "': " + ex.Message);
                }
            }
        }
Пример #39
0
    public static string diffpicpath = "";    //上一张要被剪切的原图地址
    /// <summary>
    /// 图片剪切
    /// </summary>
    /// <param name="picpath">源图片文件地址</param>
    /// <param name="spath">剪切临时文件地址</param>
    /// <param name="x1">x起始坐标</param>
    /// <param name="y1">y起始坐标</param>
    /// <param name="width">宽度</param>
    /// <param name="height">高度</param>
    /// <param name="filecache">源文件处理方式</param>
    /// <param name="warning">处理警告信息</param>
    /// <returns>剪切图片地址</returns>
    public static string imgcrop(string picpath, string spath, int x1, int y1, int width, int height, FileCache filecache, out string warning)
    {
        //反馈信息
        System.Text.StringBuilder checkmessage = new System.Text.StringBuilder();
        //从指定源图片,创建image对象
        string _sourceimg_common_mappath = "";
        //检测源文件
        bool checkfile = false;

        checkfile = FileExistMapPath(picpath, FileCheckModel.M, out _sourceimg_common_mappath);

        System.Drawing.Image    _sourceimg_common = null;
        System.Drawing.Bitmap   _currimg_common   = null;
        System.Drawing.Graphics _g_common         = null;

        if (checkfile == true)
        {
            //从源文件创建imgage
            _sourceimg_common = System.Drawing.Image.FromFile(_sourceimg_common_mappath);

            //从指定width、height创建bitmap对象
            _currimg_common = new System.Drawing.Bitmap(width, height);

            //从_currimg_common创建画笔
            _g_common = Graphics.FromImage(_currimg_common);

            //设置画笔
            _g_common.CompositingMode   = System.Drawing.Drawing2D.CompositingMode.SourceOver;
            _g_common.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            _g_common.PixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.Half;

            //绘制图片
            _g_common.DrawImage(_sourceimg_common, new Rectangle(0, 0, width, height), new Rectangle(x1, y1, width, height), GraphicsUnit.Pixel);

            //保存图片
            string _spath_common_mappath = "";

            //判断是否是对同一张图片进行剪切
            //判断是否,已更新剪切图片,防止覆盖上一张已完成剪切的图片
            //spath = string.IsNullOrEmpty(lastcroppic) ? spath + DateTime.Now.ToString("MMddhhmmss") + ".jpg" : (diffpicpath == picpath ? lastcroppic : spath + Guid.NewGuid().ToString() + ".jpg");

            lastcroppic = spath;
            diffpicpath = picpath;

            FileExistMapPath(spath, FileCheckModel.M, out _spath_common_mappath);

            _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //释放
            _sourceimg_common.Dispose();
            _currimg_common.Dispose();
            _g_common.Dispose();

            //处理原文件
            int filecachecode = filecache.GetHashCode();

            //文件缓存方式:Delete,删除原文件
            if (filecachecode == 1)
            {
                System.IO.File.Delete(_sourceimg_common_mappath);
            }

            //返回相对虚拟路径
            warning = "";
            return(spath);
        }

        checkmessage.Append("error:未能找到剪切原图片;");

        warning = checkmessage.ToString().TrimEnd(';');

        return("");
    }
Пример #40
0
        public static System.Drawing.Bitmap Combine(string[] files, int paddingY, string infoString)
        {
            //read all images into memory
            List <System.Drawing.Bitmap> images = new List <System.Drawing.Bitmap>();

            System.Drawing.Bitmap finalImage = null;

            try
            {
                int INFOSTRINGHEIGHT = string.IsNullOrEmpty(infoString) ? 0 : 100; // for MTN string
                int width            = 0;
                int height           = INFOSTRINGHEIGHT;

                foreach (string image in files)
                {
                    //create a Bitmap from the file and add it to the list
                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);

                    //update the size of the final bitmap
                    height += bitmap.Height + paddingY;
                    width   = bitmap.Width > width ? bitmap.Width : width;

                    images.Add(bitmap);
                }

                //create a bitmap to hold the combined image
                finalImage = new System.Drawing.Bitmap(width, height);

                //get a graphics object from the image so we can draw on it
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
                {
                    //set background color
                    g.Clear(System.Drawing.Color.Gray);

                    // fill mtn info if available
                    if (!string.IsNullOrEmpty(infoString))
                    {
                        g.SmoothingMode = SmoothingMode.AntiAlias;
                        g.DrawString(infoString,
                                     new Font("Arial", 12, FontStyle.Bold),
                                     SystemBrushes.WindowText, new Point(paddingY, paddingY));
                    }

                    //go through each image and draw it on the final image
                    int offset = INFOSTRINGHEIGHT;
                    foreach (System.Drawing.Bitmap image in images)
                    {
                        g.DrawImage(image,
                                    new System.Drawing.Rectangle(0, offset, image.Width, image.Height));
                        offset += image.Height + paddingY;
                    }
                }



                return(finalImage);
            }
            catch (Exception ex)
            {
                if (finalImage != null)
                {
                    finalImage.Dispose();
                }

                throw ex;
            }
            finally
            {
                //clean up memory
                foreach (System.Drawing.Bitmap image in images)
                {
                    image.Dispose();
                }
            }
        }
Пример #41
0
        public void OldMethodForImageFilm()
        {
            //List<System.Drawing.Bitmap> bitimages = new List<System.Drawing.Bitmap>();
            System.Drawing.Bitmap finalImage = null;

            int width  = 0;
            int height = 0;

            foreach (var image in ImagesZip)
            {
                //create a Bitmap from the file and add it to the list
                if (image.IsZIPSelected == true)
                {
                    //System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image.Path);

                    //update the size of the final bitmap
                    height += (int)((double)ExportHeightZip * 0.3);
                    width   = (int)((double)ExportWidthZip * 0.3) > width ? (int)((double)ExportWidthZip * 0.3) : width;

                    //bitimages.Add(bitmap);
                }
            }

            //create a bitmap to hold the combined image
            finalImage = new System.Drawing.Bitmap(width, height);

            //get a graphics object from the image so we can draw on it
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
            {
                //set background color
                g.Clear(System.Drawing.Color.Black);

                //go through each image and draw it on the final image
                int offset = 0;
                //foreach (System.Drawing.Bitmap image in bitimages)
                //{
                //    g.DrawImage(image, new System.Drawing.Rectangle(0, offset, (int)ExportWidthZip, (int)ExportHeightZip));
                //    offset += (int)ExportHeightZip;
                //}
                foreach (var image in ImagesZip)
                {
                    if (image.IsZIPSelected == true)
                    {
                        Bitmap b = compressimagesize(new Bitmap(image.Path));
                        {
                            g.DrawImage(b, new System.Drawing.Rectangle(0, offset, (int)b.Width, (int)b.Height));
                            offset += (int)b.Height;
                            b.Dispose();
                            Thread.Sleep(20);
                        }
                    }
                }
            }
            using (var ms = new MemoryStream())
            {
                using (FileStream fs = new FileStream(Path.Combine(/*tempPath*/ "", "imagefilm." + SelectedFileExtension), FileMode.Create, FileAccess.ReadWrite))
                {
                    finalImage.Save(ms, ImageFormat.Jpeg);
                    byte[] bytes = ms.ToArray();
                    fs.Write(bytes, 0, bytes.Length);
                }
            }
        }
Пример #42
0
 public override System.Drawing.Bitmap GetNext()
 {
     System.Drawing.Bitmap result;
     lock (this.newBitmap)
     {
         lock (this.oldBitmap)
         {
             if (this.nowState == MarqueeDisplayState.First)
             {
                 this.nowPosition = (int)this.nowPositionF;
                 int arg_52_0 = (this.newBitmap.Width - this.nowPosition) / 2;
                 System.Drawing.Bitmap   bitmap   = new System.Drawing.Bitmap(this.oldBitmap);
                 System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap);
                 System.Drawing.Pen      pen      = new System.Drawing.Pen(System.Drawing.Color.Red);
                 while (this.nowy > 8)
                 {
                     this.nowx -= 8;
                     this.nowy -= 8;
                 }
                 if (this.nowy > 0)
                 {
                     for (int i = 0; i < this.newBitmap.Height; i += 8)
                     {
                         graphics.DrawImage(this.newBitmap, new System.Drawing.Rectangle(this.nowx - 8, 0, 8, this.nowy), new System.Drawing.Rectangle(this.nowx - 8, 0, 8, this.nowy), System.Drawing.GraphicsUnit.Pixel);
                         for (int j = 0; j < 8; j++)
                         {
                             try
                             {
                                 if (this.newBitmap.GetPixel(this.nowx + j, i + this.nowy).R > 10)
                                 {
                                     graphics.DrawLine(pen, new System.Drawing.Point(0, i + this.nowy), new System.Drawing.Point(this.nowx - 8, i + this.nowy));
                                     break;
                                 }
                             }
                             catch
                             {
                             }
                         }
                     }
                 }
                 if (this.nowx > 0)
                 {
                     graphics.DrawImage(this.newBitmap, new System.Drawing.Rectangle(this.nowx, 0, this.newBitmap.Width - this.nowx, this.newBitmap.Height), new System.Drawing.Rectangle(this.nowx, 0, this.newBitmap.Width - this.nowx, this.newBitmap.Height), System.Drawing.GraphicsUnit.Pixel);
                 }
                 this.nowy += (int)this.step;
                 if (this.nowx < 0)
                 {
                     this.nowState = MarqueeDisplayState.Stay;
                 }
                 result = bitmap;
             }
             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);
             }
             else
             {
                 result = this.Exit.GetNext();
             }
         }
     }
     return(result);
 }
Пример #43
0
        private void backgroundToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BackgroundDialog dlg = new BackgroundDialog();

            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (BankDescription bank in Editor.currentLevel.loadedBanks)
                {
                    if (bank.type == BankDescription.BankType.Background)
                    {
                        bank.ROM_Start  = dlg.selectedBank.ROM_Start;
                        bank.compressed = dlg.selectedBank.compressed;
                        bank.arg        = dlg.selectedBank.arg;
                        if (dlg.imageFileName != null)
                        {
                            Bitmap bmp = (Bitmap)Bitmap.FromFile(dlg.imageFileName);
                            if (bmp.Width != 249 || bmp.Height != 249)
                            {
                                Bitmap destImage = new Bitmap(249, 249, PixelFormat.Format32bppArgb);

                                destImage.SetResolution(bmp.HorizontalResolution, bmp.VerticalResolution);

                                using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(destImage))
                                {
                                    graphics.CompositingMode    = CompositingMode.SourceCopy;
                                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                                    graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                    graphics.SmoothingMode      = SmoothingMode.HighQuality;
                                    graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                                    using (ImageAttributes wrapMode = new ImageAttributes())
                                    {
                                        wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                                        graphics.DrawImage(bmp, new Rectangle(0, 0, 249, 249), 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, wrapMode);
                                    }
                                }
                                EmulationState.messages.AppendMessage("Selected image has been resized from " + bmp.Width + " x " + bmp.Height + " pixels to 256x256 pixels.", "Information");
                                bmp.Dispose();
                                bmp = destImage;
                            }

                            BitmapData dat   = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                            byte[]     bytes = new byte[bmp.Width * bmp.Height * 4];
                            System.Runtime.InteropServices.Marshal.Copy(dat.Scan0, bytes, 0, bytes.Length);
                            int stride = dat.Stride;
                            bmp.UnlockBits(dat);
                            byte[] newBankValue = new byte[256 * 256 * 2 + 10 * 8 * 4];
                            int    cursor       = 0;
                            for (int tileY = 0; tileY < 8; tileY++)
                            {
                                for (int tileX = 0; tileX < 8; tileX++)
                                {
                                    for (int y = 0; y < 32; y++)
                                    {
                                        for (int x = 0; x < 32; x++)
                                        {
                                            int   offset   = ((x + tileX * 31) * 4 + (y + tileY * 31) * stride);
                                            short newValue = (short)(((bytes[offset + 2] & 0xF8) << 8) | ((bytes[offset + 1] & 0xF8) << 3) | (bytes[offset] >> 2));
                                            newBankValue[cursor++] = (byte)(newValue >> 8);
                                            newBankValue[cursor++] = (byte)(newValue & 0xFF);
                                        }
                                    }
                                }
                            }
                            for (int y = 0; y < 8; y++)
                            {
                                for (int x = 0; x < 10; x++)
                                {
                                    cvt.writeInt32(newBankValue, cursor, 0xA000000 + (x % 8 + y * 8) * 0x800);
                                    cursor += 4;
                                }
                            }
                            bmp.Dispose();
                            if (bank.compressed)
                            {
                                newBankValue = SM64RAM.MIO0.encode_MIO0(newBankValue);
                            }
                            bank.ROM_End = bank.ROM_Start + (uint)newBankValue.Length;
                            Array.Copy(newBankValue, 0, EmulationState.instance.ROM, bank.ROM_Start, newBankValue.Length);
                            System.IO.File.WriteAllBytes(EmulationState.instance.ROMName, EmulationState.instance.ROM);
                            EmulationState.instance.banks[0xA] = new EmulationState.RAMBank(bank.ID, (int)bank.ROM_Start, (int)bank.ROM_End, bank.compressed);
                            Editor.projectSettings.banks.Add(bank);
                        }
                    }
                }
            }
        }
Пример #44
0
    /// <summary>
    /// 根据指定:缩略宽、高,缩略图片并保存
    /// 返回图片虚拟路径,和一个警告信息,可根据此信息获取图片合成信息
    /// </summary>
    /// <param name="picpath">原图路径</param>
    /// <param name="model">缩略模式[X,Y,XY](默认XY模式)</param>
    /// <param name="spath">文件保存路径(默认跟路径)</param>
    /// <param name="imgtype">图片保存类型</param>
    /// <param name="mwidth">缩略宽度(默认原图高度)</param>
    /// <param name="mheight">缩略高度(默认原图高度)</param>
    /// <param name="filecache">原文件处理方式</param>
    /// <param name="warning">处理警告信息</param>
    /// <returns>错误,返回错误信息;成功,返回图片路径</returns>
    public static string Resizepic(string picpath, ResizeType model, string spath, ImageType imgtype, double?mwidth, double?mheight, FileCache filecache, out string warning)
    {
        //反馈信息
        System.Text.StringBuilder checkmessage = new System.Text.StringBuilder();

        //文件保存路径
        spath = string.IsNullOrEmpty(spath) ? "/" : spath;

        //缩略宽度
        double swidth = mwidth.HasValue ? double.Parse(mwidth.ToString()) : 0;

        //缩略高度
        double sheight = mheight.HasValue ? double.Parse(mheight.ToString()) : 0;

        //从指定源图片,创建image对象
        string _sourceimg_common_mappath = "";

        //检测源文件
        bool checkfile = false;

        checkfile = FileExistMapPath(picpath, FileCheckModel.C, out _sourceimg_common_mappath);

        System.Drawing.Image    _sourceimg_common = null;
        System.Drawing.Bitmap   _currimg_common   = null;
        System.Drawing.Graphics _g_common         = null;

        if (checkfile == true)
        {
            //从源文件创建imgage
            _sourceimg_common = System.Drawing.Image.FromFile(_sourceimg_common_mappath);

            #region 缩略模式
            //缩略模式
            switch (model)
            {
            case ResizeType.X:

                #region X模式

                //根据给定尺寸,获取绘制比例
                double _width_scale = swidth / _sourceimg_common.Width;
                //高着比例
                sheight = _sourceimg_common.Height * _width_scale;

                #endregion
                ; break;

            case ResizeType.Y:
                #region Y模式

                //根据给定尺寸,获取绘制比例
                double _height_scale = sheight / _sourceimg_common.Height;
                //宽着比例
                swidth = _sourceimg_common.Width * _height_scale;

                #endregion
                ; break;

            case ResizeType.XY:
                #region XY模式

                //当选择XY模式时,mwidth,mheight为必须值
                if (swidth < 0 || sheight < 0)
                {
                    checkmessage.Append("error:XY模式,mwidth,mheight为必须值;");
                }

                #endregion
                ; break;

            default:

                #region 默认XY模式

                //当默认XY模式时,mwidth,mheight为必须值
                if (swidth < 0 || sheight < 0)
                {
                    checkmessage.Append("error:你当前未选择缩略模式,系统默认XY模式,mwidth,mheight为必须值;");
                }

                ; break;
                #endregion
            }
            #endregion
        }
        else
        {
            checkmessage.Append("error:未能找到缩略原图片," + picpath + ";");
        }

        if (string.IsNullOrEmpty(checkmessage.ToString()))
        {
            //创建bitmap对象
            _currimg_common = new System.Drawing.Bitmap((int)swidth, (int)sheight);

            _g_common = Graphics.FromImage(_currimg_common);

            //设置画笔
            _g_common.CompositingMode   = System.Drawing.Drawing2D.CompositingMode.SourceOver;
            _g_common.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            _g_common.PixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.Half;

            //绘制图片
            _g_common.DrawImage(_sourceimg_common, new Rectangle(0, 0, (int)swidth, (int)sheight), new Rectangle(0, 0, _sourceimg_common.Width, _sourceimg_common.Height), GraphicsUnit.Pixel);

            //保存图片
            string _spath_common_mappath = "";

            //获取图片类型的hashcode值,生成图片后缀名
            int extro = imgtype.GetHashCode();

            string extend = extro == 0 ? ".jpg" : (extro == 1 ? ".gif" : (extro == 2 ? ".png" : ".jpg"));

            //全局文件名
            spath = spath + Guid.NewGuid().ToString() + extend;

            FileExistMapPath(spath, FileCheckModel.M, out _spath_common_mappath);

            switch (imgtype)
            {
            case ImageType.JPEG: _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Jpeg); break;

            case ImageType.GIF: _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Gif); break;

            case ImageType.PNG: _currimg_common.Save(_spath_common_mappath, System.Drawing.Imaging.ImageFormat.Png); break;
            }

            //释放
            _sourceimg_common.Dispose();
            _currimg_common.Dispose();
            _g_common.Dispose();

            //处理原文件
            int filecachecode = filecache.GetHashCode();

            //文件缓存方式:Delete,删除原文件
            if (filecachecode == 1)
            {
                System.IO.File.Delete(_sourceimg_common_mappath);
            }

            //返回相对虚拟路径
            warning = "";
            return(spath);
        }

        //释放
        if (_sourceimg_common != null)
        {
            _sourceimg_common.Dispose();
        }
        if (_currimg_common != null)
        {
            _currimg_common.Dispose();
        }
        if (_g_common != null)
        {
            _g_common.Dispose();
        }

        warning = checkmessage.ToString().TrimEnd(';');

        return("");
    }
Пример #45
0
        private void RedrawField(int x, int y, System.Drawing.Graphics g)
        {
            {
                if (!knownFields[x, y])
                {
                    if (flags[x, y])
                    {
                        g.DrawImage(gameGraphics[4], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                    }
                    else
                    {
                        g.DrawImage(gameGraphics[1], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                    }
                }
                else
                {
                    switch (fields[x, y])
                    {
                    case 0:
                        g.DrawImage(gameGraphics[7], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                        break;

                    case 1:
                        g.DrawImage(gameGraphics[8], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                        break;

                    case 2:
                        g.DrawImage(gameGraphics[9], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                        break;

                    case 3:
                        g.DrawImage(gameGraphics[10], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                        break;

                    case 4:
                        g.DrawImage(gameGraphics[11], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                        break;

                    case 5:
                        g.DrawImage(gameGraphics[12], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                        break;

                    case 6:
                        g.DrawImage(gameGraphics[13], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                        break;

                    case 7:
                        g.DrawImage(gameGraphics[14], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                        break;

                    case 8:
                        g.DrawImage(gameGraphics[15], FIELD_SIZE * x + 3, FIELD_SIZE * y + 3, FIELD_SIZE, FIELD_SIZE);
                        break;
                    }
                }
            }
        }
Пример #46
0
        public static Bitmap ResizeImage(Bitmap originalImage, int height, int width, bool letterbox, string lbxColor)
        {
            int srcWidth  = originalImage.Width;
            int srcHeight = originalImage.Height;

            Size newSize;

            if (height != 0 && width != 0)
            {
                newSize = GetOutSize(originalImage, width, height);
            }
            else
            {
                if (srcWidth > srcHeight)
                {
                    newSize = GetOutSize(originalImage, width, height);
                }
                else
                {
                    newSize = GetOutSize(originalImage, height, width);
                }
            }
            //Decimal sizeRatio = ((Decimal)srcHeight / srcWidth);
            //int thumbHeight = Decimal.ToInt32(sizeRatio * resizeWidth);

            Bitmap bmp = null;

            if (!letterbox)
            {
                bmp = new Bitmap(newSize.Width, newSize.Height);
            }
            else
            {
                bmp = new Bitmap(width, height);
            }

            using (System.Drawing.Graphics gr = System.Drawing.Graphics.FromImage(bmp))
            {
                Color cl = Color.Black;

                if (!String.IsNullOrEmpty(lbxColor))
                {
                    cl = ColorTranslator.FromHtml(lbxColor);
                }
                else
                {
                    cl = ColorTranslator.FromHtml("transparent");
                }

                using (Brush brBG = new SolidBrush(cl))
                {
                    gr.FillRectangle(brBG, new Rectangle(0, 0, width, height));
                }

                gr.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                gr.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                gr.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.Half;

                Point newPos = new Point(0, 0);

                if (letterbox)
                {
                    newPos = new Point((width / 2) - (newSize.Width / 2), (height / 2) - (newSize.Height / 2));
                }

                System.Drawing.Rectangle rectDestination = new System.Drawing.Rectangle(newPos, newSize);

                gr.DrawImage(originalImage, rectDestination, 0, 0, srcWidth, srcHeight, GraphicsUnit.Pixel);
            }
            return(bmp);
        }
Пример #47
0
        /// <summary>
        /// Return the icon which should display for this asset.
        /// </summary>
        /// <returns></returns>
        public Bitmap DisplayIcon()
        {
            // Load the primary image for this asset - noting that for the 'standard' types
            // (computer, laptop, server, domaincontroller) that we will add the StockStatus to the
            // name to more accurately affect the asset
            string displayIcon = _icon;

            if (displayIcon == "computer.png" || displayIcon == "laptop.png" || displayIcon == "domaincontroller.png" || displayIcon == "server.png")
            {
                string stockStub = "";
                switch (_stockStatus)
                {
                case STOCKSTATUS.disposed: stockStub = "_disposed"; break;

                case STOCKSTATUS.inuse: break;

                case STOCKSTATUS.pendingdisposal: stockStub = "_pending"; break;

                case STOCKSTATUS.stock: stockStub = "_stock"; break;
                }
                //
                displayIcon = displayIcon.Substring(0, displayIcon.Length - 4) + stockStub + ".png";
            }

            // Audited?
            if ((LastAudit == DateTime.MinValue) && (_stockStatus == STOCKSTATUS.inuse) && (displayIcon == "computer.png"))
            {
                displayIcon = displayIcon.Substring(0, displayIcon.Length - 4) + "_notaudited.png";
            }

            // From this we can get the icon
            Bitmap baseImage    = IconMapping.LoadIcon(displayIcon, IconMapping.Iconsize.Small);
            Bitmap displayImage = new Bitmap(16, 16);

            System.Drawing.Graphics graphics = Graphics.FromImage(displayImage);
            graphics.DrawImage(baseImage, new Point(0, 0));

            // Now add on (any) overlays for the agent status and reaudit request
            // First icon is a little indicator to show if a reaudit has been requested
            if (RequestAudit)
            {
                Bitmap reauditImage = Properties.Resources.asset_reaudit;
                graphics.DrawImage(reauditImage, new Point(0, 9));
            }

            // ..then the AuditAgent Status image in the top left
            if (AgentStatus == Asset.AGENTSTATUS.deployed)
            {
                Bitmap agentImage = Properties.Resources.agent_stopped;
                graphics.DrawImage(agentImage, new Point(0, 0));
            }

            else if (AgentStatus == Asset.AGENTSTATUS.Running)
            {
                Bitmap agentImage = Properties.Resources.agent_active;
                graphics.DrawImage(agentImage, new Point(0, 0));
            }

            // Return these icons
            return(displayImage);
        }
Пример #48
0
        /// <summary>
        /// A static improved function to blur an image
        /// </summary>
        /// <param name="image">Image to blur</param>
        /// <param name="rectangle">Rectangle to use in generating the blur</param>
        /// <param name="blurSize">Size of the blur</param>
        /// <returns></returns>
        public unsafe static System.Drawing.Bitmap BlurFastImproved(this System.Drawing.Bitmap image, Rectangle rectangle, Int32 blurSize)
        {
            System.Drawing.Bitmap blurred = new System.Drawing.Bitmap(image.Width, image.Height);

            // make an exact copy of the bitmap provided
            using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(blurred))
                graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
                                   new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

            // Lock the bitmap's bits
            BitmapData blurredData = blurred.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadWrite, blurred.PixelFormat);

            // Get bits per pixel for current PixelFormat
            int bitsPerPixel = Image.GetPixelFormatSize(blurred.PixelFormat);

            // Get pointer to first line
            byte *scan0 = (byte *)blurredData.Scan0.ToPointer();

            // look at every pixel in the blur rectangle
            for (int xx = rectangle.X; xx < rectangle.X + rectangle.Width; xx++)
            {
                for (int yy = rectangle.Y; yy < rectangle.Y + rectangle.Height; yy++)
                {
                    int avgR = 0, avgG = 0, avgB = 0;
                    int blurPixelCount = 0;

                    // average the color of the red, green and blue for each pixel in the
                    // blur size while making sure you don't go outside the image bounds
                    for (int x = xx; (x < xx + blurSize && x < image.Width); x++)
                    {
                        for (int y = yy; (y < yy + blurSize && y < image.Height); y++)
                        {
                            // Get pointer to RGB
                            byte *data = scan0 + x * blurredData.Stride + y * bitsPerPixel / 8;

                            avgB += data[0]; // Blue
                            avgG += data[1]; // Green
                            avgR += data[2]; // Red

                            blurPixelCount++;
                        }
                    }

                    avgR = avgR / blurPixelCount;
                    avgG = avgG / blurPixelCount;
                    avgB = avgB / blurPixelCount;

                    // now that we know the average for the blur size, set each pixel to that color
                    for (int x = xx; x < xx + blurSize && x < image.Width && x < rectangle.Width; x++)
                    {
                        for (int y = yy; y < yy + blurSize && y < image.Height && y < rectangle.Height; y++)
                        {
                            // Get pointer to RGB
                            byte *data = scan0 + x * blurredData.Stride + y * bitsPerPixel / 8;

                            // Change values
                            data[0] = (byte)avgB;
                            data[1] = (byte)avgG;
                            data[2] = (byte)avgR;
                        }
                    }
                }
            }

            // Unlock the bits
            blurred.UnlockBits(blurredData);

            return(blurred);
        }
        /// <summary>
        /// according to mouse wheel delta zoom in or zoom out DisplayImg
        /// </summary>
        /// <param name="DisplayImg"></param>
        /// <param name="WheelDelta"></param>
        /// <param name="mousePos"></param>
        public void ZoomPicture(System.Drawing.Bitmap DisplayImg, double WheelDelta, System.Drawing.Point mousePos)
        {
            if (mousePos.X == -1 && mousePos.Y == -1)
            {
                mousePos = origLeftTop;
            }

            double zoom;

            System.Drawing.Size LeftTopDelta = new System.Drawing.Size();
            try
            {
                if (WheelDelta > 0)
                {
                    if (totalZoom < 300)
                    {
                        zoom = Math.Pow(1.25, WheelDelta / 120.0);
                        LeftTopDelta.Width  = Convert.ToInt32(Convert.ToDouble(mousePos.X - origLeftTop.X) * 0.25);
                        LeftTopDelta.Height = Convert.ToInt32(Convert.ToDouble(mousePos.Y - origLeftTop.Y) * 0.25);
                        origLeftTop.X      -= LeftTopDelta.Width;
                        origLeftTop.Y      -= LeftTopDelta.Height;
                    }
                    else
                    {
                        zoom = 1;
                    }
                }
                else
                {
                    if (totalZoom > 0.03)
                    {
                        zoom = Math.Pow(0.85, WheelDelta / (-120.0));
                        LeftTopDelta.Width  = Convert.ToInt32(Convert.ToDouble(mousePos.X - origLeftTop.X) * 0.25);
                        LeftTopDelta.Height = Convert.ToInt32(Convert.ToDouble(mousePos.Y - origLeftTop.Y) * 0.25);
                        origLeftTop.X      += LeftTopDelta.Width;
                        origLeftTop.Y      += LeftTopDelta.Height;
                    }
                    else
                    {
                        zoom = 1;
                    }
                }
                totalZoom = totalZoom * zoom;


                DisplaySize.Width  = Convert.ToInt32(DisplaySize.Width * zoom);
                DisplaySize.Height = Convert.ToInt32(DisplaySize.Height * zoom);

                System.Drawing.Bitmap    newBitmap = new System.Drawing.Bitmap(_pcbox.Width, _pcbox.Height);
                System.Drawing.Rectangle ZoomSize  = new System.Drawing.Rectangle(origLeftTop.X, origLeftTop.Y, DisplaySize.Width, DisplaySize.Height);
                System.Drawing.Graphics  g         = System.Drawing.Graphics.FromImage(newBitmap);
                g.DrawImage(DisplayImg, ZoomSize);

                _pcbox.Image = newBitmap;
                _pcbox.Refresh();
            }
            catch (SystemException ex)
            {
                System.Windows.Forms.MessageBox.Show("In PictureboxZoomAndPan.ZoomPicture: " + ex.ToString());
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("In PictureboxZoomAndPan.ZoomPicture: " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
Пример #50
0
        // --- functions ---
        /// <summary>Gets the texture from this origin.</summary>
        /// <param name="texture">Receives the texture.</param>
        /// <returns>Whether the texture could be obtained successfully.</returns>
        public override bool GetTexture(out Texture texture)
        {
            Bitmap    bitmap = this.Bitmap;
            Rectangle rect   = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            /*
             * If the bitmap format is not already 32-bit BGRA,
             * then convert it to 32-bit BGRA.
             * */
            Color24[] p = null;
            if (bitmap.PixelFormat != PixelFormat.Format32bppArgb && bitmap.PixelFormat != PixelFormat.Format24bppRgb)
            {
                /* Only store the color palette data for
                 * textures using a restricted palette
                 * With a large number of textures loaded at
                 * once, this can save a decent chunk of memory
                 * */
                p = new Color24[bitmap.Palette.Entries.Length];
                for (int i = 0; i < bitmap.Palette.Entries.Length; i++)
                {
                    p[i] = bitmap.Palette.Entries[i];
                }
            }

            if (bitmap.PixelFormat != PixelFormat.Format32bppArgb)
            {
                Bitmap compatibleBitmap          = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format32bppArgb);
                System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(compatibleBitmap);
                graphics.DrawImage(bitmap, rect, rect, GraphicsUnit.Pixel);
                graphics.Dispose();
                bitmap = compatibleBitmap;
            }

            /*
             * Extract the raw bitmap data.
             * */
            BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);

            if (data.Stride == 4 * data.Width)
            {
                /*
                 * Copy the data from the bitmap
                 * to the array in BGRA format.
                 * */
                byte[] raw = new byte[data.Stride * data.Height];
                System.Runtime.InteropServices.Marshal.Copy(data.Scan0, raw, 0, data.Stride * data.Height);
                bitmap.UnlockBits(data);
                int width  = bitmap.Width;
                int height = bitmap.Height;

                /*
                 * Change the byte order from BGRA to RGBA.
                 * */
                for (int i = 0; i < raw.Length; i += 4)
                {
                    byte temp = raw[i];
                    raw[i]     = raw[i + 2];
                    raw[i + 2] = temp;
                }

                texture = new Texture(width, height, 32, raw, p);
                texture = texture.ApplyParameters(this.Parameters);
                return(true);
            }

            /*
             * The stride is invalid. This indicates that the
             * CLI either does not implement the conversion to
             * 32-bit BGRA correctly, or that the CLI has
             * applied additional padding that we do not
             * support.
             * */
            bitmap.UnlockBits(data);
            texture = null;
            return(false);
        }
Пример #51
0
        /// <summary>
        /// the main difference with a Group row and a regular row is the way it is painted on the control.
        /// the Paint method is therefore overridden and specifies how the Group row is painted.
        /// Note: this method is not implemented optimally. It is merely used for demonstration purposes
        /// </summary>
        /// <param name="graphics"></param>
        /// <param name="clipBounds"></param>
        /// <param name="rowBounds"></param>
        /// <param name="rowIndex"></param>
        /// <param name="rowState"></param>
        /// <param name="isFirstDisplayedRow"></param>
        /// <param name="isLastVisibleRow"></param>
        protected override void Paint(System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle rowBounds, int rowIndex, DataGridViewElementStates rowState, bool isFirstDisplayedRow, bool isLastVisibleRow)
        {
            if (this.isGroupRow)
            {
                OfferBookGrid grid = (OfferBookGrid)this.DataGridView;

                int rowHeadersWidth = grid.RowHeadersVisible ? grid.RowHeadersWidth : 0;

                // this can be optimized
                Color color  = base.DataGridView.AlternatingRowsDefaultCellStyle.BackColor;
                Brush brush  = new SolidBrush(grid.GroupHeaderBackColor);
                Brush brush2 = new SolidBrush(grid.GroupHeaderUnderlineColor);
                Brush brush3 = new SolidBrush(grid.GroupHeaderFontColor);

                int       gridwidth  = grid.Columns.GetColumnsWidth(DataGridViewElementStates.Displayed);
                Rectangle rowBounds2 = grid.GetRowDisplayRectangle(this.Index, true);

                // draw the background
                graphics.FillRectangle(brush, rowBounds.Left + rowHeadersWidth - grid.HorizontalScrollingOffset, rowBounds.Top, gridwidth, rowBounds.Height - 1);

                // draw text, using the current grid font
                string[] s          = group.Text.Split('|');
                SizeF    stringSize = new SizeF();

                stringSize = graphics.MeasureString(s[1], grid.GroupHeaderFont);

                // Não mostrar a corretora
                //graphics.DrawString(s[0], grid.GroupHeaderFont, brush3, grid.Columns[0].Width - stringSize.Width - 5, rowBounds.Bottom - 18);

                if (stringSize.Width > (grid.Columns[1].Width - 10))
                {
                    string texto = s[1].ToInt64().ToNumeroAbreviado();

                    stringSize = graphics.MeasureString(texto, grid.GroupHeaderFont);
                    graphics.DrawString(texto, grid.GroupHeaderFont, brush3, grid.Columns[0].Width + grid.Columns[1].Width - stringSize.Width - 5, rowBounds.Bottom - 18);
                }
                else
                {
                    switch (((OfferBookGrid)this.DataGridView).Type)
                    {
                    case GridType.Buy:
                        graphics.DrawString(s[1], grid.GroupHeaderFont, brush3, grid.Columns[0].Width + grid.Columns[1].Width - stringSize.Width - 5, rowBounds.Bottom - 18);
                        break;

                    case GridType.Sell:
                        graphics.DrawString(s[1], grid.GroupHeaderFont, brush3, grid.Columns[0].Width + 5, rowBounds.Bottom - 18);
                        break;
                    }
                }

                stringSize = graphics.MeasureString(s[2], grid.GroupHeaderFont);

                switch (((OfferBookGrid)this.DataGridView).Type)
                {
                case GridType.Buy:
                    graphics.DrawString(s[2], grid.GroupHeaderFont, brush3, grid.Columns[0].Width + grid.Columns[1].Width + grid.Columns[2].Width - stringSize.Width - 5, rowBounds.Bottom - 18);
                    break;

                case GridType.Sell:
                    graphics.DrawString(s[2], grid.GroupHeaderFont, brush3, rowBounds.Left + rowHeadersWidth - grid.HorizontalScrollingOffset + 4, rowBounds.Bottom - 18);
                    break;
                }

                //draw bottom line
                graphics.FillRectangle(brush2, rowBounds.Left + rowHeadersWidth - grid.HorizontalScrollingOffset, rowBounds.Bottom - 2, gridwidth - 1, 1);

                // draw right vertical bar
                if (grid.CellBorderStyle == DataGridViewCellBorderStyle.SingleVertical || grid.CellBorderStyle == DataGridViewCellBorderStyle.Single)
                {
                    graphics.FillRectangle(brush2, rowBounds.Left + rowHeadersWidth - grid.HorizontalScrollingOffset + gridwidth - 1, rowBounds.Top, 1, rowBounds.Height);
                }



                if (group.Collapsed)
                {
                    switch (((OfferBookGrid)this.DataGridView).Type)
                    {
                    case GridType.Buy:
                        if (grid.ExpandIcon != null)
                        {
                            graphics.DrawImage(grid.ExpandIcon, rowBounds.Left + rowHeadersWidth - grid.HorizontalScrollingOffset + 4, rowBounds.Bottom - 18, 11, 11);
                        }
                        break;

                    case GridType.Sell:
                        if (grid.ExpandIcon != null)
                        {
                            //graphics.DrawImage(grid.ExpandIcon, grid.Columns[0].Width + grid.Columns[1].Width + grid.Columns[2].Width - 15, rowBounds.Bottom - 18, 11, 11);
                            graphics.DrawImage(grid.ExpandIcon, rowBounds.Right - 15, rowBounds.Bottom - 18, 11, 11);
                        }
                        break;
                    }
                }
                else
                {
                    //if (grid.CollapseIcon != null)
                    //  Graphics.DrawImage(grid.CollapseIcon, rowBounds.Left + rowHeadersWidth - grid.HorizontalScrollingOffset + 4, rowBounds.Bottom - 18, 11, 11);

                    switch (((OfferBookGrid)this.DataGridView).Type)
                    {
                    case GridType.Buy:
                        if (grid.ExpandIcon != null)
                        {
                            graphics.DrawImage(grid.CollapseIcon, rowBounds.Left + rowHeadersWidth - grid.HorizontalScrollingOffset + 4, rowBounds.Bottom - 18, 11, 11);
                        }
                        break;

                    case GridType.Sell:
                        if (grid.ExpandIcon != null)
                        {
                            graphics.DrawImage(grid.CollapseIcon, rowBounds.Right - 15, rowBounds.Bottom - 18, 11, 11);
                        }
                        break;
                    }
                }

                brush.Dispose();
                brush2.Dispose();
                brush3.Dispose();
            }

            base.Paint(graphics, clipBounds, rowBounds, rowIndex, rowState, isFirstDisplayedRow, isLastVisibleRow);
        }
Пример #52
0
        void RenderFontShadow(
            System.Drawing.Graphics graphics,
            System.Drawing.FontFamily fontFamily,
            System.Drawing.FontStyle fontStyle,
            int nfontSize,
            string pszText,
            System.Drawing.Rectangle rtDraw,
            System.Drawing.StringFormat strFormat)
        {
            Rectangle rectbmp = new Rectangle(0, 0, m_pBkgdBitmap.Width, m_pBkgdBitmap.Height);

            System.Drawing.Bitmap pBmpMask =
                m_pBkgdBitmap.Clone(rectbmp, PixelFormat.Format32bppArgb);

            System.Drawing.Bitmap pBmpFontBodyBackup =
                m_pBkgdBitmap.Clone(rectbmp, PixelFormat.Format32bppArgb);

            System.Drawing.Graphics   graphicsMask = System.Drawing.Graphics.FromImage(pBmpMask);
            System.Drawing.SolidBrush brushBlack   = new System.Drawing.SolidBrush(System.Drawing.Color.FromArgb(0, 0, 0));
            graphicsMask.FillRectangle(brushBlack, 0, 0, m_pBkgdBitmap.Width, m_pBkgdBitmap.Height);

            System.Drawing.Bitmap pBmpDisplay =
                m_pBkgdBitmap.Clone(rectbmp, PixelFormat.Format32bppArgb);
            System.Drawing.Graphics graphicsBkgd = System.Drawing.Graphics.FromImage(pBmpDisplay);

            graphicsMask.CompositingMode    = graphics.CompositingMode;
            graphicsMask.CompositingQuality = graphics.CompositingQuality;
            graphicsMask.InterpolationMode  = graphics.InterpolationMode;
            graphicsMask.SmoothingMode      = graphics.SmoothingMode;
            graphicsMask.TextRenderingHint  = graphics.TextRenderingHint;
            graphicsMask.PageUnit           = graphics.PageUnit;
            graphicsMask.PageScale          = graphics.PageScale;

            graphicsBkgd.CompositingMode    = graphics.CompositingMode;
            graphicsBkgd.CompositingQuality = graphics.CompositingQuality;
            graphicsBkgd.InterpolationMode  = graphics.InterpolationMode;
            graphicsBkgd.SmoothingMode      = graphics.SmoothingMode;
            graphicsBkgd.TextRenderingHint  = graphics.TextRenderingHint;
            graphicsBkgd.PageUnit           = graphics.PageUnit;
            graphicsBkgd.PageScale          = graphics.PageScale;

            m_pFontBodyShadow.DrawString(
                graphicsMask,
                fontFamily,
                fontStyle,
                nfontSize,
                pszText,
                rtDraw,
                strFormat);

            m_pShadowStrategy.DrawString(
                graphicsBkgd,
                fontFamily,
                fontStyle,
                nfontSize,
                pszText,
                rtDraw,
                strFormat);

            unsafe
            {
                UInt32 *pixelsSrc  = null;
                UInt32 *pixelsDest = null;
                UInt32 *pixelsMask = null;

                BitmapData bitmapDataSrc  = new BitmapData();
                BitmapData bitmapDataDest = new BitmapData();
                BitmapData bitmapDataMask = new BitmapData();
                Rectangle  rect           = new Rectangle(0, 0, m_pBkgdBitmap.Width, m_pBkgdBitmap.Height);

                pBmpFontBodyBackup.LockBits(
                    rect,
                    ImageLockMode.WriteOnly,
                    PixelFormat.Format32bppArgb,
                    bitmapDataSrc);

                pBmpDisplay.LockBits(
                    rect,
                    ImageLockMode.WriteOnly,
                    PixelFormat.Format32bppArgb,
                    bitmapDataDest);

                pBmpMask.LockBits(
                    rect,
                    ImageLockMode.WriteOnly,
                    PixelFormat.Format32bppArgb,
                    bitmapDataMask);


                // Write to the temporary buffer provided by LockBits.
                pixelsSrc  = (UInt32 *)(bitmapDataSrc.Scan0);
                pixelsDest = (UInt32 *)(bitmapDataDest.Scan0);
                pixelsMask = (UInt32 *)(bitmapDataMask.Scan0);

                if (pixelsSrc == null || pixelsDest == null || pixelsMask == null)
                {
                    return;
                }

                UInt32 col    = 0;
                int    stride = bitmapDataDest.Stride >> 2;
                if (m_bDiffuseShadow && m_bExtrudeShadow == false)
                {
                    for (UInt32 row = 0; row < bitmapDataDest.Height; ++row)
                    {
                        for (col = 0; col < bitmapDataDest.Width; ++col)
                        {
                            UInt32 index     = (UInt32)(row * stride + col);
                            Byte   nAlpha    = (Byte)(pixelsMask[index] & 0xff);
                            UInt32 clrShadow = (UInt32)(0xff000000 | (UInt32)(m_clrShadow.R << 16) | (UInt32)(m_clrShadow.G << 8) | m_clrShadow.B);
                            if (nAlpha > 0)
                            {
                                UInt32 clrtotal = clrShadow;
                                for (int i = 2; i <= m_nShadowThickness; ++i)
                                {
                                    pixelsSrc[index] = Alphablend(pixelsSrc[index], clrtotal, m_clrShadow.A);
                                }

                                pixelsDest[index] = pixelsSrc[index];
                            }
                        }
                    }
                }
                else
                {
                    for (UInt32 row = 0; row < bitmapDataDest.Height; ++row)
                    {
                        for (col = 0; col < bitmapDataDest.Width; ++col)
                        {
                            UInt32 index     = (UInt32)(row * stride + col);
                            Byte   nAlpha    = (Byte)(pixelsMask[index] & 0xff);
                            UInt32 clrShadow = (UInt32)(0xff000000 | (UInt32)(m_clrShadow.R << 16) | (UInt32)(m_clrShadow.G << 8) | m_clrShadow.B);
                            if (nAlpha > 0)
                            {
                                pixelsDest[index] = Alphablend(pixelsSrc[index], clrShadow, m_clrShadow.A);
                            }
                        }
                    }
                }

                pBmpMask.UnlockBits(bitmapDataMask);
                pBmpDisplay.UnlockBits(bitmapDataDest);
                pBmpFontBodyBackup.UnlockBits(bitmapDataSrc);

                graphics.DrawImage(pBmpDisplay, 0, 0, pBmpDisplay.Width, pBmpDisplay.Height);

                pBmpMask           = null;
                pBmpFontBodyBackup = null;
                pBmpDisplay        = null;
            }
        }
Пример #53
0
        private void button_ReadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();                                           //创建事例
            string         dir = Environment.GetFolderPath(Environment.SpecialFolder.Templates); //指定初始目录

            dlg.InitialDirectory = dir;                                                          //指定初始目录
            dlg.Title            = "图表对话框";
            dlg.ShowReadOnly     = true;                                                         //以只读方式打开
            dlg.ShowHelp         = true;                                                         //显示帮助按钮            ///////
            dlg.Filter           = "图表.jpg|*.jpg|图表.tif|*.tif|图表.bmp|*.bmp|所有文件|*.*";            //文件过滤器,指定打开文件类型
            //dlg.ShowDialog();//打开对话框
            //BMP 文件(*.bmp) | *.bmp | JPEG 文件(*.jpg, *.jpeg) | *.jpg, *.jpeg | PNG 文件(*.png) | *.png | GIF 文件(*.gif) | *.gif | TIFF 文件(*.tiff, *.tif) | *.tiff
            //MessageBox.Show(dlg.Title);//打开消息
            //dlg.Multiselect = true;//是否允许一次打开多个文件
            dlg.Multiselect = false;     //是否允许一次打开多个文件
                                         // if (dlg.ShowDialog() == DialogResult.OK)
                                         //{
            if (dlg.CheckPathExists)     //检查路径是否存在
            {
                if (dlg.CheckFileExists) //检查文件是否存在
                {
                    // if (dlg.ValidateNames)//检查是否有效Win32文件名
                    //  {
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        string s = dlg.FileNames[0];
                        // foreach (string s in dlg.FileNames)
                        //{                                //string fileName = dlg.FileName;
                        //MessageBox.Show("打开文件:" + s);//打开消息对话框

                        bmDraw = new Bitmap(this.pictureBox_Image.Width, this.pictureBox_Image.Height);
                        Bitmap inputimage = (Bitmap)Image.FromFile(s);

                        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bmDraw);

                        double scale_width  = Convert.ToDouble(bmDraw.Width) / inputimage.Width;
                        double scale_height = Convert.ToDouble(bmDraw.Height) / inputimage.Height;
                        double scale        = scale_width;
                        if (scale_width > scale_height)
                        {
                            scale = scale_height;
                        }

                        int       centerx   = bmDraw.Width / 2;
                        int       centery   = bmDraw.Height / 2;
                        int       newWidth  = Convert.ToInt32(inputimage.Width * scale / 2);
                        int       newHeight = Convert.ToInt32(inputimage.Height * scale / 2);
                        Rectangle rg        = new Rectangle(centerx - newWidth, centery - newHeight, newWidth * 2, newHeight * 2);
                        //将bm内rg所指定的区域绘制到bm1
                        g.DrawImage(inputimage, rg);
                        this.pictureBox_Image.Image = bmDraw;



                        var sourcePath = s;
                        if (!File.Exists(sourcePath))
                        {
                            Console.WriteLine("The source file you specified does not exist.");
                            Environment.Exit(1);
                        }

                        var lastDot    = sourcePath.LastIndexOf('.');
                        var targetPath = sourcePath.Insert(lastDot, "-quant");
                        //if(args.Length > 1)
                        //    targetPath = args[1];

                        var quantizer = new WuQuantizer();
                        // QuantizedPalette ColorPalette = new QuantizedPalette();
                        var    bitmap0 = new Bitmap(sourcePath);
                        Bitmap bitmap1 = ConvertTo32bpp(bitmap0);

                        using (var bitmap = bitmap1)
                        //using (var bitmap = new Bitmap(sourcePath))
                        {
                            using (var quantized = quantizer.QuantizeImage(bitmap))
                            {
                                QuantizedPalette palette = quantizer.palette;
                                //quantized.Save(targetPath, ImageFormat.Png);


                                inputimage   = new Bitmap(quantized);
                                scale_width  = Convert.ToDouble(bmDraw.Width) / inputimage.Width;
                                scale_height = Convert.ToDouble(bmDraw.Height) / inputimage.Height;
                                scale        = scale_width;
                                if (scale_width > scale_height)
                                {
                                    scale = scale_height;
                                }

                                centerx   = bmDraw.Width / 2;
                                centery   = bmDraw.Height / 2;
                                newWidth  = Convert.ToInt32(inputimage.Width * scale / 2);
                                newHeight = Convert.ToInt32(inputimage.Height * scale / 2);
                                rg        = new Rectangle(centerx - newWidth, centery - newHeight, newWidth * 2, newHeight * 2);
                                //将bm内rg所指定的区域绘制到bm1
                                g.DrawImage(inputimage, rg);
                                this.pictureBox_Image.Image = bmDraw;
                            }
                        }
                    }
                    // }
                }
            }
        }
Пример #54
0
        private void MapImage_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (_Map != null)
            {
                SharpMap.Geometries.Point p = this._Map.ImageToWorld(new System.Drawing.Point(e.X, e.Y));

                if (MouseMove != null)
                {
                    MouseMove(p, e);
                }

                if (Image != null && e.Location != mousedrag && !mousedragging && e.Button == MouseButtons.Left)
                {
                    mousedragImg  = this.Image.Clone() as Image;
                    mousedragging = true;
                }

                if (mousedragging)
                {
                    if (MouseDrag != null)
                    {
                        MouseDrag(p, e);
                    }

                    if (this.ActiveTool == Tools.Pan)
                    {
                        System.Drawing.Image    img = new System.Drawing.Bitmap(this.Size.Width, this.Size.Height);
                        System.Drawing.Graphics g   = System.Drawing.Graphics.FromImage(img);
                        g.Clear(Color.Transparent);
                        g.DrawImageUnscaled(mousedragImg, new System.Drawing.Point(e.Location.X - mousedrag.X, e.Location.Y - mousedrag.Y));
                        g.Dispose();
                        this.Image = img;
                    }
                    else if (this.ActiveTool == Tools.ZoomIn || this.ActiveTool == Tools.ZoomOut)
                    {
                        System.Drawing.Image    img = new System.Drawing.Bitmap(this.Size.Width, this.Size.Height);
                        System.Drawing.Graphics g   = System.Drawing.Graphics.FromImage(img);
                        g.Clear(Color.Transparent);
                        float scale = 0;
                        if (e.Y - mousedrag.Y < 0)                         //Zoom out
                        {
                            scale = (float)Math.Pow(1 / (float)(mousedrag.Y - e.Y), 0.5);
                        }
                        else                         //Zoom in
                        {
                            scale = 1 + (e.Y - mousedrag.Y) * 0.1f;
                        }
                        RectangleF rect = new RectangleF(0, 0, this.Width, this.Height);
                        if (_Map.Zoom / scale < _Map.MinimumZoom)
                        {
                            scale = (float)Math.Round(_Map.Zoom / _Map.MinimumZoom, 4);
                        }
                        rect.Width  *= scale;
                        rect.Height *= scale;
                        rect.Offset(this.Width / 2 - rect.Width / 2, this.Height / 2 - rect.Height / 2);
                        g.DrawImage(mousedragImg, rect);
                        g.Dispose();
                        this.Image = img;
                        if (MapZooming != null)
                        {
                            MapZooming(scale);
                        }
                    }
                }
            }
        }
Пример #55
0
        /// <summary>
        ///   根据指定宽度,高度,裁剪
        /// </summary>
        /// <param name="fromFileStream">图片流</param>
        /// <param name="fileSaveUrl">保存地址</param>
        /// <param name="templateWidth">指定要裁剪后的宽度</param>
        /// <param name="templateHeight">指定要裁剪后的高度</param>
        /// <param name="mode">裁剪方式</param>
        public static void CacheFilesMakeSmallImg(System.IO.Stream fromFileStream, string fileSaveUrl, System.Double templateWidth, System.Double templateHeight, string mode)
        {
            //从文件取得图片对象,并使用流中嵌入的颜色管理信息
            System.Drawing.Image myImage = System.Drawing.Image.FromStream(fromFileStream, true);

            int x         = 0;
            int y         = 0;
            int newWidth  = Convert.ToInt32(templateWidth);
            int newHeight = Convert.ToInt32(templateHeight);

            int ow = myImage.Width;
            int oh = myImage.Height;

            //当文件大于模板的宽度时,才生成缩略图
            //if (ow > newWidth)
            //if (File.Exists(fileSaveUrl))
            if (1 == 1)
            {
                switch (mode)
                {
                case "WH":
                    //如果上传图片的宽度[小于]指定宽度
                    if (myImage.Width < Convert.ToInt32(templateWidth))
                    {
                        //上传图片高度[大于]指定高度
                        if (myImage.Height > Convert.ToInt32(templateHeight))
                        {
                            //指定高,宽按比例
                            newWidth = myImage.Width * Convert.ToInt32(templateHeight) / myImage.Height;
                        }
                        else    //上传的图片的高度[小于]指定高度
                        {
                            //什么都有不做,但是,原样存一个副本到缩略图路径
                            //保存缩略图
                            newWidth  = myImage.Width;
                            newHeight = myImage.Height;
                        }
                    }
                    else    //上传图片的宽度[大于]指定宽度
                    {
                        //上传图片高度[大于]指定高度
                        if (myImage.Height > Convert.ToInt32(templateHeight))                                     //上传图片的宽度和高度同时[大于]指定宽高
                        {
                            if (myImage.Width > myImage.Height)                                                   //上传图片宽[大于]高
                            {
                                double whBL   = Convert.ToInt32(templateWidth) / Convert.ToInt32(templateHeight); //指定图片的宽高比例
                                double scwhBL = myImage.Width / myImage.Height;                                   //上传图片的宽高比例

                                //指定高,宽按比例
                                newWidth = myImage.Width * Convert.ToInt32(templateHeight) / myImage.Height;
                                //指定宽,高按比例
                                newHeight = myImage.Height * Convert.ToInt32(templateWidth) / myImage.Width;

                                if (whBL > scwhBL)    //推测,同比例缩放后 :上传的图片的高度[小于]指定高度
                                {
                                    newWidth = Convert.ToInt32(templateWidth);
                                }
                                else
                                {
                                    newHeight = Convert.ToInt32(templateHeight);
                                }
                            }
                            else                                                                                  //上传图片宽[小于]高
                            {
                                double hwBL   = Convert.ToInt32(templateHeight) / Convert.ToInt32(templateWidth); //指定图片的高宽比例
                                double schwBL = myImage.Width / myImage.Height;                                   //上传图片的高宽比例

                                //指定高,宽按比例
                                newWidth = myImage.Width * Convert.ToInt32(templateHeight) / myImage.Height;
                                //指定宽,高按比例
                                newHeight = myImage.Height * Convert.ToInt32(templateWidth) / myImage.Width;

                                if (hwBL < schwBL)    //推测,同比例缩放后 :上传的图片的高度[小于]指定高度
                                {
                                    newWidth = Convert.ToInt32(templateWidth);
                                }
                                else
                                {
                                    newHeight = Convert.ToInt32(templateHeight);
                                }
                            }
                        }
                        else    //上传的图片的高度[小于]指定高度
                        {
                            //指定宽,高按比例
                            newHeight = myImage.Height * Convert.ToInt32(templateWidth) / myImage.Width;
                        }
                    }
                    break;


                case "HW":    //指定高宽缩放(可能变形)
                    break;

                case "W":    //指定宽,高按比例
                    newHeight = myImage.Height * Convert.ToInt32(templateWidth) / myImage.Width;
                    break;

                case "H":    //指定高,宽按比例
                    newWidth = myImage.Width * Convert.ToInt32(templateHeight) / myImage.Height;
                    break;

                case "Default":    //指定高,宽按比例
                    newWidth  = myImage.Width;
                    newHeight = myImage.Height;
                    break;

                case "Cut":    //指定高宽裁减(不变形)
                    if ((double)myImage.Width / (double)myImage.Height > (double)newWidth / (double)newHeight)
                    {
                        oh = myImage.Height;
                        ow = myImage.Height * newWidth / newHeight;
                        y  = 0;
                        x  = (myImage.Width - ow) / 2;
                    }
                    else
                    {
                        ow = myImage.Width;
                        oh = myImage.Width * Convert.ToInt32(templateHeight) / newWidth;
                        x  = 0;
                        y  = (myImage.Height - oh) / 2;
                    }
                    break;

                default:
                    break;
                }

                //取得图片大小
                System.Drawing.Size mySize = new Size((int)newWidth, (int)newHeight);
                //新建一个bmp图片
                System.Drawing.Image 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(Color.White);
                //在指定位置画图
                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);

                //保存缩略图
                if (File.Exists(fileSaveUrl))
                {
                    File.SetAttributes(fileSaveUrl, FileAttributes.Normal);
                    File.Delete(fileSaveUrl);
                }

                bitmap.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
                g.Dispose();
                myImage.Dispose();
                bitmap.Dispose();
            }
        }
Пример #56
0
        void DrawToolBar(System.Drawing.Graphics g)
        {
            int offsetIcon = 0;

            g.DrawImage(Properties.Resources.View_1, new Point(offsetIcon, 1));
            g.DrawImage(Properties.Resources.View_2, new Point(offsetIcon   += _toolbarButtonOffset, 1));
            g.DrawImage(Properties.Resources.View_3, new Point(offsetIcon   += _toolbarButtonOffset, 1));
            g.DrawImage(Properties.Resources.View_4, new Point(offsetIcon   += _toolbarButtonOffset, 1));
            g.DrawImage(Properties.Resources.View_Top, new Point(offsetIcon += _toolbarButtonOffset, 1));
            g.DrawImage(Properties.Resources.View0, new Point(offsetIcon    += _toolbarButtonOffset, 1));
            g.DrawImage(Properties.Resources.View90, new Point(offsetIcon   += _toolbarButtonOffset, 1));
            g.DrawImage(Properties.Resources.View180, new Point(offsetIcon  += _toolbarButtonOffset, 1));
            g.DrawImage(Properties.Resources.View270, new Point(offsetIcon  += _toolbarButtonOffset, 1));
            if (ShowDimensions)
            {
                g.DrawImage(Properties.Resources.CotationHide, new Point(offsetIcon += _toolbarButtonOffset, 1));
            }
            else
            {
                g.DrawImage(Properties.Resources.CotationShow, new Point(offsetIcon += _toolbarButtonOffset, 1));
            }
        }
Пример #57
0
        public static System.Drawing.Bitmap CombineBitmap2(string[] files)
        {
            //read all images into memory
            List <System.Drawing.Bitmap> images = new List <System.Drawing.Bitmap>();

            System.Drawing.Bitmap finalImage = null;

            try
            {
                int width  = 0;
                int height = 0;

                foreach (string image in files)
                {
                    //create a Bitmap from the file and add it to the list
                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);

                    //update the size of the final bitmap
                    width += bitmap.Width;
                    height = bitmap.Height > height ? bitmap.Height : height;

                    images.Add(bitmap);
                }

                //create a bitmap to hold the combined image
                finalImage = new System.Drawing.Bitmap(width, height);

                //get a graphics object from the image so we can draw on it
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
                {
                    //set background color
                    g.Clear(System.Drawing.Color.Black);

                    //go through each image and draw it on the final image
                    int offset = 0;
                    foreach (System.Drawing.Bitmap image in images)
                    {
                        g.DrawImage(image,
                                    new System.Drawing.Rectangle(offset, 0, image.Width, image.Height));
                        //offset += image.Width;
                    }
                }

                return(finalImage);
            }
            catch (Exception ex)
            {
                if (finalImage != null)
                {
                    finalImage.Dispose();
                }

                throw ex;
            }
            finally
            {
                //clean up memory
                foreach (System.Drawing.Bitmap image in images)
                {
                    image.Dispose();
                }
            }
        }
Пример #58
0
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="originalImagePath">源图路径(物理路径)</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="mode">生成缩略图的方式</param>
    private void MakeThumbnail(string originalImagePath, int width, int height, string mode, string type)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

        int towidth  = width;
        int toheight = height;
        int x        = 0;
        int y        = 0;
        int ow       = originalImage.Width;
        int oh       = originalImage.Height;

        switch (mode)
        {
        case "HW":    //指定高宽缩放(可能变形)
            break;

        case "W":    //指定宽,高按比例
            toheight = originalImage.Height * width / originalImage.Width;
            break;

        case "H":    //指定高,宽按比例
            towidth = originalImage.Width * height / originalImage.Height;
            break;

        case "Cut":    //指定高宽裁减(不变形)
            if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
            {
                oh = originalImage.Height;
                ow = originalImage.Height * towidth / toheight;
                y  = 0;
                x  = (originalImage.Width - ow) / 2;
            }
            else
            {
                ow = originalImage.Width;
                oh = originalImage.Width * height / towidth;
                x  = 0;
                y  = (originalImage.Height - oh) / 2;
            }
            break;

        case "DB":    //等比缩放(不变形,如果高大按高,宽大按宽缩放)
            if ((double)originalImage.Width / (double)towidth < (double)originalImage.Height / (double)toheight)
            {
                toheight = height;
                towidth  = originalImage.Width * height / originalImage.Height;
            }
            else
            {
                towidth  = width;
                toheight = originalImage.Height * width / originalImage.Width;
            }
            break;

        default:
            break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

        //新建一个画板
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(System.Drawing.Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                    new System.Drawing.Rectangle(x, y, ow, oh),
                    System.Drawing.GraphicsUnit.Pixel);
        //System.Drawing.Font f = new System.Drawing.Font("Verdana", 12);
        //System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Gray);
        //g.DrawString(addText, f, b, 5, height - 40);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        try
        {
            //保存缩略图
            if (type == "JPG")
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            if (type == "BMP")
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            }
            if (type == "GIF")
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            }
            if (type == "PNG")
            {
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            }
            Response.ClearContent();
            Response.ContentType = "Image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
        catch (System.Exception e) { throw e; }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
        }
    }
Пример #59
0
        /// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="watermarkFilename">水印文件名</param>
        /// <param name="watermarkStatus">图片水印位置:0=不使用 1=左上 2=中上 3=右上 4=左中 ... 9=右下</param>
        /// <param name="quality">是否是高质量图片 取值范围0--100</param>
        /// <param name="watermarkTransparency">图片水印透明度 取值范围1--10 (10为不透明)</param>

        public static void AddImageSignPic(string Path, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            System.Drawing.Image    img = System.Drawing.Image.FromFile(Path);
            System.Drawing.Graphics g   = System.Drawing.Graphics.FromImage(img);

            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            System.Drawing.Image watermark = new System.Drawing.Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return;
            }

            System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes();
            System.Drawing.Imaging.ColorMap        colorMap        = new System.Drawing.Imaging.ColorMap();

            colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0);
            System.Drawing.Imaging.ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            float transparency = 0.5F;

            if (watermarkTransparency >= 1 && watermarkTransparency <= 10)
            {
                transparency = (watermarkTransparency / 10.0F);
            }

            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, transparency, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };

            System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
            case 1:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)(img.Height * (float).01);
                break;

            case 2:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)(img.Height * (float).01);
                break;

            case 3:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)(img.Height * (float).01);
                break;

            case 4:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 5:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 6:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                break;

            case 7:
                xpos = (int)(img.Width * (float).01);
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 8:
                xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;

            case 9:
                xpos = (int)((img.Width * (float).99) - (watermark.Width));
                ypos = (int)((img.Height * (float).99) - watermark.Height);
                break;
            }

            g.DrawImage(watermark, new System.Drawing.Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes);

            System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
            System.Drawing.Imaging.ImageCodecInfo   ici    = null;
            foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs)
            {
                //if (codec.MimeType.IndexOf("jpeg") > -1)
                if (codec.MimeType.Contains("jpeg"))
                {
                    ici = codec;
                }
            }
            System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }
            qualityParam[0] = quality;

            System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
            {
                img.Save(filename, ici, encoderParams);
            }
            else
            {
                img.Save(filename);
            }

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }
Пример #60
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImage">源图</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="photoWidth">最终缩略图宽度</param>
        /// <param name="height">最终缩略图高度</param>
        /// <param name="mode">生成缩略图的方式
        /// <code>HW:指定高宽缩放(可能变形)</code>
        /// <code>W:指定宽,高按比例  </code>
        /// <code>H:指定高,宽按比例</code>
        /// <code>CUT:指定高宽裁减(不变形) </code>
        /// <code>FILL:填充</code>
        /// </param>
        public static void Image2Thumbs(System.Drawing.Image originalImage, string thumbnailPath, int photoWidth, int photoHeight, string mode)
        {
            #region 开始画图
            int lastPhotoWidth  = photoWidth;  //最后缩略图的宽度
            int lastPhotoHeight = photoHeight; //最后缩略图的高度

            int toWidth  = photoWidth;         //原图片被压缩的宽度
            int toHeight = photoHeight;        //原图片被压缩的高度

            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            int bg_x = 0;
            int bg_y = 0;
            switch (mode.ToUpper())
            {
            case "FILL":    //压缩填充至指定区域
                toHeight = photoHeight;
                toWidth  = toHeight * ow / oh;
                if (toWidth > photoWidth)
                {
                    toHeight = toHeight * photoWidth / toWidth;
                    toWidth  = photoWidth;
                }
                bg_x = (photoWidth - toWidth) / 2;
                bg_y = (photoHeight - toHeight) / 2;
                break;

            case "HW":    //指定高宽缩放(可能变形)
                break;

            case "W":    //指定宽,高按比例
                toHeight = lastPhotoHeight = originalImage.Height * photoWidth / originalImage.Width;
                break;

            case "H":    //指定高,宽按比例
                toWidth = lastPhotoWidth = originalImage.Width * photoHeight / originalImage.Height;
                break;

            case "CUT":    //指定高宽裁减(不变形)
                if ((double)originalImage.Width / (double)originalImage.Height > (double)lastPhotoWidth / (double)lastPhotoHeight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * lastPhotoWidth / lastPhotoHeight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * photoHeight / lastPhotoWidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }
            System.Drawing.Image    bitmap = new System.Drawing.Bitmap(lastPhotoWidth, lastPhotoHeight); //新建一个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.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.High;
            g.Clear(System.Drawing.Color.White);                                                    //白色
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, toWidth, toHeight), //在指定位置并且按指定大小绘制原图片的指定部分
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);
            try
            {
                bitmap.Save(thumbnailPath, ImgFormat(thumbnailPath));
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                bitmap.Dispose();
                g.Dispose();
            }
            #endregion
        }