//Función que convierte una imagen a escala de grises
    public void convertirGris(string imagefrom, string imageto)
    {
        //create a blank bitmap the same size as original
        Bitmap original = new Bitmap(imagefrom);
        Bitmap newBitmap = new Bitmap(original.Width, original.Height);

        //get a graphics object from the new image
        Graphics g = Graphics.FromImage(newBitmap);

        //create the grayscale ColorMatrix
        ColorMatrix colorMatrix = new ColorMatrix(new float[][]
         {
             new float[] {.30f, .30f, .30f, 0, 0},
             new float[] {.59f, .59f, .59f, 0, 0},
             new float[] {.11f, .11f, .11f, 0, 0},
             new float[] {0, 0, 0, 1, 0},
             new float[] {0, 0, 0, 0, 1}
         });

        //create some image attributes
        ImageAttributes attributes = new ImageAttributes();

        //set the color matrix attribute
        attributes.SetColorMatrix(colorMatrix);

        //draw the original image on the new image
        //using the grayscale color matrix
        g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
           0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

        //dispose the Graphics object
        g.Dispose();
        newBitmap.Save(imageto);
    }
        /// <summary>
        /// Converts the given <paramref name="imageMoniker"/> to its <see cref="BitmapSource"/> counterpart.
        /// </summary>
        /// <param name="imageMoniker">The image moniker.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="visualStudioImageService">The visual studio image service.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Must be a positive, non-zero value
        /// or
        /// Must be a positive, non-zero value
        /// </exception>
        public static BitmapSource ToBitmapSource(this ImageMoniker imageMoniker, int width, int height, IVsImageService2 visualStudioImageService)
        {
            // based on https://github.com/madskristensen/ExtensibilityTools/blob/master/src/Misc/Commands/ImageMonikerDialog.xaml.cs#L47

            if (visualStudioImageService == null) throw new ArgumentNullException(nameof(visualStudioImageService));
            if (width <= 0) throw new ArgumentOutOfRangeException(nameof(width), "Must be a positive, non-zero value");
            if (height <= 0) throw new ArgumentOutOfRangeException(nameof(height), "Must be a positive, non-zero value");

            if (Microsoft.VisualStudio.Imaging.ExtensionMethods.IsNullImage(imageMoniker))
                return null;

            ImageAttributes imageAttributes = new ImageAttributes
            {
                Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags,
                ImageType = (uint)_UIImageType.IT_Bitmap,
                Format = (uint)_UIDataFormat.DF_WPF,
                LogicalHeight = height,
                LogicalWidth = width,
                StructSize = Marshal.SizeOf(typeof(ImageAttributes))
            };

            IVsUIObject result = visualStudioImageService.GetImage(imageMoniker, imageAttributes);

            object data;
            result.get_Data(out data);

            return data as BitmapSource;
        }
Example #3
0
	public static void Main(string[] args)
	{	
		Graphics.DrawImageAbort imageCallback;
		Bitmap outbmp = new Bitmap (300, 300);				
		Bitmap bmp = new Bitmap("../../Test/System.Drawing/bitmaps/almogaver24bits.bmp");
		Graphics dc = Graphics.FromImage (outbmp);        
		
		ImageAttributes imageAttr = new ImageAttributes();
		
		/* Simple image drawing */		
		dc.DrawImage(bmp, 0,0);				
				
		/* Drawing using points */
		PointF ulCorner = new PointF(150.0F, 0.0F);
		PointF urCorner = new PointF(350.0F, 0.0F);
		PointF llCorner = new PointF(200.0F, 150.0F);
		RectangleF srcRect = new Rectangle (0,0,100,100);		
		PointF[] destPara = {ulCorner, urCorner, llCorner};	
		imageCallback =  new Graphics.DrawImageAbort(DrawImageCallback);		
		dc.DrawImage (bmp, destPara, srcRect, GraphicsUnit.Pixel, imageAttr, imageCallback);
	
		/* Using rectangles */	
		RectangleF destRect = new Rectangle (10,200,100,100);
		RectangleF srcRect2 = new Rectangle (50,50,100,100);		
		dc.DrawImage (bmp, destRect, srcRect2, GraphicsUnit.Pixel);		
		
		/* Simple image drawing with with scaling*/		
		dc.DrawImage(bmp, 200,200, 75, 75);				
		
		outbmp.Save("drawimage.bmp", ImageFormat.Bmp);				
		
	}
Example #4
0
    // TODO:
    // Perhaps move square/hex tile drawing methods from TileViewPortControl into TileSprite ...
    // Such methods would want an argument for the TVP (or other GLControl?) to draw them upon ...
    // For now, will make TileViewPortControl.Render() get the texture_id via (sprite_obj).texture ...
    public void GDI_Draw_Tile(Graphics gg, int xx, int yy, ImageAttributes attrib)
    {
        // Keeping this around, as it may prove convenient to be able
        // to draw a tile onto a Control for certain UI purposes.

        // Draw the region this.rect of the image onto gg at xx,yy, with no scaling
        Rectangle destRect = new Rectangle(xx, yy, _rect.Width, _rect.Height);
        gg.DrawImage(_image,
                     new Rectangle(xx, yy, _rect.Width, _rect.Height),
                     _rect.X, _rect.Y, _rect.Width, _rect.Height,
                     GraphicsUnit.Pixel, attrib);
    }
Example #5
0
	public static Color ProcessColorMatrix (Color color, ColorMatrix colorMatrix)
	{
		Bitmap bmp = new Bitmap (64, 64);
		Graphics gr = Graphics.FromImage (bmp);
		ImageAttributes imageAttr = new ImageAttributes ();

		bmp.SetPixel (0,0, color);

		imageAttr.SetColorMatrix (colorMatrix);
		gr.DrawImage (bmp, new Rectangle (0, 0, 64,64), 0,0, 64,64, GraphicsUnit.Pixel, imageAttr);

		Console.WriteLine ("{0} - > {1}", color,  bmp.GetPixel (0,0));
		return bmp.GetPixel (0,0);

	}
Example #6
0
 protected override void OnPaint(PaintEventArgs e)
 {
     if (mImg1 == null || mImg2 == null)
         e.Graphics.FillRectangle(new SolidBrush(this.BackColor), new Rectangle(0, 0, this.Width, this.Height));
     else
     {
         Rectangle rc = new Rectangle(0, 0, this.Width, this.Height);
         ColorMatrix cm = new ColorMatrix();
         ImageAttributes ia = new ImageAttributes();
         cm.Matrix33 = mBlend;
         ia.SetColorMatrix(cm);
         e.Graphics.DrawImage(mImg2, rc, 0, 0, mImg2.Width, mImg2.Height, GraphicsUnit.Pixel, ia);
         cm.Matrix33 = 1F - mBlend;
         ia.SetColorMatrix(cm);
         e.Graphics.DrawImage(mImg1, rc, 0, 0, mImg1.Width, mImg1.Height, GraphicsUnit.Pixel, ia);
     }
     base.OnPaint(e);
 }
Example #7
0
	public static void ProcessImageColorMatrix (string sin, string sout, ColorMatrix colorMatrix)
	{
		Bitmap bmp_in = new Bitmap (sin);		
		Bitmap bmp_out = new Bitmap (bmp_in.Width, bmp_in.Height, bmp_in.PixelFormat);		
		
		Graphics gr = Graphics.FromImage (bmp_out);
		ImageAttributes imageAttr = new ImageAttributes ();
		
		imageAttr.SetColorMatrix (colorMatrix);

		gr.DrawImage (bmp_in, new Rectangle (0, 0, bmp_out.Width, bmp_out.Height), 
			0,0, bmp_out.Width, bmp_out.Height, GraphicsUnit.Pixel, imageAttr);		
		
		imageAttr.Dispose ();			
		bmp_out.Save (sout);
		bmp_in.Dispose ();
		bmp_out.Dispose ();
		Console.WriteLine ("Saving image file {0}", sout);
	}
        public static BitmapSource GetImage(ImageMoniker moniker, int size)
        {
            ImageAttributes imageAttributes = new ImageAttributes();
            imageAttributes.Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags;
            imageAttributes.ImageType = (uint)_UIImageType.IT_Bitmap;
            imageAttributes.Format = (uint)_UIDataFormat.DF_WPF;
            imageAttributes.LogicalHeight = size;
            imageAttributes.LogicalWidth = size;
            imageAttributes.StructSize = Marshal.SizeOf(typeof(ImageAttributes));

            IVsUIObject result = _imageService.GetImage(moniker, imageAttributes);

            object data;
            result.get_Data(out data);

            if (data == null)
                return null;

            return data as BitmapSource;
        }
        public static ImageSource GetImage(this ImageMoniker imageMoniker)
        {
            IVsImageService2 vsIconService = ServiceProvider.GlobalProvider.GetService(typeof(SVsImageService)) as IVsImageService2;

            ImageAttributes imageAttributes = new ImageAttributes();
            imageAttributes.Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags;
            imageAttributes.ImageType = (uint)_UIImageType.IT_Bitmap;
            imageAttributes.Format = (uint)_UIDataFormat.DF_WPF;
            imageAttributes.LogicalHeight = 16;//IconHeight,
            imageAttributes.LogicalWidth = 16;//IconWidth,
            imageAttributes.StructSize = Marshal.SizeOf(typeof(ImageAttributes));

            IVsUIObject result = vsIconService.GetImage(imageMoniker, imageAttributes);

            object data;
            result.get_Data(out data);
            ImageSource glyph = data as ImageSource;
            glyph.Freeze();

            return glyph;
        }
Example #10
0
        public static BitmapSource GetIconForImageMoniker(ImageMoniker? imageMoniker, int sizeX, int sizeY)
        {
            if (imageMoniker == null)
            {
                return null;
            }

            IVsImageService2 vsIconService = ServiceProvider.GlobalProvider.GetService(typeof(SVsImageService)) as IVsImageService2;

            if (vsIconService == null)
            {
                return null;
            }

            ImageAttributes imageAttributes = new ImageAttributes
            {
                Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags,
                ImageType = (uint)_UIImageType.IT_Bitmap,
                Format = (uint)_UIDataFormat.DF_WPF,
                LogicalHeight = sizeY,
                LogicalWidth = sizeX,
                StructSize = Marshal.SizeOf(typeof(ImageAttributes))
            };

            IVsUIObject result = vsIconService.GetImage(imageMoniker.Value, imageAttributes);

            object data;
            result.get_Data(out data);
            BitmapSource glyph = data as BitmapSource;

            if (glyph != null)
            {
                glyph.Freeze();
            }

            return glyph;
        }
Example #11
0
        public static ImageSource GetIconForImageMoniker(ImageMoniker imageMoniker) {
            IVsImageService2 imageService = VsAppShell.Current.GetGlobalService<IVsImageService2>(typeof(SVsImageService));
            ImageSource glyph = null;

            ImageAttributes imageAttributes = new ImageAttributes();
            imageAttributes.Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags;
            imageAttributes.ImageType = (uint)_UIImageType.IT_Bitmap;
            imageAttributes.Format = (uint)_UIDataFormat.DF_WPF;
            imageAttributes.LogicalHeight = 16;// IconHeight,
            imageAttributes.LogicalWidth = 16;// IconWidth,
            imageAttributes.StructSize = Marshal.SizeOf(typeof(ImageAttributes));

            IVsUIObject result = imageService.GetImage(imageMoniker, imageAttributes);

            Object data = null;
            if (result.get_Data(out data) == VSConstants.S_OK) {
                glyph = data as ImageSource;
                if (glyph != null) {
                    glyph.Freeze();
                }
            }

            return glyph;
        }
Example #12
0
    /// <summary>
    /// 图片等比缩放
    /// </summary>
    /// <remarks>吴剑 2011-01-21</remarks>
    /// <param name="postedFile">原图HttpPostedFile对象</param>
    /// <param name="savePath">缩略图存放地址</param>
    /// <param name="targetWidth">指定的最大宽度</param>
    /// <param name="targetHeight">指定的最大高度</param>
    /// <param name="watermarkText">水印文字(为""表示不使用水印)</param>
    /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param>
    public static void ZoomAuto(System.Web.HttpPostedFileBase postedFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText, string watermarkImage)
    {
        //创建目录
        string dir = Path.GetDirectoryName(savePath);
        if (!Directory.Exists(dir))
            Directory.CreateDirectory(dir);

        //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
        System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true);

        //原图宽高均小于模版,不作处理,直接保存
        if (initImage.Width <= targetWidth && initImage.Height <= targetHeight)
        {
            //文字水印
            if (watermarkText != "")
            {
                using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage))
                {
                    System.Drawing.Font fontWater = new Font("黑体", 10);
                    System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                    gWater.Dispose();
                }
            }

            //透明图片水印
            if (watermarkImage != "")
            {
                if (File.Exists(watermarkImage))
                {
                    //获取水印图片
                    using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                    {
                        //水印绘制条件:原始图片宽高均大于或等于水印图片
                        if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height)
                        {
                            Graphics gWater = Graphics.FromImage(initImage);

                            //透明属性
                            ImageAttributes imgAttributes = new ImageAttributes();
                            ColorMap colorMap = new ColorMap();
                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                            ColorMap[] remapTable = { colorMap };
                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                            float[][] colorMatrixElements = {
                                   new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  0.0f,  0.5f, 0.0f},//透明度:0.5
                                   new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                };

                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                            gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);

                            gWater.Dispose();
                        }
                        wrImage.Dispose();
                    }
                }
            }

            //保存
            initImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        else
        {
            //缩略图宽、高计算
            double newWidth = initImage.Width;
            double newHeight = initImage.Height;

            //宽大于高或宽等于高(横图或正方)
            if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
            {
                //如果宽大于模版
                if (initImage.Width > targetWidth)
                {
                    //宽按模版,高按比例缩放
                    newWidth = targetWidth;
                    newHeight = initImage.Height * (targetWidth / initImage.Width);
                }
            }
            //高大于宽(竖图)
            else
            {
                //如果高大于模版
                if (initImage.Height > targetHeight)
                {
                    //高按模版,宽按比例缩放
                    newHeight = targetHeight;
                    newWidth = initImage.Width * (targetHeight / initImage.Height);
                }
            }

            //生成新图
            //新建一个bmp图片
            System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
            //新建一个画板
            System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);

            //设置质量
            newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //置背景色
            newG.Clear(Color.White);
            //画图
            newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

            //文字水印
            if (watermarkText != "")
            {
                using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(newImage))
                {
                    System.Drawing.Font fontWater = new Font("宋体", 10);
                    System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                    gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                    gWater.Dispose();
                }
            }

            //透明图片水印
            if (watermarkImage != "")
            {
                if (File.Exists(watermarkImage))
                {
                    //获取水印图片
                    using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                    {
                        //水印绘制条件:原始图片宽高均大于或等于水印图片
                        if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height)
                        {
                            Graphics gWater = Graphics.FromImage(newImage);

                            //透明属性
                            ImageAttributes imgAttributes = new ImageAttributes();
                            ColorMap colorMap = new ColorMap();
                            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                            ColorMap[] remapTable = { colorMap };
                            imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                            float[][] colorMatrixElements = {
                                   new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                   new float[] {0.0f,  0.0f,  0.0f,  0.5f, 0.0f},//透明度:0.5
                                   new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                };

                            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                            imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                            gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
                            gWater.Dispose();
                        }
                        wrImage.Dispose();
                    }
                }
            }

            //保存缩略图
            newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //释放资源
            newG.Dispose();
            newImage.Dispose();
            initImage.Dispose();
        }
    }
Example #13
0
        /// <summary>
        /// Raises the RenderItemImage event.
        /// </summary>
        /// <param name="e">An ToolStripItemImageRenderEventArgs containing the event data.</param>
        protected override void OnRenderItemImage(ToolStripItemImageRenderEventArgs e)
        {
            // Is this a min/restore/close pendant button
            if (e.Item.GetType().ToString() == "System.Windows.Forms.MdiControlStrip+ControlBoxMenuItem")
            {
                // Get access to the owning form of the mdi control strip
                if (e.ToolStrip.Parent.TopLevelControl is Form f)
                {
                    // Get the mdi control strip instance
                    PropertyInfo piMCS = typeof(Form).GetProperty("MdiControlStrip", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                    if (piMCS != null)
                    {
                        object mcs = piMCS.GetValue(f, null);
                        if (mcs != null)
                        {
                            // Get the min/restore/close internal menu items
                            Type      mcsType = mcs.GetType();
                            FieldInfo fiM     = mcsType.GetField("minimize", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                            FieldInfo fiR     = mcsType.GetField("restore", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                            FieldInfo fiC     = mcsType.GetField("close", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
                            if ((fiM != null) && (fiR != null) && (fiC != null))
                            {
                                ToolStripMenuItem m = fiM.GetValue(mcs) as ToolStripMenuItem;
                                ToolStripMenuItem r = fiR.GetValue(mcs) as ToolStripMenuItem;
                                ToolStripMenuItem c = fiC.GetValue(mcs) as ToolStripMenuItem;
                                if ((m != null) && (r != null) && (c != null))
                                {
                                    // Compare the event provided image with the internal cached ones to discover the type of pendant button we are drawing
                                    PaletteButtonSpecStyle specStyle = PaletteButtonSpecStyle.Generic;
                                    if (m.Image == e.Image)
                                    {
                                        specStyle = PaletteButtonSpecStyle.PendantMin;
                                    }
                                    else if (r.Image == e.Image)
                                    {
                                        specStyle = PaletteButtonSpecStyle.PendantRestore;
                                    }
                                    else if (c.Image == e.Image)
                                    {
                                        specStyle = PaletteButtonSpecStyle.PendantClose;
                                    }

                                    // A match, means we have a known pendant button
                                    if (specStyle != PaletteButtonSpecStyle.Generic)
                                    {
                                        // Grab the palette pendant details needed for drawing
                                        Image paletteImage     = KCT.Palette.GetButtonSpecImage(specStyle, PaletteState.Normal);
                                        Color transparentColor = KCT.Palette.GetButtonSpecImageTransparentColor(specStyle);

                                        // Finally we actually have an image to draw!
                                        if (paletteImage != null)
                                        {
                                            using (ImageAttributes attribs = new ImageAttributes())
                                            {
                                                // Setup mapping to make required color transparent
                                                ColorMap remap = new ColorMap
                                                {
                                                    OldColor = transparentColor,
                                                    NewColor = Color.Transparent
                                                };
                                                attribs.SetRemapTable(new ColorMap[] { remap });

                                                // Phew, actually draw the darn thing
                                                e.Graphics.DrawImage(paletteImage, e.ImageRectangle,
                                                                     0, 0, e.Image.Width, e.Image.Height,
                                                                     GraphicsUnit.Pixel, attribs);

                                                // Do not let base class draw system defined image
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            base.OnRenderItemImage(e);
        }
Example #14
0
        /// <summary>
        /// 在图片中添加文字水印
        /// </summary>
        /// <param name="gSrcCanvas"></param>
        /// <param name="watermarkText"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        private static void AddWatermarkText(Graphics gSrcCanvas, string watermarkText, int width, int height)
        {
            //计算图片对角线长度
            double diagonal = Math.Sqrt(Math.Pow(width, 2) + Math.Pow(height, 2));

            //计算对角线倾角
            double angle = Math.Asin(height / Math.Sqrt(Math.Pow(width, 2) + Math.Pow(height, 2))) / Math.PI * 180;

            // 确定水印文字的字体大小
            int[] sizes = new int[]
            {
                280, 276, 272, 268, 264, 260, 256, 252, 248, 244, 240, 236, 232, 228, 224, 220, 216, 212, 208,
                204, 200, 196, 192, 188, 184, 180, 176, 172, 168, 164, 160, 156, 152, 148, 144, 140, 136, 132,
                128, 124, 120, 116, 112, 108, 104, 100, 96, 92, 88, 84, 80, 76, 72, 68, 64, 60, 56, 52, 48, 44,
                40, 36, 32, 28, 24, 20, 16, 12, 8, 4
            };
            Font  crFont = null;
            SizeF crSize = new SizeF();

            for (int i = 0; i < sizes.Length; i++)
            {
                crFont = new Font("微软雅黑", sizes[i], FontStyle.Bold);
                crSize = gSrcCanvas.MeasureString(watermarkText, crFont);
                if ((int)crSize.Width < (int)diagonal * 0.9)
                {
                    break;
                }
            }
            // 生成水印图片(将文字写到图片中)
            //Bitmap bmWaterMark = new Bitmap((int)crSize.Width + 3, (int)crSize.Height + 3, PixelFormat.Format32bppArgb);
            Bitmap   bmWaterMark = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            Graphics gWaterMark  = Graphics.FromImage(bmWaterMark);

            gWaterMark.TranslateTransform(width / 2, height / 2);
            //文字倾斜角度根据实际图片对角线长度计算
            gWaterMark.RotateTransform(-(int)angle);
            gWaterMark.TranslateTransform(-crSize.Width / 2, -crSize.Height / 2);

            PointF pt = new PointF(0, 0);
            // 画阴影文字
            Brush transparentBrush0 = new SolidBrush(Color.FromArgb(255, Color.Black));
            Brush transparentBrush1 = new SolidBrush(Color.FromArgb(255, Color.Black));

            gWaterMark.DrawString(watermarkText, crFont, transparentBrush0, pt.X, pt.Y + 1);
            gWaterMark.DrawString(watermarkText, crFont, transparentBrush0, pt.X + 1, pt.Y);
            gWaterMark.DrawString(watermarkText, crFont, transparentBrush1, pt.X + 1, pt.Y + 1);
            gWaterMark.DrawString(watermarkText, crFont, transparentBrush1, pt.X, pt.Y + 2);
            gWaterMark.DrawString(watermarkText, crFont, transparentBrush1, pt.X + 2, pt.Y);
            transparentBrush0.Dispose();
            transparentBrush1.Dispose();

            // 画文字
            gWaterMark.SmoothingMode = SmoothingMode.HighQuality;
            //Brush SolidBrush3 = new SolidBrush(Color.White);
            Brush solidBrush3 = new SolidBrush(Color.FromArgb(255, Color.White));

            gWaterMark.DrawString(watermarkText, crFont, solidBrush3, pt.X, pt.Y, StringFormat.GenericDefault);
            solidBrush3.Dispose();

            // 保存刚才的操作
            gWaterMark.Save();
            gWaterMark.Dispose();
            bmWaterMark.Save(_wmImgSavePath, ImageFormat.Jpeg);

            //// 将水印图片加到原图中
            //AddWatermarkImage(gSrcCanvas, new Bitmap(bmWaterMark), "WM_TOP_LEFT", width, height);

            using (var imageAttr = new ImageAttributes())
            {
                ColorMap colorMap = new ColorMap();
                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                ColorMap[] remapTable = { colorMap };
                imageAttr.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
                float[][] colorMatrixElements =
                {
                    new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                    new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                    new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                    new float[] { 0.0f, 0.0f, 0.0f, 0.3f, 0.0f },
                    new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                };
                ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);
                imageAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                gSrcCanvas.DrawImage(bmWaterMark, new Rectangle(10, 10, bmWaterMark.Width, bmWaterMark.Height), 0, 0,
                                     bmWaterMark.Width, bmWaterMark.Height, GraphicsUnit.Pixel, imageAttr);
                gSrcCanvas.Dispose();
            }
            bmWaterMark.Dispose();
        }
Example #15
0
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            Graphics  gxOff;            //Offscreen graphics
            Rectangle imgRect;          //image rectangle
            Brush     backBrush;        //brush for filling a backcolor
            Pen       framepen;         //pen for draw frame

            if (m_bmpOffscreen == null) //Bitmap for doublebuffering
            {
                m_bmpOffscreen = new Bitmap(ClientSize.Width, ClientSize.Height);
            }

            gxOff = Graphics.FromImage(m_bmpOffscreen);

            gxOff.Clear(this.BackColor);


            //添加了ImageButton 的自绘背景及图标的功能,并通过聚合SimpleImagesContaner以优化资源分配 by cs at 2009-1-20  {295CEBAC-5099-403c-90BF-DD86BC58264D}
            //if (bgimage != null)
            if ((IMGContainer != null) &&
                (IMGContainer.BackImg != null) &&
                (IMGContainer.ImgDisable != null)
                )
            {
                Image bgimage;

                if (!Enabled)
                {
                    bgimage = IMGContainer.ImgDisable;
                }
                else
                {
                    if (Checked && IMGContainer.CheckedBackImg != null)
                    {
                        bgimage = IMGContainer.CheckedBackImg;
                    }
                    else
                    {
                        bgimage = IMGContainer.BackImg;
                    }
                }

                //Center the image relativelly to the control
                int imageLeft = (this.Width - bgimage.Width) / 2;
                int imageTop  = (this.Height - bgimage.Height) / 2;

                imgRect = new Rectangle(imageLeft, imageTop, bgimage.Width, bgimage.Height);

                if (this.TransParent)
                {
                    //Set transparent key
                    ImageAttributes imageAttr = new ImageAttributes();
                    imageAttr.SetColorKey(BackgroundImageColor(bgimage), BackgroundImageColor(bgimage));

                    //Draw image
                    gxOff.DrawImage(bgimage, imgRect, 0, 0, bgimage.Width, bgimage.Height, GraphicsUnit.Pixel, imageAttr);
                }
                else
                {
                    gxOff.DrawImage(bgimage, imgRect, new Rectangle(0, 0, bgimage.Width, bgimage.Height), GraphicsUnit.Pixel);
                }
            }
            else
            if (BackImg != null)
            {
                Image bgimage = BackImg;

                if (!Enabled && ImgDisable != null)
                {
                    bgimage = ImgDisable;
                }

                int imageLeft = (this.Width - bgimage.Width) / 2;
                int imageTop  = (this.Height - bgimage.Height) / 2;

                imgRect = new Rectangle(imageLeft, imageTop, bgimage.Width, bgimage.Height);

                if (this.TransParent)
                {
                    //Set transparent key
                    ImageAttributes imageAttr = new ImageAttributes();
                    imageAttr.SetColorKey(BackgroundImageColor(bgimage), BackgroundImageColor(bgimage));

                    //Draw image
                    gxOff.DrawImage(bgimage, imgRect, 0, 0, bgimage.Width, bgimage.Height, GraphicsUnit.Pixel, imageAttr);
                }
                else
                {
                    gxOff.DrawImage(bgimage, imgRect, new Rectangle(0, 0, bgimage.Width, bgimage.Height), GraphicsUnit.Pixel);
                }
            }
            else     //draw frame
            {
                {
                    //gray
                    framepen = new Pen(Color.Gray, 1);
                    gxOff.DrawRectangle(framepen, 0, 0, ClientSize.Width - 2, ClientSize.Height - 2);


                    //white
                    framepen = new Pen(System.Drawing.Color.FromArgb(((int)(((byte)(100)))), ((int)(((byte)(127)))), ((int)(((byte)(181))))), 1);
                    gxOff.DrawLine(framepen, 1, 1, ClientSize.Width - 3, 1);
                    gxOff.DrawLine(framepen, 1, 1, 1, ClientSize.Height - 3);

                    //black
                    framepen = new Pen(Color.Black, 1);
                    gxOff.DrawLine(framepen, ClientSize.Width - 1, ClientSize.Height - 1, 0, ClientSize.Height - 1);
                    gxOff.DrawLine(framepen, ClientSize.Width - 1, ClientSize.Height - 1, ClientSize.Width - 1, 0);
                }
            }

            //todo: icon
            //添加了ImageButton 的自绘背景及图标的功能,并通过聚合SimpleImagesContaner以优化资源分配 by cs at 2009-1-20  {295CEBAC-5099-403c-90BF-DD86BC58264D}
            //if (Icon != null)
            if ((IMGContainer != null) &&
                (IMGContainer.Icon != null))
            {
                //Layout

                //Center the image relativelly to the control
                int imageLeft = (this.Width - IMGContainer.Icon.Width) / 2;
                int imageTop  = (this.Height - IMGContainer.Icon.Height) / 2;

                imgRect = new Rectangle(imageLeft, imageTop, IMGContainer.Icon.Width, IMGContainer.Icon.Height);

                if (this.TransParent)
                {
                    //Set transparent key
                    ImageAttributes imageAttr = new ImageAttributes();
                    imageAttr.SetColorKey(BackgroundImageColor(IMGContainer.Icon), BackgroundImageColor(IMGContainer.Icon));

                    //Draw image
                    gxOff.DrawImage(IMGContainer.Icon, imgRect, 0, 0, IMGContainer.Icon.Width, IMGContainer.Icon.Height, GraphicsUnit.Pixel, imageAttr);
                }
                else
                {
                    gxOff.DrawImage(IMGContainer.Icon, imgRect, new Rectangle(0, 0, IMGContainer.Icon.Width, IMGContainer.Icon.Height), GraphicsUnit.Pixel);
                }
            }
            else
            {
                if (Text != string.Empty)//todo:text no icon
                {
                    if (this.Enabled)
                    {
                        backBrush = new SolidBrush(this.ForeColor);
                    }
                    else
                    {
                        backBrush = new SolidBrush(Color.Gray);
                    }

                    if (textX < 0 || textY < 0)
                    {
                        gxOff.DrawString(this.Text, this.Font, backBrush,
                                         (this.ClientSize.Width - gxOff.MeasureString(this.Text, this.Font).Width) / 2,
                                         (this.ClientSize.Height - gxOff.MeasureString(this.Text, this.Font).Height) / 2);
                    }
                    else
                    {
                        gxOff.DrawString(this.Text, this.Font, backBrush, textX, textY);
                    }
                }
            }

            e.Graphics.DrawImage(m_bmpOffscreen, 0, 0);

            //base.OnPaint(e);
        }
        View CreateView()
        {
            var layout = new RelativeLayout {
            };

            var backgroundImage = new Image
            {
                Source = new FileImageSource {
                    File = "list_item_bg.png"
                },
                Aspect = Aspect.Fill,
            };

            layout.Children.Add(
                backgroundImage,
                Constraint.RelativeToParent((parent) =>
            {
                return(0);
            }),
                Constraint.RelativeToParent((parent) =>
            {
                return(0);
            }),
                Constraint.RelativeToParent((parent) =>
            {
                return(parent.Width);
            }),
                Constraint.RelativeToParent((parent) =>
            {
                return(parent.Height);
            }));

            var descriptionLabel = new Label
            {
                Text = "Description",
                HorizontalOptions = LayoutOptions.StartAndExpand,
                VerticalOptions   = LayoutOptions.EndAndExpand,
                FontSize          = 30 * 72 * 2.6 / 316,
                FontAttributes    = FontAttributes.Bold,
            };

            descriptionLabel.SetBinding(Label.TextProperty, "Title");

            var pathLabel = new Label
            {
                Text = "Path",
                HorizontalOptions = LayoutOptions.StartAndExpand,
                VerticalOptions   = LayoutOptions.StartAndExpand,
                FontSize          = 25 * 72 * 2.6 / 316,
                TextColor         = Color.FromRgb(146, 146, 146),
            };

            pathLabel.SetBinding(Label.TextProperty, "Path");

            layout.Children.Add(descriptionLabel,
                                Constraint.RelativeToParent((parent) =>
            {
                return(parent.Width * 0.0431);
            }),
                                Constraint.RelativeToParent((parent) =>
            {
                return(parent.Height * 0.3084);
            }));

            layout.Children.Add(pathLabel,
                                Constraint.RelativeToParent((parent) =>
            {
                return(parent.Width * 0.0431);
            }),
                                Constraint.RelativeToParent((parent) =>
            {
                return(parent.Height * 0.5198);
            }));

            var gestureRecognizer = new LongTapGestureRecognizer();

            gestureRecognizer.TapStarted += (s, e) =>
            {
                //change forground blend color of image
                ImageAttributes.SetBlendColor(backgroundImage, Color.FromRgb(213, 228, 240));
            };

            gestureRecognizer.TapCanceled += (s, e) =>
            {
                //revert forground blend color of image
                ImageAttributes.SetBlendColor(backgroundImage, Color.Default);
            };

            gestureRecognizer.TapCompleted += (s, e) =>
            {
                //revert forground blend color of image
                ImageAttributes.SetBlendColor(backgroundImage, Color.Default);
            };
            layout.GestureRecognizers.Add(gestureRecognizer);

            return(layout);
        }
Example #17
0
    /// <summary>
    /// 加图片水印
    /// </summary>
    /// <param name="imgPath">原图文件名物理路径</param>
    /// <param name="filename">生成文件名物理路径</param>
    /// <param name="watermarkFilename">水印文件名物理路径</param>
    /// <param name="positon">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 ... 9=右下</param>
    /// <param name="quality">附加图片质量,0--100之间,值大质量高</param>
    /// <param name="watermarkTransparency">水印的透明度 1--100 100为不透明</param>

    public static bool AddImageSignPic(string imgPath, string filename, string watermarkFilename, Enums.Position positon, int quality, int watermarkTransparency, int minWidth, int minHeight)
    {
        using (Bitmap img = new Bitmap(imgPath))
        {
            Graphics g ;
                //如果原图片是索引像素格式之列的,则需要转换
                if (IsPixelFormatIndexed(img.PixelFormat))
                {
                    using (Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb))
                    {
                        g = Graphics.FromImage(bmp);
                        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        g.DrawImage(img, 0, 0);
                    }

                }
                else
                {
                    g = Graphics.FromImage(img);
                    //设置高质量插值法
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    //设置高质量,低速度呈现平滑程度
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                }
                int watermarkStatus = (int)positon;


                using (System.Drawing.Image watermark = new Bitmap(watermarkFilename))
                {

                    if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                    {
                        return false;
                    }
                    if (img.Width < minWidth || img.Height < minHeight)
                    {
                        return false;
                    }


                    using (ImageAttributes imageAttributes = new ImageAttributes())
                    {
                        ColorMap colorMap = new ColorMap();

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

                        imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                        float transparency = 0.5F;
                        if (watermarkTransparency >= 1 && watermarkTransparency <= 100)
                        {
                            transparency = (watermarkTransparency / 100.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}
                                            };

                        ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

                        imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, 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 Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
                        ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                        ImageCodecInfo ici = null;
                        foreach (ImageCodecInfo codec in codecs)
                        {
                            if (codec.MimeType.ToLower().IndexOf("jpeg") > -1 || codec.MimeType.ToLower().IndexOf("jpg") > -1)
                            {
                                ici = codec;
                            }
                        }
                        EncoderParameters encoderParams = new EncoderParameters();
                        long[] qualityParam = new long[1];
                        if (quality < 0 || quality > 100)
                        {
                            quality = 80;
                        }
                        qualityParam[0] = quality;

                        EncoderParameter encoderParam = new 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();
                    }
                
            }
        }
        return true;
    }
        private void SaveImagesToDisk(string folder)
        {
            PropertyInfo[] monikers = typeof(KnownMonikers).GetProperties(BindingFlags.Static | BindingFlags.Public);

            ImageAttributes imageAttributes = new ImageAttributes();
            imageAttributes.Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags;
            imageAttributes.ImageType = (uint)_UIImageType.IT_Bitmap;
            imageAttributes.Format = (uint)_UIDataFormat.DF_WPF;
            imageAttributes.LogicalHeight = 16;
            imageAttributes.LogicalWidth = 16;
            imageAttributes.StructSize = Marshal.SizeOf(typeof(ImageAttributes));

            WriteableBitmap sprite = null;
            int count = 0;
            char letter = ' ';

            foreach (var monikerName in monikers)
            {
                ImageMoniker moniker = (ImageMoniker)monikerName.GetValue(null, null);
                IVsUIObject result = _imageService.GetImage(moniker, imageAttributes);

                if (monikerName.Name[0] != letter)
                {
                    if (sprite != null)
                    {
                        sprite.Unlock();
                        SaveBitmapToDisk(sprite, Path.Combine(folder, "_sprites", letter + ".png"));
                    }

                    int items = monikers.Count(m => m.Name[0] == monikerName.Name[0]);
                    sprite = new WriteableBitmap(16, 16 * (items), 96, 96, PixelFormats.Pbgra32, null);
                    sprite.Lock();
                    letter = monikerName.Name[0];
                    count = 0;
                }

                Object data;
                result.get_Data(out data);

                if (data == null)
                    continue;

                BitmapSource glyph = data as BitmapSource;
                string fileName = Path.Combine(folder, monikerName.Name + ".png");

                int stride = glyph.PixelWidth * (glyph.Format.BitsPerPixel / 8);
                byte[] buffer = new byte[stride * glyph.PixelHeight];
                glyph.CopyPixels(buffer, stride, 0);

                sprite.WritePixels(new Int32Rect(0, count, glyph.PixelWidth, glyph.PixelHeight), buffer, stride, 0);
                count += 16;

                SaveBitmapToDisk(glyph, fileName);
            }

            // Save the last image sprite to disk
            sprite.Unlock();
            SaveBitmapToDisk(sprite, Path.Combine(folder, "_sprites", letter + ".png"));
        }
Example #19
0
    //public void GDI_Draw_Tile(Graphics gg, int xx, int yy, ImageAttributes attrib, int frame) {
    //} // GDI_Draw_Tile()
    public void GDI_Draw_Tile(Graphics gg, int xx, int yy, ImageAttributes attrib, int frame)
    {
        int ff = frame % this.num_frames;
        // Keeping this around, as it may prove convenient to be able
        // to draw a tile onto a Control for certain UI purposes.

        // Draw the region this.rect of the image onto gg at xx,yy, with no scaling
        Rectangle rr = this.rect[ff];
        Rectangle destRect = new Rectangle(xx, yy, rr.Width, rr.Height);
        gg.DrawImage(this.bitmap[ff],
                     new Rectangle(xx, yy, rr.Width, rr.Height),
                     rr.X, rr.Y, rr.Width, rr.Height,
                     GraphicsUnit.Pixel, attrib);
    }
Example #20
0
        private void tlVectorControl1_AfterPaintPage(object sender, ItopVector.Core.PaintMapEventArgs e)
        {
            int nScale = 0;

            switch ((int)(this.tlVectorControl1.DrawArea.ScaleUnit * 1000))
            {
            case 100:
                nScale = 8;
                break;

            case 200:
                nScale = 9;
                break;

            case 400:
                nScale = 10;
                break;

            case 1000:
                nScale = 11;
                break;

            case 2000:
                nScale = 12;
                break;

            case 4000:
                nScale = 13;
                break;

            default:
                return;
            }
            LongLat longlat = LongLat.Empty;
            //计算中心点经纬度

            int offsetY = (nScale - 10) * 25;

            longlat = mapview.OffSet(mapview.ZeroLongLat, nScale, -(int)(e.CenterPoint.X), -(int)(e.CenterPoint.Y));

            //创建地图
            System.Drawing.Image image = mapview.CreateMap(e.Bounds.Width, e.Bounds.Height, nScale, longlat.Longitude, longlat.Latitude);

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMatrix     matrix1         = new ColorMatrix();

            matrix1.Matrix00 = 1f;
            matrix1.Matrix11 = 1f;
            matrix1.Matrix22 = 1f;
            matrix1.Matrix33 = 0.9f;            //地图透明度
            matrix1.Matrix44 = 1f;
            //设置地图透明度
            imageAttributes.SetColorMatrix(matrix1, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            //绘制地图
            e.G.DrawImage((Bitmap)image, e.Bounds, 0f, 0f, (float)image.Width, (float)image.Height, GraphicsUnit.Pixel, imageAttributes);

            //绘制中心点
            e.G.DrawEllipse(Pens.Red, e.Bounds.Width / 2 - 2, e.Bounds.Height / 2 - 2, 4, 4);
            e.G.DrawEllipse(Pens.Red, e.Bounds.Width / 2 - 1, e.Bounds.Height / 2 - 1, 2, 2);

            {    //绘制比例尺
                Point p1 = new Point(20, e.Bounds.Height - 30);
                Point p2 = new Point(20, e.Bounds.Height - 20);
                Point p3 = new Point(80, e.Bounds.Height - 20);
                Point p4 = new Point(80, e.Bounds.Height - 30);

                e.G.DrawLines(new Pen(Color.Black, 2), new Point[4] {
                    p1, p2, p3, p4
                });
                string str1 = string.Format("{0}公里", mapview.GetMiles(nScale));
                e.G.DrawString(str1, new Font("宋体", 10), Brushes.Black, 30, e.Bounds.Height - 40);
            }
            //			string s = string.Format("{0}行{1}列", nRows, nCols);
            string s = string.Format("经{0}:纬{1}", longlat.Longitude, longlat.Latitude);

            //			//显示中心点经纬度
            e.G.DrawString(s, new Font("宋体", 10), Brushes.Red, 20, 40);
        }
Example #21
0
        /// <summary>
        /// 加水印,对传入的Image对象操作
        /// </summary>
        /// <param name="logo_num">水印图片的编号</param>
        /// <param name="logo_pos">水印图片的位置,0:中间,1:左上,2:右上,3:右下,4:左下</param>
        /// <param name="imgPhoto">要加水印的Bitmap对象,直接在上面加水印(ref 引用传递)</param>
        public static void AddWaterMark(ref Bitmap imgPhoto, int logo_num, int logo_pos)
        {
            string zu_logo_root = System.Web.HttpContext.Current.Server.MapPath("~/ERP/images/watermark/");

            string[] waterMarkImgs = new string[2] {
                zu_logo_root + "black_logo.gif",
                zu_logo_root + "white_logo.gif"
            };

            string watermarkFullPath = waterMarkImgs[logo_num];

            int phWidth  = imgPhoto.Width;
            int phHeight = imgPhoto.Height;

            //用水印BMP文件创建一个image对象
            System.Drawing.Image imgWatermarkRow = new System.Drawing.Bitmap(watermarkFullPath);

            //将水印文件缩放到原始文件的1/3大
            System.Drawing.Image imgWatermark = ResizeImage(imgWatermarkRow, phWidth / 3, phHeight / 3);



            int pos_x_offset, pos_y_offset;  //水印的坐标

            switch (logo_pos)
            {
            case 1:     //左上
                pos_x_offset = phWidth / 8;
                pos_y_offset = phHeight / 8;
                break;

            case 2:     //右上
                pos_x_offset = phWidth * 7 / 12;
                pos_y_offset = phHeight / 8;
                break;

            case 3:     //右下
                pos_x_offset = phWidth * 7 / 12;
                pos_y_offset = phHeight * 7 / 11;
                break;

            case 4:     //右上
                pos_x_offset = phWidth / 8;
                pos_y_offset = phHeight * 7 / 11;
                break;

            default:
                pos_x_offset = phWidth / 3;
                pos_y_offset = phHeight / 3;
                break;
            }



            //创建一个与原图尺寸相同的位图
            Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            //位图装载到一个Graphics对象
            Graphics grPhoto = Graphics.FromImage(bmPhoto);


            int wmWidth  = imgWatermark.Width;
            int wmHeight = imgWatermark.Height;

            //设置图片质量
            grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

            //以原始尺寸把照片图像画到此graphics对象
            grPhoto.DrawImage(
                imgPhoto,                               // Photo Image object
                new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
                0,                                      // x-coordinate of the portion of the source image to draw.
                0,                                      // y-coordinate of the portion of the source image to draw.
                phWidth,                                // Width of the portion of the source image to draw.
                phHeight,                               // Height of the portion of the source image to draw.
                GraphicsUnit.Pixel);                    // Units of measure

            //基于前面已修改的Bitmap创建一个新Bitmap
            Bitmap bmWatermark = new Bitmap(bmPhoto);

            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            //Load this Bitmap into a new Graphic Object
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //To achieve a transulcent watermark we will apply (2) color
            //manipulations by defineing a ImageAttributes object and
            //seting (2) of its properties.
            ImageAttributes imageAttributes = new ImageAttributes();

            //第一步是以透明色(Alpha=0, R=0, G=0, B=0)来替换背景色
            //为此我们将使用一个Colormap并用它来定义一个RemapTable
            ColorMap colorMap = new ColorMap();

            //水印被定义为一个100%的绿色背景l
            //这将是我们以transparency来查找并替换的颜色
            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //第二个颜色操作是用来改变水印的透明度
            //用包涵the coordinates for the RGBA space的一个5x5 的矩阵
            //设置第三行第三列to 0.3f we achive a level of opacity
            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.8f, 0.0f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, 0.3f, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
            };
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                                           ColorAdjustType.Bitmap);


            grWatermark.DrawImage(imgWatermark,
                                  new Rectangle(pos_x_offset, pos_y_offset, wmWidth, wmHeight), //Set the detination Position
                                  0,                                                            // 源图的横坐标位置
                                  0,                                                            // 源图的纵坐标位置
                                  wmWidth,                                                      // 水印宽度
                                  wmHeight,                                                     // 水印高度
                                  GraphicsUnit.Pixel,                                           // Unit of measurment
                                  imageAttributes);                                             //ImageAttributes Object

            //以新图替换原始图
            imgPhoto = bmWatermark;
            grPhoto.Dispose();
            grWatermark.Dispose();
            imgWatermark.Dispose();
        }
Example #22
0
        public static byte[] GetScaledVersion(this KeyBitmap keyBitmap, int width, int height)
        {
            var keyDataAccess = (IKeyBitmapDataAccess)keyBitmap;

            if (keyDataAccess.IsNull)
            {
                return(null);
            }

            var rawData = new byte[keyDataAccess.DataLength];

            keyDataAccess.CopyData(rawData, 0);

            if (keyBitmap.Width == width && keyBitmap.Height == height)
            {
                return(rawData);
            }

            var destRect = new Rectangle(0, 0, width, height);

            using (var scaledBmp = new Bitmap(width, height, PixelFormat.Format24bppRgb))
                using (var sourceBmp = new Bitmap(keyBitmap.Width, keyBitmap.Height, PixelFormat.Format24bppRgb))
                {
                    var bmpData = sourceBmp.LockBits(new Rectangle(0, 0, sourceBmp.Width, sourceBmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
                    try
                    {
                        Marshal.Copy(rawData, 0, bmpData.Scan0, rawData.Length);
                    }
                    finally
                    {
                        sourceBmp.UnlockBits(bmpData);
                    }

                    using (var g = System.Drawing.Graphics.FromImage(scaledBmp))
                    {
                        g.CompositingMode    = CompositingMode.SourceCopy;
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode      = SmoothingMode.HighQuality;
                        g.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                        using (var wrapMode = new ImageAttributes())
                        {
                            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                            g.DrawImage(sourceBmp, destRect, 0, 0, sourceBmp.Width, sourceBmp.Height, GraphicsUnit.Pixel, wrapMode);
                        }
                    }

                    bmpData = scaledBmp.LockBits(destRect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                    try
                    {
                        var dataArray = new byte[width * height * 3];
                        Marshal.Copy(bmpData.Scan0, dataArray, 0, dataArray.Length);
                        return(dataArray);
                    }
                    finally
                    {
                        scaledBmp.UnlockBits(bmpData);
                    }
                }
        }
Example #23
0
        private static void AddWatermark(string imageFilePath,
                                         string watermarkText  = null,
                                         string watermarkImage = null,
                                         float opacity         = 0.3f,
                                         string fontName       = "arial",
                                         string postfix        = "_watermarked",
                                         string outputDir      = null)
        {
            var originalImagePath = imageFilePath;

            //create a image object containing the photograph to watermark
            Image imgPhoto = Image.FromFile(originalImagePath);
            int   phWidth  = imgPhoto.Width;
            int   phHeight = imgPhoto.Height;

            #region Step #2 - Insert Watermark image
            if (watermarkImage.IsNotNullOrEmpty())
            {
                //create a image object containing the watermark
                //Image imgWatermark = new Bitmap(watermarkImagePath);
                var imgWatermark = Image.FromFile(watermarkImage);
                int wmWidth      = imgWatermark.Width;
                int wmHeight     = imgWatermark.Height;

                //Load this Bitmap into a new Graphic Object
                Graphics grWatermark = Graphics.FromImage(imgPhoto);

                //To achieve a transulcent watermark we will apply (2) color
                //manipulations by defineing a ImageAttributes object and
                //seting (2) of its properties.
                ImageAttributes imageAttributes = new ImageAttributes();

                //The first step in manipulating the watermark image is to replace
                //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
                //to do this we will use a Colormap and use this to define a RemapTable
                ColorMap colorMap = new ColorMap();

                //My watermark was defined with a background of 100% Green this will
                //be the color we search for and replace with transparency
                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

                ColorMap[] remapTable = { colorMap };

                imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                //The second color manipulation is used to change the opacity of the
                //watermark.  This is done by applying a 5x5 matrix that contains the
                //coordinates for the RGBA space.  By setting the 3rd row and 3rd column
                //to 0.3f we achive a level of opacity
                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, opacity, 0.0f },
                    new float[] { 0.0f, 0.0f, 0.0f,    0.0f, 1.0f }
                };
                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

                imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                                               ColorAdjustType.Bitmap);

                //For this example we will place the watermark in the upper right
                //hand corner of the photograph. offset down 10 pixels and to the
                //left 10 pixles

                int xPosOfWm = 10;
                int yPosOfWm = ((phHeight - wmHeight) - 10);

                grWatermark.DrawImage(imgWatermark,
                                      new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight), //Set the detination position
                                      0,                                                    // x-coordinate of the portion of the source image to draw.
                                      0,                                                    // y-coordinate of the portion of the source image to draw.
                                      wmWidth,                                              // Watermark Width
                                      wmHeight,                                             // Watermark Height
                                      GraphicsUnit.Pixel,                                   // Unit of measurment
                                      imageAttributes);                                     //ImageAttributes Object

                imgWatermark.Dispose();
                grWatermark.Dispose();
            }

            #endregion

            //save new image to file system.
            if (outputDir.IsNullOrEmpty())
            {
                outputDir = Path.GetDirectoryName(imageFilePath);
            }

            var generatedName =
                Path.Combine(outputDir,
                             Path.GetFileNameWithoutExtension(imageFilePath) + postfix + Path.GetExtension(imageFilePath));
            imgPhoto.Save(generatedName, GetImageFormat(imageFilePath));

            imgPhoto.Dispose();
        }
Example #24
0
        /// <summary>
        /// 马路
        /// </summary>
        /// <param name="g"></param>
        /// <param name="time"></param>
        private void Draw2(Graphics g, int time)
        {
            if (base.DrawVisible)
            {
                Matrix matrix1 = base.Transform.Matrix.Clone();

                GraphicsContainer container1 = g.BeginContainer();

                g.SmoothingMode = base.OwnerDocument.SmoothingMode;

                Matrix matrix2 = base.GraphTransform.Matrix.Clone();
                base.GraphTransform.Matrix.Multiply(matrix1, MatrixOrder.Prepend);


                ClipAndMask.ClipPath.Clip(g, time, this);
                bool flag1 = base.Visible;
                if (!base.Visible)
                {
                    g.SetClip(Rectangle.Empty);
                }
                float single1 = this.StrokeOpacity;
                if (this.svgAnimAttributes.ContainsKey("fill-opacity"))
                {
                    single1 = Math.Min(single1, (float)this.svgAnimAttributes["fill-opacity"]);
                }
                ISvgBrush brush1 = this.GraphBrush;
                using (GraphicsPath path1 = (GraphicsPath)this.GPath.Clone()) {
                    path1.Transform(base.GraphTransform.Matrix);
                    if (!base.ShowBound)
                    {
                        float  width1 = Width * GraphTransform.Matrix.Elements[0];
                        Stroke stroke = Stroke.GetStroke(this);
                        Color  color1 = Color.FromArgb(75, 75, 75);
                        if (stroke.StrokeColor.ToArgb() != Color.Black.ToArgb())
                        {
                            color1 = stroke.StrokeColor;
                        }
                        using (Pen p = new Pen(Color.FromArgb((int)(single1 * 255), color1))) {
                            p.Width = width1;
                            g.DrawPath(p, path1);
                        }
                        if (LineType == "3")
                        {
                            using (Pen p = new Pen(Color.Yellow)) {
                                if (width1 > 30)
                                {
                                    p.Width = 2;
                                }
                                else
                                {
                                    p.Width = 1;
                                }
                                //p.DashPattern = new float[] { 10, 10 };
                                g.DrawPath(p, path1);
                            }
                        }
                        else
                        {
                            //using (Pen p = new Pen(Color.Yellow)) {
                            //    if (width1 > 30)
                            //        p.Width = 2;
                            //    else
                            //        p.Width = 1;
                            //    g.DrawPath(p, path1);
                            //}
                        }
                        if (LineType == "4")
                        {
                            using (Pen p = new Pen(Color.FromArgb((int)(single1 * 255), color1))) {
                                p.Width = width1;
                                float           f22             = width1 / 4f;
                                ImageAttributes imageAttributes = new ImageAttributes();
                                ColorMatrix     cmatrix1        = new ColorMatrix();
                                cmatrix1.Matrix00 = 1f;
                                cmatrix1.Matrix11 = 1f;
                                cmatrix1.Matrix22 = 1f;
                                cmatrix1.Matrix33 = single1;//透明度
                                cmatrix1.Matrix44 = 1f;
                                //设置透明度
                                imageAttributes.SetColorMatrix(cmatrix1, ColorMatrixFlag.Default, ColorAdjustType.Default);
                                if (BackgroundImage == null)
                                {
                                    BackgroundImageFile = "road.png";
                                }
                                TextureBrush tbush = new TextureBrush(BackgroundImage, new Rectangle(0, 0, BackgroundImage.Width, BackgroundImage.Height), imageAttributes);
                                tbush.WrapMode = WrapMode.Tile;
                                for (int i = 0; i < path1.PointCount - 1; i++)
                                {
                                    float k = (path1.PathPoints[i + 1].Y - path1.PathPoints[i].Y) / (path1.PathPoints[i + 1].X - path1.PathPoints[i].X);

                                    float y1    = path1.PathPoints[i].Y - path1.PathPoints[i + 1].Y;
                                    float y2    = path1.PathPoints[i].X - path1.PathPoints[i + 1].X;
                                    float k2    = (float)Math.Abs(k);
                                    float angle = (float)Math.Atan(k2) * 180 / (float)Math.PI;
                                    if (k < 0)
                                    {
                                        angle = 360 - angle;
                                    }

                                    PointF[] pts      = new PointF[] { new PointF(path1.PathPoints[i].X, path1.PathPoints[i].Y - 26) };
                                    Matrix   matrix11 = new Matrix();
                                    matrix11.RotateAt(angle, path1.PathPoints[i]);
                                    matrix11.Translate(path1.PathPoints[i].X, path1.PathPoints[i].Y);
                                    matrix11.Scale(width1 / 50, width1 / 50);
                                    //tbush.ScaleTransform(width1 / 50, width1 / 50, MatrixOrder.Append);
                                    //tbush.RotateTransform(angle, MatrixOrder.Append);
                                    //tbush.TranslateTransform(path1.PathPoints[i].X, path1.PathPoints[i].Y , MatrixOrder.Append);
                                    tbush.Transform = matrix11;

                                    p.Brush     = tbush.Clone() as TextureBrush;
                                    p.Alignment = PenAlignment.Center;

                                    g.DrawLine(p, path1.PathPoints[i], path1.PathPoints[i + 1]);
                                    tbush.ResetTransform();
                                }
                            }
                            if (BackgroundImageFile == "road.png")
                            {
                                using (Pen p = new Pen(Color.Yellow)) {
                                    if (width1 > 30)
                                    {
                                        p.Width = 2;
                                    }
                                    else
                                    {
                                        p.Width = 1;
                                    }
                                    g.DrawPath(p, path1);
                                }
                            }
                        }
                    }
                    else
                    {
                        g.DrawPath(new Pen(base.BoundColor), path1);
                    }
                    this.DrawConnect(g);
                }
                matrix1.Dispose();
                ClipAndMask.ClipPath.DrawClip(g, time, this);
                g.EndContainer(container1);
                this.pretime = time;
            }
        }
Example #25
0
 public extern static ReactElement Img(ImageAttributes properties, params ReactElementOrText[] children);
    protected override void Apply(ImageProcessingActionExecuteArgs args)
    {
        Bitmap result = null;
        try
        {
            // Create the result image
            result = new Bitmap(350, 350, CodeCarvings.Piczard.CommonData.DefaultPixelFormat);

            // Set the right image resolution (DPI)
            ImageHelper.SetImageResolution(result, args.ImageProcessingJob.OutputResolution);

            using (Graphics g = Graphics.FromImage(result))
            {
                // Use the max quality
                ImageHelper.SetGraphicsMaxQuality(g);

                if ((args.IsLastAction) && (!args.AppliedImageBackColorValue.HasValue))
                {
                    // Optimization (not mandatory)
                    // This is the last filter action and the ImageBackColor has not been yet applied...
                    // Apply the ImageBackColor now to save RAM & CPU
                    args.ApplyImageBackColor(g);
                }

                using (ImageAttributes imageAttributes = new ImageAttributes())
                {
                    // Important
                    imageAttributes.SetWrapMode(WrapMode.TileFlipXY);

                    // Draw the scaled image
                    Rectangle destinationRectangle = new Rectangle(75, 52, 200, 200);
                    using (Image resizedImage = new FixedCropConstraint(GfxUnit.Pixel, destinationRectangle.Size).GetProcessedImage(args.Image))
                    {
                        g.DrawImage(resizedImage, destinationRectangle, 0, 0, resizedImage.Width, resizedImage.Height, GraphicsUnit.Pixel, imageAttributes);

                        // Draw the reflection
                        destinationRectangle = new Rectangle(75, 252, 200, 98);
                        using (Image flippedImage = ImageTransformation.FlipVertical.GetProcessedImage(resizedImage))
                        {
                            g.DrawImage(flippedImage, destinationRectangle, 0, 0, flippedImage.Width, flippedImage.Height, GraphicsUnit.Pixel, imageAttributes);
                        }
                    }

                    // Draw the mask
                    destinationRectangle = new Rectangle(0, 0, result.Width, result.Height);
                    using (LoadedImage loadedImage = ImageArchiver.LoadImage("~/repository/filters/MyCustomFilter1Mask.png"))
                    {
                        g.DrawImage(loadedImage.Image, destinationRectangle, 0, 0, loadedImage.Size.Width, loadedImage.Size.Height, GraphicsUnit.Pixel, imageAttributes);
                    }
                }

                // Draw the text
                string text = "Generated by 'MyCustomFilter1' on " + DateTime.Now.ToString();
                FontDefinition fontDefinition = new FontDefinition();
                fontDefinition.Size = 12; //12px
                using (Font font = fontDefinition.GetFont())
                {
                    // Setup the custom parameters
                    g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    using (StringFormat stringFormat = new StringFormat())
                    {
                        SizeF textSize = g.MeasureString(text, font, int.MaxValue, stringFormat);
                        Size pixelTextSize = new Size(Convert.ToInt32(Math.Round(textSize.Width)), Convert.ToInt32(Math.Round(textSize.Height)));

                        // Calculate the text position
                        Point location = new Point((result.Width - pixelTextSize.Width) / 2, result.Height - 14 - pixelTextSize.Height);

                        // Draw the text
                        using (Brush brush = new SolidBrush(ColorTranslator.FromHtml("#5b615d")))
                        {
                            g.DrawString(text, font, brush, location, stringFormat);
                        }
                    }
                }
            }

            // Return the image
            args.Image = result;
        }
        catch
        {
            // An error has occurred...

            // Release the resources
            if (result != null)
            {
                result.Dispose();
                result = null;
            }

            // Re-throw the exception
            throw;
        }
    }
Example #27
0
        /// <summary>
        /// 生成图片
        /// </summary>
        public void CreateNew()
        {
            Image originalImage = Image.FromFile(this.OriginalImagePath);

            int towidth = this.Width;
            int toheight = this.Height;

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

            switch (this.Mode)
            {
                case HWMode.HW: // 指定高宽缩放(可能变形)
                    break;
                case HWMode.W: // 指定宽,高按比例
                    toheight = originalImage.Height * this.Width / originalImage.Width;
                    break;
                case HWMode.H: // 指定高,宽按比例
                    towidth = originalImage.Width * this.Height / originalImage.Height;
                    break;
                case HWMode.Cut: // 指定高宽裁减(不变形)
                    if (originalImage.Width / (double)originalImage.Height > 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 * this.Height / towidth;
                        x = 0;
                        y = (originalImage.Height - oh) / 2;
                    }

                    break;
                case HWMode.Auto:
                    if (originalImage.Height > originalImage.Width)
                    {
                        // 指定高,宽按比例
                        towidth = originalImage.Width * this.Height / originalImage.Height;
                    }
                    else // 指定宽,高按比例
                        toheight = originalImage.Height * this.Width / originalImage.Width;
                    break;
                case HWMode.Fill:
                    towidth = this.Width;
                    toheight = this.Height;
                    if (originalImage.Width > originalImage.Height)
                    {
                        ow = originalImage.Width;
                        oh = originalImage.Width;
                        x = 0;
                        y = (originalImage.Height - originalImage.Width) / 2;
                    }
                    else
                    {
                        ow = originalImage.Height;
                        oh = originalImage.Height;
                        x = (originalImage.Width - originalImage.Height) / 2;
                        y = 0;
                    }

                    break;
                default:
                    towidth = originalImage.Width;
                    toheight = originalImage.Height;
                    break;
            }

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

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

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

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

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

            // 在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(
                originalImage,
                new Rectangle(0, 0, towidth, toheight),
                new Rectangle(x, y, ow, oh),
                GraphicsUnit.Pixel);

            #region 填充水印

            if (!string.IsNullOrEmpty(this.MarkPath))
            {
                Image imgMark = new Bitmap(this.MarkPath);
                int intMarkWidth = imgMark.Width;
                int intMarkHeight = imgMark.Height;

                ImageAttributes imageAttributes = new ImageAttributes();

                float[][] colorMatrixElements =
                    {
                        new[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                        new[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                        new[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                        new[] { 0.0f, 0.0f, 0.0f, this.Opacity / 100f, 0.0f },
                        new[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                    };

                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

                imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

                int intLeft = 0, intTop = 0;
                switch (this.Position)
                {
                    case PositionMode.TopLeft:
                        intLeft = 0;
                        intTop = 0;
                        break;
                    case PositionMode.TopCenter:
                        intLeft = towidth / 2 - intMarkWidth / 2;
                        intTop = 0;
                        break;
                    case PositionMode.TopRight:
                        intLeft = towidth - intMarkWidth;
                        intTop = 0;
                        break;
                    case PositionMode.MiddleLeft:
                        intLeft = 0;
                        intTop = toheight / 2 - intMarkHeight / 2;
                        break;
                    case PositionMode.MiddleCenter:
                        intLeft = towidth / 2 - intMarkWidth / 2;
                        intTop = toheight / 2 - intMarkHeight / 2;
                        break;
                    case PositionMode.MiddleRight:
                        intLeft = towidth - intMarkWidth;
                        intTop = toheight / 2 - intMarkHeight / 2;
                        break;
                    case PositionMode.BottomLeft:
                        intLeft = 0;
                        intTop = toheight - intMarkHeight;
                        break;
                    case PositionMode.BottomCenter:
                        intLeft = towidth / 2 - intMarkWidth / 2;
                        intTop = toheight - intMarkHeight;
                        break;
                    case PositionMode.BottomRight:
                        intLeft = towidth - intMarkWidth;
                        intTop = toheight - intMarkHeight;
                        break;
                }

                g.DrawImage(imgMark, new Rectangle(intLeft, intTop, intMarkWidth, intMarkHeight), 0, 0, intMarkWidth, intMarkHeight, GraphicsUnit.Pixel, imageAttributes);
            }
            #endregion

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType == "image/jpeg")
                {
                    ici = codec;
                }
            }

            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
            try
            {
                // 以jpg格式保存缩略图
                bitmap.Save(this.SavePath, ici, ep);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
Example #28
0
        /// <summary>
        /// 图片水印
        /// </summary>
        /// <param name="imgPath">服务器图片相对路径</param>
        /// <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 imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            if (!File.Exists(Utils.GetMapPath(imgPath)))
            {
                return;
            }
            byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
            Image  img         = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));

            filename = Utils.GetMapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
            {
                watermarkFilename = "/" + watermarkFilename;
            }
            watermarkFilename = Utils.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
            {
                return;
            }
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

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

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap        colorMap        = new ColorMap();

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

            imageAttributes.SetRemapTable(remapTable, 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 }
            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, 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 Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new 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();
        }
Example #29
0
        void paint(bool force)
        {
            string s = "(no tags yet)";

            if (tag != null)
            {
                s = tag.tag.tag;
            }

            if (!force && s == lastTag && this.Size == lastSize)
            {
                return;
            }

            lastTag  = s;
            lastSize = this.Size;

            gTags.Text = s;

            if (!gPic.Visible)
            {
                return;
            }

            if (gPic.Image != null)
            {
                var old = gPic.Image;
                gPic.Image = null;
                old.Dispose();
            }

            // label kerning is busted if non-cleartype,
            // graphics hinting is busted if non-cleartype,
            // win by grayscaling cleartype (orz)

            var brushBG = new SolidBrush(gTags.BackColor);
            var bmFG    = new Bitmap(gPic.Width, gPic.Height, PixelFormat.Format24bppRgb);

            using (var g = Graphics.FromImage(bmFG))
            {
                setGraphicOptions(g);
                g.TextRenderingHint = gTags.Hinting;
                g.TextContrast      = 0; // 0..12

                var sz = g.MeasureString(s, gTags.Font, gPic.Width);
                var al = settings.tboxAlign;

                int margin = 4;

                var x = -1;
                if (al == 1 || al == 4 || al == 7)
                {
                    x = margin;
                }
                else if (al == 3 || al == 6 || al == 9)
                {
                    x = (int)((gPic.Width - margin) - sz.Width);
                }
                else
                {
                    x = (int)((gPic.Width - sz.Width) / 2);
                }

                var y = -1;
                if (al == 1 || al == 2 || al == 3)
                {
                    y = margin;
                }
                else if (al == 7 || al == 8 || al == 9)
                {
                    y = (int)((gPic.Height - margin) - sz.Height);
                }
                else
                {
                    y = (int)((gPic.Height - sz.Height) / 2);
                }

                g.FillRectangle(Brushes.Black, 0, 0, gPic.Width, gPic.Height);

                g.DrawString(s, gTags.Font, Brushes.White, new RectangleF(
                                 x, y, gPic.Width - margin * 2, gPic.Height - margin * 2));
            }

            var bmBG = new Bitmap(gPic.Width, gPic.Height);

            using (Graphics g = Graphics.FromImage(bmBG))
            {
                setGraphicOptions(g);
                g.FillRectangle(brushBG, 0, 0, gPic.Width, gPic.Height);

                float cr  = gTags.ForeColor.R / 256f;
                float cg  = gTags.ForeColor.G / 256f;
                float cb  = gTags.ForeColor.B / 256f;
                var   tab = new float[][] {
                    new float[] { 0, 0, 0, .30f, 0 },
                    new float[] { 0, 0, 0, .59f, 0 },
                    new float[] { 0, 0, 0, .11f, 0 },
                    new float[] { 0, 0, 0, 0, 0 },
                    new float[] { cr, cg, cb, 0, 1 }
                };
                var cm = new ColorMatrix(tab);
                using (var iattr = new ImageAttributes())
                {
                    iattr.SetColorMatrix(cm);
                    g.DrawImage(bmFG, new Rectangle(Point.Empty, gPic.Size),
                                0, 0, gPic.Width, gPic.Height, GraphicsUnit.Pixel, iattr);
                }
            }
            bmFG.Dispose();
            brushBG.Dispose();
            gPic.Image = bmBG;
        }
Example #30
0
    /// <summary>
    /// 图片水印
    /// </summary>
    /// <param name="imgPath">服务器图片相对路径</param>
    /// <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 imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
    {
        byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath));
            Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes));
            filename = HttpContext.Current.Server.MapPath(filename);

            if (watermarkFilename.StartsWith("/") == false)
                watermarkFilename = "/" + watermarkFilename;
            watermarkFilename = Utils.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
                return;
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

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

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();

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

            imageAttributes.SetRemapTable(remapTable, 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}
                                            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, 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 Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

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

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new 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();
    }
    public string GenerateImage(string savePath, string sPhysicalPath, string sOrgFileName, string sImageFileName, ImageFormat oFormat, int widthnew, int heightnew)
    {
        string filename = sOrgFileName.Substring(0, sOrgFileName.LastIndexOf("."));
        Size thumsize = new Size(widthnew, heightnew);
        try
        {
            if (oFormat != ImageFormat.Gif)
            {
                System.Drawing.Image oImg = System.Drawing.Image.FromFile(sPhysicalPath + @"\" + sOrgFileName);
                System.Drawing.Image oThumbNail = new Bitmap(thumsize.Width, thumsize.Height, oImg.PixelFormat);

                Graphics oGraphic = Graphics.FromImage(oThumbNail);
                oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                oGraphic.SmoothingMode = SmoothingMode.AntiAlias;
                oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                oGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                ImageAttributes attribute = new ImageAttributes();
                attribute.SetWrapMode(WrapMode.TileFlipXY);
                oGraphic.DrawImage(oImg, new Rectangle(new Point(0, 0), thumsize), 0, 0, oImg.Width, oImg.Height, GraphicsUnit.Pixel, attribute);

                oImg.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();

                // First delete the image
                //FileInfo fi = new FileInfo(sPhysicalPath + sOrgFileName);
                //fi.Attributes = FileAttributes.Normal;
                //fi.Delete();

                // Then resave it with its new size
                oThumbNail.Save(sPhysicalPath + sImageFileName, oFormat);

                // Empty Garbage
                oGraphic.Dispose();
                oThumbNail.Dispose();
                GC.Collect();
                sb.Append(sPhysicalPath + sImageFileName);
            }
            else
            {
                Bitmap bm = new Bitmap(sPhysicalPath + @"\" + sOrgFileName);
                Bitmap bm2 = new Bitmap(thumsize.Width, thumsize.Height, PixelFormat.Format64bppArgb);
                Graphics g2 = Graphics.FromImage(bm2);

                Rectangle subRect = new Rectangle(0, 0, thumsize.Width, thumsize.Height);
                g2.DrawImage(bm, subRect);
                bm.Dispose();
                GC.Collect();
                GC.WaitForPendingFinalizers();

                bm2.Save(sPhysicalPath + sImageFileName, ImageFormat.Jpeg);
                g2.Dispose();
                bm2.Dispose();
                GC.Collect();

                sb.Append(sPhysicalPath + sImageFileName);

            }
        }
        catch (Exception e1) { sb.Append(e1.Message); }
        return sb.ToString();
    }
Example #32
0
    /// <summary>
    /// Creating a Watermarked Photograph with GDI+ for .NET
    /// </summary>
    /// <param name="rSrcImgPath">原始图片的物理路径</param>
    /// <param name="rMarkImgPath">水印图片的物理路径</param>
    /// <param name="rMarkText">水印文字(不显示水印文字设为空串)</param>
    /// <param name="rDstImgPath">输出合成后的图片的物理路径</param>
    public void BuildWatermark(Image rSrcImgPath, string rMarkImgPath, string rMarkText, string rDstImgPath)
    {
        //以下(代码)从一个指定文件创建了一个Image 对象,然后为它的 Width 和 Height定义变量。
        //这些长度待会被用来建立一个以24 bits 每像素的格式作为颜色数据的Bitmap对象。

        Image  imgPhoto = rSrcImgPath;
        int    phWidth  = imgPhoto.Width;
        int    phHeight = imgPhoto.Height;
        Bitmap bmPhoto  = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(100, 100);
        Graphics grPhoto = Graphics.FromImage(bmPhoto);

        //这个代码载入水印图片,水印图片已经被保存为一个BMP文件,以绿色(A=0,R=0,G=255,B=0)作为背景颜色。
        //再一次,会为它的Width 和Height定义一个变量。
        Image imgWatermark = new Bitmap(rMarkImgPath);
        int   wmWidth      = imgWatermark.Width;
        int   wmHeight     = imgWatermark.Height;

        //这个代码以100%它的原始大小绘制imgPhoto 到Graphics 对象的(x=0,y=0)位置。
        //以后所有的绘图都将发生在原来照片的顶部。
        grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
        grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, phWidth, phHeight), 0, 0, phWidth, phHeight, GraphicsUnit.Pixel);
        //为了最大化版权信息的大小,我们将测试7种不同的字体大小来决定我们能为我们的照片宽度使用的可能的最大大小。
        //为了有效地完成这个,我们将定义一个整型数组,接着遍历这些整型值测量不同大小的版权字符串。
        //一旦我们决定了可能的最大大小,我们就退出循环,绘制文本
        int[] sizes  = new int[] { 16, 14, 12, 10, 8, 6, 4 };
        Font  crFont = null;
        SizeF crSize = new SizeF();

        for (int i = 0; i < 7; i++)
        {
            crFont = new Font("arial", sizes[i],
                              FontStyle.Bold);
            crSize = grPhoto.MeasureString(rMarkText, crFont);
            if ((ushort)crSize.Width < (ushort)phWidth)
            {
                break;
            }
        }
        //因为所有的照片都有各种各样的高度,所以就决定了从图象底部开始的5%的位置开始。
        //使用rMarkText字符串的高度来决定绘制字符串合适的Y坐标轴。
        //通过计算图像的中心来决定X轴,然后定义一个StringFormat 对象,设置StringAlignment 为Center。
        //int yPixlesFromBottom = 100; //(int)(phHeight * .05);
        float        yPosFromBottom = 100;//((phHeight - yPixlesFromBottom) - (crSize.Height / 2));
        float        xCenterOfImg   = (phWidth / 2);
        StringFormat StrFormat      = new StringFormat();

        StrFormat.Alignment = StringAlignment.Center;
        //现在我们已经有了所有所需的位置坐标来使用60%黑色的一个Color(alpha值153)创建一个SolidBrush 。
        //在偏离右边1像素,底部1像素的合适位置绘制版权字符串。
        //这段偏离将用来创建阴影效果。使用Brush重复这样一个过程,在前一个绘制的文本顶部绘制同样的文本。
        SolidBrush semiTransBrush2 =
            new SolidBrush(Color.FromArgb(153, 0, 0, 0));

        grPhoto.DrawString(rMarkText, crFont, semiTransBrush2,
                           new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat);
        SolidBrush semiTransBrush = new SolidBrush(
            Color.FromArgb(153, 255, 255, 255));

        grPhoto.DrawString(rMarkText,
                           crFont,
                           semiTransBrush,
                           new PointF(xCenterOfImg, yPosFromBottom),
                           StrFormat);
        //根据前面修改后的照片创建一个Bitmap。把这个Bitmap载入到一个新的Graphic对象。
        Bitmap bmWatermark = new Bitmap(bmPhoto);

        bmWatermark.SetResolution(
            imgPhoto.HorizontalResolution,
            imgPhoto.VerticalResolution);
        Graphics grWatermark =
            Graphics.FromImage(bmWatermark);
        //通过定义一个ImageAttributes 对象并设置它的两个属性,我们就是实现了两个颜色的处理,以达到半透明的水印效果。
        //处理水印图象的第一步是把背景图案变为透明的(Alpha=0, R=0, G=0, B=0)。我们使用一个Colormap 和定义一个RemapTable来做这个。
        //就像前面展示的,我的水印被定义为100%绿色背景,我们将搜到这个颜色,然后取代为透明。
        ImageAttributes imageAttributes =
            new ImageAttributes();
        ColorMap colorMap = new ColorMap();

        colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
        colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
        ColorMap[] remapTable = { colorMap };
        //第二个颜色处理用来改变水印的不透明性。
        //通过应用包含提供了坐标的RGBA空间的5x5矩阵来做这个。
        //通过设定第三行、第三列为0.3f我们就达到了一个不透明的水平。结果是水印会轻微地显示在图象底下一些。
        imageAttributes.SetRemapTable(remapTable,
                                      ColorAdjustType.Bitmap);
        float[][] colorMatrixElements =
        {
            new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
            new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
            new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
            new float[] { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f },
            new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
        };
        ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

        imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
        //随着两个颜色处理加入到imageAttributes 对象,我们现在就能在照片右手边上绘制水印了。
        //我们会偏离10像素到底部,10像素到左边。
        int markWidth;
        int markHeight;

        //mark比原来的图宽
        //if (phWidth <= wmWidth)
        //{
        //    markWidth = phWidth - 10;
        //    markHeight = (markWidth * wmHeight) / wmWidth;
        //}
        //else if (phHeight <= wmHeight)
        //{
        //    markHeight = phHeight - 10;
        //    markWidth = (markHeight * wmWidth) / wmHeight;
        //}
        //else
        //{
        //    markWidth = wmWidth;
        //    markHeight = wmHeight;
        //}
        markHeight = phWidth / 6;   //wmHeight/2;
        markWidth  = phWidth / 6;   //wmWidth/2;
        int xPosOfWm = phWidth / 2; //((phWidth - markWidth) - 10);
        int yPosOfWm = phHeight - (phHeight / 3);

        grWatermark.DrawImage(imgWatermark, new Rectangle(xPosOfWm, yPosOfWm, markWidth, markHeight), 0, 0, wmWidth, wmHeight, GraphicsUnit.Pixel, imageAttributes);
        //最后的步骤将是使用新的Bitmap取代原来的Image。 销毁两个Graphic对象,然后把Image 保存到文件系统。
        imgPhoto = bmWatermark;
        grPhoto.Dispose();
        grWatermark.Dispose();
        imgPhoto.Save(rDstImgPath, ImageFormat.Jpeg);
        imgPhoto.Dispose();
        imgWatermark.Dispose();
    }
Example #33
0
        public void DrawImageAlpha(float alpha, AbstractImage mimage, RectangleF targetRect)
        {
            // Clamp and Quantize
            alpha = Util.Clamp(alpha, 0f, 1f);
            alpha = (float)Math.Round(alpha * 16f) / 16f;
            if (alpha <= 0f)
            {
                return;
            }
            if (alpha >= 1f)
            {
                g.DrawImage(mimage.XImage, targetRect);
                return;
            }

            int key = (int)Math.Round(alpha * 16);

            Image  image = mimage.Image;
            XImage ximage;
            int    w, h;

            lock (image)
            {
                w = image.Width;
                h = image.Height;

                if (image.Tag == null || !(image.Tag is Dictionary <int, XImage>))
                {
                    image.Tag = new Dictionary <int, XImage>();
                }

                Dictionary <int, XImage> dict = image.Tag as Dictionary <int, XImage>;
                if (dict.ContainsKey(key))
                {
                    ximage = dict[key];
                }
                else
                {
                    // Need to construct a new image (PdfSharp can't alpha-render images)
                    // Memoize these in the image itself, since most requests will be from
                    // a small set

                    Bitmap scratchBitmap = new Bitmap(w, h, PixelFormat.Format32bppArgb);
                    using (var scratchGraphics = Graphics.FromImage(scratchBitmap))
                    {
                        ColorMatrix matrix = new ColorMatrix();
                        matrix.Matrix00 = matrix.Matrix11 = matrix.Matrix22 = 1;
                        matrix.Matrix33 = alpha;

                        ImageAttributes attr = new ImageAttributes();
                        attr.SetColorMatrix(matrix);

                        scratchGraphics.DrawImage(image, new Rectangle(0, 0, w, h), 0, 0, w, h, GraphicsUnit.Pixel, attr);
                    }

                    ximage    = XImage.FromGdiPlusImage(scratchBitmap);
                    dict[key] = ximage;
                }
            }

            lock (ximage)
            {
                g.DrawImage(ximage, targetRect);
            }
        }
Example #34
0
        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="oldFilePath">原始图片路径</param>
        /// <param name="newFilePath">将要添加水印图片路径</param>
        /// <param name="waterPosition">水印位置</param>
        /// <param name="waterImagePath">水印图片路径</param>
        /// <param name="transparency">透明度</param>
        /// <param name="quality">质量</param>
        public static void CreateWaterImage(string oldFilePath, string newFilePath, int waterPosition, string waterImagePath, int watermarkTransparency, int quality)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(oldFilePath);

            Bitmap bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);

            Graphics g = Graphics.FromImage(bmp);

            g.Clear(Color.White);

            g.DrawImage(image, 0, 0, image.Width, image.Height);

            //设置透明度
            System.Drawing.Image watermark       = new Bitmap(waterImagePath);
            ImageAttributes      imageAttributes = new ImageAttributes();
            ColorMap             colorMap        = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };
            imageAttributes.SetRemapTable(remapTable, 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 },                                                                                          //注意:倒数第二处为0.0f为完全透明,1.0f为完全不透明
                new float[] { 0.0f, 0.0f, 0.0f,         0.0f, 1.0f }
            };
            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

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

            int    _width          = image.Width;
            int    _height         = image.Height;
            int    xpos            = 0;
            int    ypos            = 0;
            int    WatermarkWidth  = 0;
            int    WatermarkHeight = 0;
            double bl = 1d;

            //计算水印图片的比率
            //取背景的1/4宽度来比较
            if ((_width > watermark.Width * 2) && (_height > watermark.Height * 2))
            {
                bl = 1;
            }
            else if ((_width > watermark.Width * 2) && (_height < watermark.Height * 2))
            {
                bl = Convert.ToDouble(_height / 2) / Convert.ToDouble(watermark.Height);
            }
            else if ((_width < watermark.Width * 2) && (_height > watermark.Height * 2))
            {
                bl = Convert.ToDouble(_width / 2) / Convert.ToDouble(watermark.Width);
            }
            else
            {
                if ((_width * watermark.Height) > (_height * watermark.Width))
                {
                    bl = Convert.ToDouble(_height / 2) / Convert.ToDouble(watermark.Height);
                }
                else
                {
                    bl = Convert.ToDouble(_width / 2) / Convert.ToDouble(watermark.Width);
                }
            }
            WatermarkWidth  = Convert.ToInt32(watermark.Width * bl);
            WatermarkHeight = Convert.ToInt32(watermark.Height * bl);
            switch (waterPosition)
            {
            case 3:
                xpos = _width - WatermarkWidth - 10;
                ypos = 10;
                break;

            case 2:
                xpos = 10;
                ypos = _height - WatermarkHeight - 10;
                break;

            case 5:
                xpos = _width / 2 - WatermarkWidth / 2;
                ypos = _height / 2 - WatermarkHeight / 2;
                break;

            case 1:
                xpos = 10;
                ypos = 10;
                break;

            case 4:
            default:
                xpos = _width - WatermarkWidth - 10;
                ypos = _height - WatermarkHeight - 10;
                break;
            }
            g.DrawImage(watermark, new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);
            try
            {
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   ici    = null;
                foreach (ImageCodecInfo codec in codecs)
                {
                    if (codec.MimeType.IndexOf("jpeg") > -1)
                    {
                        ici = codec;
                    }
                }
                EncoderParameters encoderParams = new EncoderParameters();
                long[]            qualityParam  = new long[1];

                if (quality < 0 || quality > 100)
                {
                    quality = 80;
                }

                qualityParam[0] = quality;

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

                if (ici != null)
                {
                    bmp.Save(newFilePath, ici, encoderParams);
                }
                else
                {
                    bmp.Save(newFilePath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                watermark.Dispose();
                imageAttributes.Dispose();
                image.Dispose();
                bmp.Dispose();
            }
        }
Example #35
0
        internal void DrawImage(GaugeGraphics g, bool primary, bool drawShadow)
        {
            if (!Visible || (drawShadow && base.ShadowOffset == 0f))
            {
                return;
            }
            float width = Width;

            width = g.GetAbsoluteDimension(width);
            Image image = null;

            image = ((!primary) ? Common.ImageLoader.LoadImage(CapImage) : Common.ImageLoader.LoadImage(Image));
            if (image.Width == 0 || image.Height == 0)
            {
                return;
            }
            Point empty = Point.Empty;

            empty = ((!primary) ? CapImageOrigin : ImageOrigin);
            if (empty.IsEmpty)
            {
                empty.X = image.Width / 2;
                empty.Y = image.Height / 2;
            }
            int num = (image.Height <= image.Width) ? image.Width : image.Height;

            if (num != 0)
            {
                float           num2            = (!primary) ? (g.GetAbsoluteDimension(CapWidth * 2f) / (float)num) : (g.GetAbsoluteDimension(Width * 2f) / (float)num);
                Rectangle       rectangle       = new Rectangle(0, 0, (int)((float)image.Width * num2), (int)((float)image.Height * num2));
                ImageAttributes imageAttributes = new ImageAttributes();
                if (primary && ImageTransColor != Color.Empty)
                {
                    imageAttributes.SetColorKey(ImageTransColor, ImageTransColor, ColorAdjustType.Default);
                }
                if (!primary && CapImageTransColor != Color.Empty)
                {
                    imageAttributes.SetColorKey(CapImageTransColor, CapImageTransColor, ColorAdjustType.Default);
                }
                Matrix transform         = g.Transform;
                Matrix matrix            = g.Transform.Clone();
                float  positionFromValue = GetScale().GetPositionFromValue(base.Position);
                PointF absolutePoint     = g.GetAbsolutePoint(GetScale().GetPivotPoint());
                PointF pointF            = new PointF((float)empty.X * num2, (float)empty.Y * num2);
                float  offsetX           = matrix.OffsetX;
                float  offsetY           = matrix.OffsetY;
                matrix.Translate(absolutePoint.X - pointF.X, absolutePoint.Y - pointF.Y, MatrixOrder.Append);
                absolutePoint.X += offsetX;
                absolutePoint.Y += offsetY;
                matrix.RotateAt(positionFromValue, absolutePoint, MatrixOrder.Append);
                if (drawShadow)
                {
                    ColorMatrix colorMatrix = new ColorMatrix();
                    colorMatrix.Matrix00 = 0f;
                    colorMatrix.Matrix11 = 0f;
                    colorMatrix.Matrix22 = 0f;
                    colorMatrix.Matrix33 = Common.GaugeCore.ShadowIntensity / 100f;
                    imageAttributes.SetColorMatrix(colorMatrix);
                    matrix.Translate(base.ShadowOffset, base.ShadowOffset, MatrixOrder.Append);
                }
                else if (primary && !ImageHueColor.IsEmpty)
                {
                    Color       color        = g.TransformHueColor(ImageHueColor);
                    ColorMatrix colorMatrix2 = new ColorMatrix();
                    colorMatrix2.Matrix00 = (float)(int)color.R / 255f;
                    colorMatrix2.Matrix11 = (float)(int)color.G / 255f;
                    colorMatrix2.Matrix22 = (float)(int)color.B / 255f;
                    imageAttributes.SetColorMatrix(colorMatrix2);
                }
                else if (!primary && !CapImageHueColor.IsEmpty)
                {
                    Color       color2       = g.TransformHueColor(CapImageHueColor);
                    ColorMatrix colorMatrix3 = new ColorMatrix();
                    colorMatrix3.Matrix00 = (float)(int)color2.R / 255f;
                    colorMatrix3.Matrix11 = (float)(int)color2.G / 255f;
                    colorMatrix3.Matrix22 = (float)(int)color2.B / 255f;
                    imageAttributes.SetColorMatrix(colorMatrix3);
                }
                g.Transform = matrix;
                ImageSmoothingState imageSmoothingState = new ImageSmoothingState(g);
                imageSmoothingState.Set();
                g.DrawImage(image, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes);
                imageSmoothingState.Restore();
                g.Transform = transform;
                if (!drawShadow)
                {
                    matrix.Translate(0f - offsetX, 0f - offsetY, MatrixOrder.Append);
                    GraphicsPath graphicsPath = new GraphicsPath();
                    graphicsPath.AddRectangle(rectangle);
                    graphicsPath.Transform(matrix);
                    AddHotRegion(graphicsPath, primary);
                }
            }
        }
Example #36
0
        /// <summary>
        /// Renders the layer
        /// </summary>
        /// <param name="graphics">Graphics object reference</param>
        /// <param name="map">Map which is rendered</param>
        public override void Render(Graphics graphics, MapViewport map)
        {
            var bbox   = map.Envelope;
            var extent = new Extent(bbox.MinX, bbox.MinY, bbox.MaxX, bbox.MaxY);
            var level  = BruTile.Utilities.GetNearestLevel(_source.Schema.Resolutions, Math.Max(map.PixelWidth, map.PixelHeight));
            var tiles  = _source.Schema.GetTileInfos(extent, level);

            //Abort previous running Threads
            Cancel();

            using (var ia = new ImageAttributes())
            {
                if (!_transparentColor.IsEmpty)
                {
                    ia.SetColorKey(_transparentColor, _transparentColor);
                }
#if !PocketPC
                ia.SetWrapMode(WrapMode.TileFlipXY);
#endif
                var tileWidth  = _source.Schema.GetTileWidth(level);
                var tileHeight = _source.Schema.GetTileHeight(level);

                foreach (TileInfo info in tiles)
                {
                    if (_bitmaps.Find(info.Index) != null)
                    {
                        //draws directly the bitmap
                        var bb = new Envelope(new Coordinate(info.Extent.MinX, info.Extent.MinY),
                                              new Coordinate(info.Extent.MaxX, info.Extent.MaxY));
                        HandleMapNewTileAvaliable(map, graphics, bb, _bitmaps.Find(info.Index),
                                                  tileWidth, tileHeight, ia);
                    }
                    else if (_fileCache != null && _fileCache.Exists(info.Index))
                    {
                        Bitmap img = GetImageFromFileCache(info) as Bitmap;
                        _bitmaps.Add(info.Index, img);

                        //draws directly the bitmap
                        var btExtent = info.Extent;
                        var bb       = new Envelope(new Coordinate(btExtent.MinX, btExtent.MinY),
                                                    new Coordinate(btExtent.MaxX, btExtent.MaxY));
                        HandleMapNewTileAvaliable(map, graphics, bb, _bitmaps.Find(info.Index),
                                                  tileWidth, tileHeight, ia);
                    }
                    else
                    {
                        var cancelToken = new CancellationTokenSource();
                        var token       = cancelToken.Token;
                        var l_info      = info;
                        if (Logger.IsDebugEnabled)
                        {
                            Logger.DebugFormat("Starting new Task to download tile {0},{1},{2}", info.Index.Level, info.Index.Col, info.Index.Row);
                        }
                        var t = new System.Threading.Tasks.Task(delegate
                        {
                            if (token.IsCancellationRequested)
                            {
                                token.ThrowIfCancellationRequested();
                            }

                            if (Logger.IsDebugEnabled)
                            {
                                Logger.DebugFormat("Task started for download of tile {0},{1},{2}", info.Index.Level, info.Index.Col, info.Index.Row);
                            }

                            var res = GetTileOnThread(token, _source, l_info, _bitmaps, true);
                            if (res)
                            {
                                Interlocked.Decrement(ref _numPendingDownloads);
                                var e = DownloadProgressChanged;
                                if (e != null)
                                {
                                    e(_numPendingDownloads);
                                }
                            }
                        }, token);
                        var dt = new DownloadTask()
                        {
                            CancellationToken = cancelToken, Task = t
                        };
                        lock (_currentTasks)
                        {
                            _currentTasks.Add(dt);
                            _numPendingDownloads++;
                        }
                        t.Start();
                    }
                }
            }
        }
Example #37
0
        /// <summary>
        /// 为图片附件图片水印
        /// </summary>
        /// <param name="targetStream">需要打水印的图片流</param>
        /// <param name="watermarkStream">水印文件的图片流</param>
        /// <param name="watermarkStatus">图片水印位置
        /// 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下</param>
        /// <param name="quality">附加水印图片质量,0-100</param>
        /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
        /// <returns></returns>
        public static Stream AttachWaterMark(Stream targetStream, Stream watermarkStream, int watermarkStatus = 9, int quality = 80, int watermarkTransparency = 5)
        {
            MemoryStream ms = null;

            if (null == targetStream || null == watermarkStream)
            {
                return(ms);
            }

            //构造源图对象GDI
            Image    img = Image.FromStream(targetStream);
            Graphics g   = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkStream);

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

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap        colorMap        = new ColorMap();

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

            imageAttributes.SetRemapTable(remapTable, 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 }
            };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, 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;

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

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

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo   ici    = null;

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                {
                    ici = codec;
                }
            }
            EncoderParameters encoderParams = new EncoderParameters();

            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
            {
                quality = 80;
            }

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);

            encoderParams.Param[0] = encoderParam;

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

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
            ms.Position = 0;

            return(ms);
        }
Example #38
0
        static void HandleMapNewTileAvaliable(MapViewport map, Graphics g, Envelope box, Bitmap bm, int sourceWidth, int sourceHeight, ImageAttributes imageAttributes)
        {
            try
            {
                var min = map.WorldToImage(box.Min());
                var max = map.WorldToImage(box.Max());

                min = new PointF((float)Math.Round(min.X), (float)Math.Round(min.Y));
                max = new PointF((float)Math.Round(max.X), (float)Math.Round(max.Y));

                g.DrawImage(bm,
                            new Rectangle((int)min.X, (int)max.Y, (int)(max.X - min.X), (int)(min.Y - max.Y)),
                            0, 0,
                            sourceWidth, sourceHeight,
                            GraphicsUnit.Pixel,
                            imageAttributes);

                // g.Dispose();
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                //this can be a GDI+ Hell Exception...
            }
        }
Example #39
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Bitmap newImage = null;
            Image  image    = factory.Image;

            try
            {
                int        sourceWidth  = image.Width;
                int        sourceHeight = image.Height;
                RectangleF rectangleF;
                CropLayer  cropLayer = this.DynamicParameter;

                if (cropLayer.CropMode == CropMode.Percentage)
                {
                    // Fix for whole numbers.
                    cropLayer.Left   = cropLayer.Left > 1 ? cropLayer.Left / 100 : cropLayer.Left;
                    cropLayer.Right  = cropLayer.Right > 1 ? cropLayer.Right / 100 : cropLayer.Right;
                    cropLayer.Top    = cropLayer.Top > 1 ? cropLayer.Top / 100 : cropLayer.Top;
                    cropLayer.Bottom = cropLayer.Bottom > 1 ? cropLayer.Bottom / 100 : cropLayer.Bottom;

                    // Work out the percentages.
                    float left   = cropLayer.Left * sourceWidth;
                    float top    = cropLayer.Top * sourceHeight;
                    float width  = cropLayer.Right < 1 ? (1 - cropLayer.Left - cropLayer.Right) * sourceWidth : sourceWidth;
                    float height = cropLayer.Bottom < 1 ? (1 - cropLayer.Top - cropLayer.Bottom) * sourceHeight : sourceHeight;

                    rectangleF = new RectangleF(left, top, width, height);
                }
                else
                {
                    rectangleF = new RectangleF(cropLayer.Left, cropLayer.Top, cropLayer.Right, cropLayer.Bottom);
                }

                Rectangle rectangle = Rectangle.Round(rectangleF);

                if (rectangle.X < sourceWidth && rectangle.Y < sourceHeight)
                {
                    if (rectangle.Width > (sourceWidth - rectangle.X))
                    {
                        rectangle.Width = sourceWidth - rectangle.X;
                    }

                    if (rectangle.Height > (sourceHeight - rectangle.Y))
                    {
                        rectangle.Height = sourceHeight - rectangle.Y;
                    }

                    newImage = new Bitmap(rectangle.Width, rectangle.Height);
                    newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

                    using (Graphics graphics = Graphics.FromImage(newImage))
                    {
                        graphics.SmoothingMode      = SmoothingMode.AntiAlias;
                        graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                        graphics.CompositingQuality = CompositingQuality.HighQuality;

                        // An unwanted border appears when using InterpolationMode.HighQualityBicubic to resize the image
                        // as the algorithm appears to be pulling averaging detail from surrounding pixels beyond the edge
                        // of the image. Using the ImageAttributes class to specify that the pixels beyond are simply mirror
                        // images of the pixels within solves this problem.
                        using (ImageAttributes wrapMode = new ImageAttributes())
                        {
                            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                            graphics.DrawImage(
                                image,
                                new Rectangle(0, 0, rectangle.Width, rectangle.Height),
                                rectangle.X,
                                rectangle.Y,
                                rectangle.Width,
                                rectangle.Height,
                                GraphicsUnit.Pixel,
                                wrapMode);
                        }
                    }

                    // Reassign the image.
                    image.Dispose();
                    image = newImage;
                }
            }
            catch (Exception ex)
            {
                if (newImage != null)
                {
                    newImage.Dispose();
                }

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return(image);
        }
Example #40
0
        private void Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            Image image   = (Image)e.Argument;
            var   minSize = new Size(3840, 2160);
            Size  newSize;

            if (image.Width < minSize.Width || image.Height < minSize.Height)
            {
                var ratio = Math.Max((double)minSize.Width / image.Width, (double)minSize.Height / image.Height);
                newSize = new Size((int)(ratio * image.Width), (int)(ratio * image.Height));
            }
            else
            {
                newSize = image.Size;
            }
            var newRect = new Rectangle(Point.Empty, newSize);

            Emgu.CV.Image <Emgu.CV.Structure.Bgr, byte> cvImage;
            using (var bitmap = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb)) {
                using (var graphics = Graphics.FromImage(bitmap)) {
                    graphics.CompositingQuality = CompositingQuality.HighQuality;
                    graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                    graphics.SmoothingMode      = SmoothingMode.HighQuality;
                    graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                    using (var wrapMode = new ImageAttributes()) {
                        wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                        graphics.DrawImage(image, newRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                    }
                }

                Invoke(new Action(() => {
                    if (screenshotViewer == null)
                    {
                        screenshotViewer = new ScreenshotViewer(this)
                        {
                            Top = Top, Left = Right
                        }
                    }
                    ;
                    screenshotViewer.SetImage(new Bitmap(bitmap));
                    screenshotViewer.Show();
                }));

                var data   = bitmap.LockBits(newRect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                var nBytes = data.Stride * data.Height;
                cvImage = new Emgu.CV.Image <Emgu.CV.Structure.Bgr, byte>(newSize);
                unsafe {
                    Buffer.MemoryCopy(data.Scan0.ToPointer(), cvImage.Mat.DataPointer.ToPointer(), nBytes, nBytes);
                }
                bitmap.UnlockBits(data);
            }

            if (sift == null)
            {
                sift = new Emgu.CV.Features2D.SIFT(edgeThreshold: 25, sigma: 1.2);
            }
            if (matcher == null)
            {
                var use_bf = true;
                if (use_bf)
                {
                    matcher = new Emgu.CV.Features2D.BFMatcher(Emgu.CV.Features2D.DistanceType.L2);
                }
                else
                {
                    matcher = new Emgu.CV.Features2D.FlannBasedMatcher(new Emgu.CV.Flann.KdTreeIndexParams(5), new Emgu.CV.Flann.SearchParams());
                }
            }

            if (heroDescriptors == null)
            {
                Invoke(new Action(() => {
                    screenshotViewer.SetProgress(Stage.LoadingData);
                }));
                heroDescriptors   = loadDescriptors("portraits.zip");
                bgnameDescriptors = loadDescriptors("bgnames.zip");
            }

            int nTotal   = heroDescriptors.Count + bgnameDescriptors.Count;
            int nCurrent = 0;

            using (var kp = new Emgu.CV.Util.VectorOfKeyPoint())
                using (var des = new Emgu.CV.Mat()) {
                    Invoke(new Action(() => {
                        screenshotViewer.SetProgress(Stage.ProcessingImage);
                    }));
                    sift.DetectAndCompute(cvImage, null, kp, des, false);
                    cvImage.Dispose();

                    var searchResults = new List <SearchResult>();
                    Invoke(new Action(() => {
                        screenshotViewer.SetProgress(0.0);
                    }));
                    foreach (var kvp in heroDescriptors)
                    {
                        using (var vMatches = new Emgu.CV.Util.VectorOfVectorOfDMatch()) {
                            matcher.KnnMatch(kvp.Value, des, vMatches, 2);
                            const float maxdist = 0.7f;
                            var         matches = vMatches.ToArrayOfArray().Where(m => m[0].Distance < maxdist * m[1].Distance).ToList();
                            if (matches.Any())
                            {
                                searchResults.Add(new SearchResult(kvp.Key, matches, kp));
                            }
                        }
                        nCurrent++;
                        Invoke(new Action(() => {
                            screenshotViewer.SetProgress((double)nCurrent / nTotal);
                        }));
                    }
                    searchResults.Sort((a, b) => - a.Distance.CompareTo(b.Distance));
                    searchResults.RemoveAll(t => searchResults.Take(searchResults.IndexOf(t)).Select(u => u.Name).Contains(t.Name));
                    var bans_picks = searchResults.Take(16).OrderBy(t => t.Location.Y).ToList();
                    var bans       = bans_picks.Take(6).OrderBy(t => t.Location.X).ToList();
                    var picks      = bans_picks.Skip(6).OrderBy(t => t.Location.X).ToList();
                    var t1picks    = picks.Take(5).OrderBy(t => t.Location.Y).ToList();
                    var t2picks    = picks.Skip(5).OrderBy(t => t.Location.Y).ToList();

                    var bgSearchResults = new List <SearchResult>();
                    foreach (var kvp in bgnameDescriptors)
                    {
                        using (var vMatches = new Emgu.CV.Util.VectorOfVectorOfDMatch()) {
                            matcher.KnnMatch(kvp.Value, des, vMatches, 2);
                            const float maxdist = 0.7f;
                            var         matches = vMatches.ToArrayOfArray().Where(m => m[0].Distance < maxdist * m[1].Distance).ToList();
                            if (matches.Any())
                            {
                                bgSearchResults.Add(new SearchResult(kvp.Key, matches, kp));
                            }
                        }
                        nCurrent++;
                        Invoke(new Action(() => {
                            screenshotViewer.SetProgress((double)nCurrent / nTotal);
                        }));
                    }
                    var bgSearchResult = bgSearchResults.OrderBy(t => - t.Distance).First();
                    Invoke(new Action(() => {
                        screenshotViewer.SetProgress(Stage.Complete);
                        screenshotViewer.SetSearchResults(bans_picks.ToArray(), bgSearchResult);
                        c_bg.Text = bgSearchResult.Name;
                        screenshotViewer.Show();
                        Focus();
                    }));
                }
        }
        private float _alpha = 0.3f; //default

        /// <summary>
        /// Executes this filter on the input image and returns the image with the WaterMark
        /// </summary>
        /// <param name="source">input image</param>
        /// <returns>transformed image</returns>
        /// <example>
        /// <code>
        /// Image transformed;
        /// ImageWatermarkFilter imageWaterMark = new ImageWatermarkFilter();
        /// imageWaterMark.Valign = ImageWatermarkFilter.VAlign.Right;
        /// imageWaterMark.Halign = ImageWatermarkFilter.HAlign.Bottom;
        /// imageWaterMark.WaterMarkImage = Image.FromFile("Images/pacman.gif");
        /// transformed = imageWaterMark.ExecuteFilter(myImg);
        /// </code>
        /// </example>
        public override Image ExecuteFilter(Image source)
        {
            _height = source.Height;
            _width  = source.Width;
            Bitmap bmWatermark = new Bitmap(source);

            bmWatermark.SetResolution(source.HorizontalResolution, source.VerticalResolution);
            //Load this Bitmap into a new Graphic Object
            Graphics grWatermark = Graphics.FromImage(bmWatermark);

            //To achieve a transulcent watermark we will apply (2) color
            //manipulations by defineing a ImageAttributes object and
            //seting (2) of its properties.
            ImageAttributes imageAttributes = new ImageAttributes();

            //The first step in manipulating the watermark image is to replace
            //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
            //to do this we will use a Colormap and use this to define a RemapTable
            ColorMap colorMap = new ColorMap();

            //My watermark was defined with a background of 100% Green this will
            //be the color we search for and replace with transparency
            colorMap.OldColor = TransparentColor;
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);

            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            //The second color manipulation is used to change the opacity of the
            //watermark.  This is done by applying a 5x5 matrix that contains the
            //coordinates for the RGBA space.  By setting the 3rd row and 3rd column
            //to 0.3f we achive a level of opacity
            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, _alpha, 0.0f },
                new float[] { 0.0f, 0.0f, 0.0f,   0.0f, 1.0f }
            };
            ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
                                           ColorAdjustType.Bitmap);

            //For this example we will place the watermark in the upper right
            //hand corner of the photograph. offset down 10 pixels and to the
            //left 10 pixles


            float xPosOfWm;// = ((rawImage.Width - _waterMarkImage.Width) - 2);
            float yPosOfWm;

            CalcDrawPosition(WaterMarkImage.Width, WaterMarkImage.Height, 0, out yPosOfWm, out xPosOfWm);

            grWatermark.DrawImage(WaterMarkImage,
                                  new Rectangle((int)xPosOfWm, (int)yPosOfWm, WaterMarkImage.Width, WaterMarkImage.Height), //Set the detination Position
                                  0,                                                                                        // x-coordinate of the portion of the source image to draw.
                                  0,                                                                                        // y-coordinate of the portion of the source image to draw.
                                  WaterMarkImage.Width,                                                                     // Watermark Width
                                  WaterMarkImage.Height,                                                                    // Watermark Height
                                  GraphicsUnit.Pixel,                                                                       // Unit of measurment
                                  imageAttributes);                                                                         //ImageAttributes Object

            //Replace the original photgraphs bitmap with the new Bitmap
            //imgPhoto = bmWatermark;
            //grWatermark.Dispose();

            //save new image to file system.
            return(bmWatermark); // bmPhoto;
        }
Example #42
0
    /// <summary>
    /// 添加图片水印
    /// </summary>
    /// <param name="sourcePicture">源图片文件名</param>
    /// <param name="waterImage">水印图片文件名</param>
    /// <param name="alpha">透明度(0.1-1.0数值越小透明度越高)</param>
    /// <param name="position">位置</param>
    /// <param name="PicturePath" >图片的路径</param>
    /// <returns>返回生成于指定文件夹下的水印文件名</returns>
    public string  DrawImage(string sourcePicture,
                             string waterImage,
                             float alpha,
                             ImagePosition position,
                             string PicturePath)
    {
        //
        // 判断参数是否有效
        //
        if (sourcePicture == string.Empty || waterImage == string.Empty || alpha == 0.0 || PicturePath == string.Empty)
        {
            return(sourcePicture);
        }

        //
        // 源图片,水印图片全路径
        //
        string sourcePictureName   = PicturePath + sourcePicture;
        string waterPictureName    = PicturePath + waterImage;
        string fileSourceExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower();
        string fileWaterExtension  = System.IO.Path.GetExtension(waterPictureName).ToLower();

        //
        // 判断文件是否存在,以及类型是否正确
        //
        if (System.IO.File.Exists(sourcePictureName) == false ||
            System.IO.File.Exists(waterPictureName) == false || (
                fileSourceExtension != ".gif" &&
                fileSourceExtension != ".jpg" &&
                fileSourceExtension != ".png") || (
                fileWaterExtension != ".gif" &&
                fileWaterExtension != ".jpg" &&
                fileWaterExtension != ".png")
            )
        {
            return(sourcePicture);
        }

        //
        // 目标图片名称及全路径
        //
        string targetImage = sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName), "") + "_1101.jpg";

        //
        // 将需要加上水印的图片装载到Image对象中
        //
        Image imgPhoto = Image.FromFile(sourcePictureName);
        //
        // 确定其长宽
        //
        int phWidth  = imgPhoto.Width;
        int phHeight = imgPhoto.Height;

        //
        // 封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。
        //
        Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);

        //
        // 设定分辨率
        //
        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

        //
        // 定义一个绘图画面用来装载位图
        //
        Graphics grPhoto = Graphics.FromImage(bmPhoto);

        //
        //同样,由于水印是图片,我们也需要定义一个Image来装载它
        //
        Image imgWatermark = new Bitmap(waterPictureName);

        //
        // 获取水印图片的高度和宽度
        //
        int wmWidth  = imgWatermark.Width;
        int wmHeight = imgWatermark.Height;

        //SmoothingMode:指定是否将平滑处理(消除锯齿)应用于直线、曲线和已填充区域的边缘。
        // 成员名称   说明
        // AntiAlias      指定消除锯齿的呈现。
        // Default        指定不消除锯齿。
        // HighQuality  指定高质量、低速度呈现。
        // HighSpeed   指定高速度、低质量呈现。
        // Invalid        指定一个无效模式。
        // None          指定不消除锯齿。
        grPhoto.SmoothingMode = SmoothingMode.AntiAlias;

        //
        // 第一次描绘,将我们的底图描绘在绘图画面上
        //
        grPhoto.DrawImage(imgPhoto,
                          new Rectangle(0, 0, phWidth, phHeight),
                          0,
                          0,
                          phWidth,
                          phHeight,
                          GraphicsUnit.Pixel);

        //
        // 与底图一样,我们需要一个位图来装载水印图片。并设定其分辨率
        //
        Bitmap bmWatermark = new Bitmap(bmPhoto);

        bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

        //
        // 继续,将水印图片装载到一个绘图画面grWatermark
        //
        Graphics grWatermark = Graphics.FromImage(bmWatermark);

        //
        //ImageAttributes 对象包含有关在呈现时如何操作位图和图元文件颜色的信息。
        //
        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);

        //
        //上面设置完颜色,下面开始设置位置
        //
        int xPosOfWm;
        int yPosOfWm;

        switch (position)
        {
        case ImagePosition.BottomMiddle:
            xPosOfWm = (phWidth - wmWidth) / 2;
            yPosOfWm = phHeight - wmHeight - 10;
            break;

        case ImagePosition.Center:
            xPosOfWm = (phWidth - wmWidth) / 2;
            yPosOfWm = (phHeight - wmHeight) / 2;
            break;

        case ImagePosition.LeftBottom:
            xPosOfWm = 10;
            yPosOfWm = phHeight - wmHeight - 10;
            break;

        case ImagePosition.LeftTop:
            xPosOfWm = 10;
            yPosOfWm = 10;
            break;

        case ImagePosition.RightTop:
            xPosOfWm = phWidth - wmWidth - 10;
            yPosOfWm = 10;
            break;

        case ImagePosition.RigthBottom:
            xPosOfWm = phWidth - wmWidth - 10;
            yPosOfWm = phHeight - wmHeight - 10;
            break;

        case ImagePosition.TopMiddle:
            xPosOfWm = (phWidth - wmWidth) / 2;
            yPosOfWm = 10;
            break;

        default:
            xPosOfWm = 10;
            yPosOfWm = phHeight - wmHeight - 10;
            break;
        }

        //
        // 第二次绘图,把水印印上去
        //
        grWatermark.DrawImage(imgWatermark,
                              new Rectangle(xPosOfWm,
                                            yPosOfWm,
                                            wmWidth,
                                            wmHeight),
                              0,
                              0,
                              wmWidth,
                              wmHeight,
                              GraphicsUnit.Pixel,
                              imageAttributes);


        imgPhoto = bmWatermark;
        grPhoto.Dispose();
        grWatermark.Dispose();

        //
        // 保存文件到服务器的文件夹里面
        //
        imgPhoto.Save(targetImage, ImageFormat.Jpeg);
        imgPhoto.Dispose();
        imgWatermark.Dispose();
        return(targetImage.Replace(PicturePath, ""));
    }
Example #43
0
        private Bitmap CreateBitmap()
        {
            Bitmap bitmap = new Bitmap(_backgroundImage.Width, _backgroundImage.Height, PixelFormat.Format32bppArgb);

            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                BidiGraphics g = new BidiGraphics(graphics, bitmap.Size);

                // draw transparent background image
                g.DrawImage(false, _backgroundImage,
                            new Rectangle(0, 0, _backgroundImage.Width, _backgroundImage.Height));

                // draw logo image
                g.DrawImage(false, _logoImage, new Rectangle(
                                (ClientSize.Width - _logoImage.Width) / 2,
                                120 - _logoImage.Height,
                                _logoImage.Width,
                                _logoImage.Height));

                // draw copyright notice
                string splashText = Res.Get(StringId.SplashScreenCopyrightNotice);
                using (Font font = new Font(Font.FontFamily, 7.5f))
                {
                    const int TEXT_PADDING_H = 36;
                    const int TEXT_PADDING_V = 26;
                    int       textWidth      = Size.Width - 2 * TEXT_PADDING_H;
                    int       textHeight     =
                        Convert.ToInt32(
                            g.MeasureText(splashText, font, new Size(textWidth, 0), TextFormatFlags.WordBreak).Height,
                            CultureInfo.InvariantCulture);

                    // GDI text can't be drawn on an alpha-blended surface. So we render a black-on-white
                    // bitmap, then use a ColorMatrix to effectively turn it into an alpha mask.

                    using (Bitmap textBitmap = new Bitmap(textWidth, textHeight, PixelFormat.Format32bppRgb))
                    {
                        using (Graphics tbG = Graphics.FromImage(textBitmap))
                        {
                            tbG.FillRectangle(Brushes.Black, 0, 0, textWidth, textHeight);
                            new BidiGraphics(tbG, textBitmap.Size).
                            DrawText(splashText, font, new Rectangle(0, 0, textWidth, textHeight), Color.White, Color.Black, TextFormatFlags.WordBreak);
                        }

                        Rectangle textRect = new Rectangle(TEXT_PADDING_H, ClientSize.Height - TEXT_PADDING_V - textHeight, textWidth, textHeight);
                        using (ImageAttributes ia = new ImageAttributes())
                        {
                            ColorMatrix cm = new ColorMatrix(new float[][]
                            {
                                new float[] { 0, 0, 0, 1f / 3f, 0 },
                                new float[] { 0, 0, 0, 1f / 3f, 0 },
                                new float[] { 0, 0, 0, 1f / 3f, 0 },
                                new float[] { 0, 0, 0, 0, 0 },
                                new float[] { 0.9372f, 0.9372f, 0.9372f, 0, 0 },
                            });
                            ia.SetColorMatrix(cm);
                            g.DrawImage(false, textBitmap, textRect, 0, 0, textWidth, textHeight, GraphicsUnit.Pixel, ia);
                        }
                    }
                }
            }
            return(bitmap);
        }
Example #44
0
        public static void GenerateImageWatermark(string originalPath, string watermarkPath, string targetPath, int position, int opacity, int quality)
        {
            float           single;
            Image           image          = null;
            Image           bitmap         = null;
            ImageAttributes imageAttribute = null;
            Graphics        graphic        = null;

            try {
                try {
                    image  = Image.FromFile(originalPath);
                    bitmap = new Bitmap(watermarkPath);
                    if ((bitmap.Height >= image.Height ? false : bitmap.Width < image.Width))
                    {
                        if ((quality < 0 ? true : quality > 100))
                        {
                            quality = 80;
                        }
                        single = ((opacity <= 0 ? true : opacity > 10) ? 0.5f : (float)((float)opacity / 10f));
                        int width  = 0;
                        int height = 0;
                        switch (position)
                        {
                        case 1: {
                            width  = (int)((float)image.Width * 0.01f);
                            height = (int)((float)image.Height * 0.01f);
                            break;
                        }

                        case 2: {
                            width  = (int)((float)image.Width * 0.5f - (float)(bitmap.Width / 2));
                            height = (int)((float)image.Height * 0.01f);
                            break;
                        }

                        case 3: {
                            width  = (int)((float)image.Width * 0.99f - (float)bitmap.Width);
                            height = (int)((float)image.Height * 0.01f);
                            break;
                        }

                        case 4: {
                            width  = (int)((float)image.Width * 0.01f);
                            height = (int)((float)image.Height * 0.5f - (float)(bitmap.Height / 2));
                            break;
                        }

                        case 5: {
                            width  = (int)((float)image.Width * 0.5f - (float)(bitmap.Width / 2));
                            height = (int)((float)image.Height * 0.5f - (float)(bitmap.Height / 2));
                            break;
                        }

                        case 6: {
                            width  = (int)((float)image.Width * 0.99f - (float)bitmap.Width);
                            height = (int)((float)image.Height * 0.5f - (float)(bitmap.Height / 2));
                            break;
                        }

                        case 7: {
                            width  = (int)((float)image.Width * 0.01f);
                            height = (int)((float)image.Height * 0.99f - (float)bitmap.Height);
                            break;
                        }

                        case 8: {
                            width  = (int)((float)image.Width * 0.5f - (float)(bitmap.Width / 2));
                            height = (int)((float)image.Height * 0.99f - (float)bitmap.Height);
                            break;
                        }

                        case 9: {
                            width  = (int)((float)image.Width * 0.99f - (float)bitmap.Width);
                            height = (int)((float)image.Height * 0.99f - (float)bitmap.Height);
                            break;
                        }
                        }
                        ColorMap colorMap = new ColorMap()
                        {
                            OldColor = Color.FromArgb(255, 0, 255, 0),
                            NewColor = Color.FromArgb(0, 0, 0, 0)
                        };
                        ColorMap[] colorMapArray = new ColorMap[] { colorMap };
                        float[][]  singleArray   = new float[5][];
                        float[]    singleArray1  = new float[] { 1f, default(float), default(float), default(float), default(float) };
                        singleArray[0] = singleArray1;
                        singleArray1   = new float[] { default(float), 1f, default(float), default(float), default(float) };
                        singleArray[1] = singleArray1;
                        singleArray1   = new float[] { default(float), default(float), 1f, default(float), default(float) };
                        singleArray[2] = singleArray1;
                        singleArray1   = new float[] { default(float), default(float), default(float), single, default(float) };
                        singleArray[3] = singleArray1;
                        singleArray1   = new float[] { default(float), default(float), default(float), default(float), 1f };
                        singleArray[4] = singleArray1;
                        ColorMatrix colorMatrix = new ColorMatrix(singleArray);
                        imageAttribute = new ImageAttributes();
                        imageAttribute.SetRemapTable(colorMapArray, ColorAdjustType.Bitmap);
                        imageAttribute.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                        graphic = Graphics.FromImage(image);
                        graphic.DrawImage(bitmap, new Rectangle(width, height, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, imageAttribute);
                        EncoderParameters  encoderParameter = new EncoderParameters();
                        EncoderParameter[] param            = encoderParameter.Param;
                        Encoder            encoder          = Encoder.Quality;
                        long[]             numArray         = new long[] { (long)quality };
                        param[0] = new EncoderParameter(encoder, numArray);
                        if (ImageHelper.GetJPEGCodec() == null)
                        {
                            image.Save(targetPath);
                        }
                        else
                        {
                            image.Save(targetPath, ImageHelper._jpegcodec, encoderParameter);
                        }
                    }
                    else
                    {
                        image.Save(targetPath);
                        return;
                    }
                }
                catch (Exception exception) {
                    throw exception;
                }
            }
            finally {
                if (graphic != null)
                {
                    graphic.Dispose();
                }
                if (imageAttribute != null)
                {
                    imageAttribute.Dispose();
                }
                if (bitmap != null)
                {
                    bitmap.Dispose();
                }
                if (image != null)
                {
                    image.Dispose();
                }
            }
        }
Example #45
0
	public static void Main(string[] args)
	{	
		Graphics.DrawImageAbort imageCallback;
		Bitmap outbmp = new Bitmap (600, 600);				
		Bitmap bmp = new Bitmap("../../Test/System.Drawing/bitmaps/almogaver32bits.bmp");
		Graphics dc = Graphics.FromImage (outbmp);        
		SolidBrush br = new SolidBrush(Color.White);
		Bitmap img = bmp.Clone (new Rectangle (0,0, 60,60) , PixelFormat.Format32bppArgb);									
		
		ImageAttributes imageAttr = new ImageAttributes();
		
		Bitmap	bmpred = new Bitmap (100,100, PixelFormat.Format32bppArgb);		
		Graphics gr = Graphics.FromImage (bmpred);		
		
		/* Sample drawing*/
		Pen cyan = new Pen(Color.Cyan, 0);
		Pen green = new Pen(Color.Green, 0);
		Pen pink = new Pen(Color.Pink, 0);			
		Pen blue = new Pen(Color.Blue, 0);			
		gr.DrawLine(cyan, 10.0F, 10.0F, 90.0F, 90.0F);
		gr.DrawLine(pink, 10.0F, 30.0F, 90.0F, 30.0F);
		gr.DrawLine(green, 10.0F, 50.0F, 90.0F, 50.0F);
		gr.DrawRectangle (blue, 10.0F, 10.0F, 80.0F, 80.0F);				
		
		/* Draw image without any imageattributes*/		
		dc.DrawImage (bmpred, 0,0);				
		dc.DrawString ("Sample drawing", new Font ("Arial", 8), br,  10, 100);				
		
		/* Remmaping colours */
		ColorMap[] clr = new ColorMap[1];	
		clr[0] = new ColorMap(); 
		clr[0].OldColor = Color.Blue;
		clr[0].NewColor = Color.Yellow;	
		
		imageAttr.SetRemapTable (clr, ColorAdjustType.Bitmap);					
		dc.DrawImage (bmpred, new Rectangle (100, 0, 100,100), 0,0, 100,100, GraphicsUnit.Pixel, imageAttr);			
		dc.DrawString ("Remapping colors", new Font ("Arial", 8), br,  110, 100);				
		
		/* Gamma correction on*/
		imageAttr = new ImageAttributes();
		imageAttr.SetGamma (2);		
		dc.DrawImage (bmpred, new Rectangle (200, 0, 100,100), 0,0, 
			100,100, GraphicsUnit.Pixel, imageAttr);
			
		dc.DrawString ("Gamma corrected", new Font ("Arial", 8), br,  210, 100);				
		
		/* WrapMode: TitleX */
		imageAttr = new ImageAttributes();	
		imageAttr.SetWrapMode (WrapMode.TileFlipX);	
		
		dc.DrawImage (bmpred, new Rectangle (0, 120, 200, 200), 0,0, 
			200, 200, GraphicsUnit.Pixel, imageAttr);					
			
		dc.DrawString ("WrapMode.TileFlipX", new Font ("Arial", 8), br,  10, 320);								
			
		/* WrapMode: TitleY */		
		imageAttr.SetWrapMode (WrapMode.TileFlipY);	
		
		dc.DrawImage (bmpred, new Rectangle (200, 120, 200, 200), 0,0, 
			200, 200, GraphicsUnit.Pixel, imageAttr);				
			
		dc.DrawString ("WrapMode.TileFlipY", new Font ("Arial", 8), br,  210, 320);											
			
		/* WrapMode: TitleXY */		
		imageAttr.SetWrapMode (WrapMode.TileFlipXY);	
		
		dc.DrawImage (bmpred, new Rectangle (400, 120, 200, 200), 0,0, 
			200, 200, GraphicsUnit.Pixel, imageAttr);				
			
		dc.DrawString ("WrapMode.TileFlipXY", new Font ("Arial", 8), br,  410, 320);														
		
		outbmp.Save("imageattributes.bmp", ImageFormat.Bmp);				
		
	}
    public static void AdjustMatrixs(Bitmap img, float[] value)
    {

        if (value.Length == 0) 

            return;


        float sb = (float)value[0] / 255F;

        float[][] brMatrix =

                  { 

                        new float[] {1,  0,  0,  0, 0},

                        new float[] {0,  1,  0,  0, 0},

                        new float[] {0,  0,  1,  0, 0},

                        new float[] {0,  0,  0,  1, 0},

                        new float[] {sb, sb, sb, 1, 1}

                  };
        float co = 1F - (float)value[1] / 255F;

        float[][] coMatrix =

                  { 

                        new float[] {co,  0,  0,  0, 0},

                        new float[] {0,  co,  0,  0, 0},

                        new float[] {0,  0,  co,  0, 0},

                        new float[] {0,  0,  0, 1, 0},

                        new float[] {0,  0,  0,  0, 1}

                  };

        float[][] colorMatrixElements=Multiply(brMatrix,coMatrix);



        ColorMatrix cm = new ColorMatrix(colorMatrixElements);

        ImageAttributes imgattr = new ImageAttributes();

        Rectangle rc = new Rectangle(0, 0, img.Width, img.Height);

        Graphics g = Graphics.FromImage(img);

        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        imgattr.SetColorMatrix(cm);

        g.DrawImage(img, rc, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgattr);



        //Clean everything up

        imgattr.Dispose();

        g.Dispose();

    }
Example #47
0
                private void DrawImage(Graphics g)
                {
                    Image image;
                    if (this.Enabled)
                    {
                        image = this.ImageEnabled;
                    }
                    else
                    {
                        if (ImageDisabled != null)
                        {
                            image = this.ImageDisabled;
                        }
                        else
                        {
                            image = this.ImageEnabled;
                        }
                    }
                    ImageAttributes imageAttr = null;
                    if (image == null)
                    {
                        return;
                    }
                    if (m_monochrom)
                    {
                        imageAttr = new ImageAttributes();
                        // transform the monochrom image
                        // white -> BackColor
                        // black -> ForeColor
                        ColorMap[] myColorMap = new ColorMap[2];
                        myColorMap[0] = new ColorMap();
                        myColorMap[0].OldColor = Color.White;
                        myColorMap[0].NewColor = Color.Transparent;
                        myColorMap[1] = new ColorMap();
                        myColorMap[1].OldColor = Color.Black;
                        myColorMap[1].NewColor = this.ForeColor;
                        imageAttr.SetRemapTable(myColorMap);
                    }
                    Rectangle rect = new Rectangle(0, 0, image.Width, image.Height);
                    if ((! Enabled) && (ImageDisabled == null))
                    {
                        using (Bitmap bitmapMono = new Bitmap(image, ClientRectangle.Size))
                        {
                            if (imageAttr != null)
                            {
                                using (Graphics gMono = Graphics.FromImage(bitmapMono))
                                {
                                    gMono.DrawImage(image, new Point[3] {new Point(0, 0), new Point(image.Width - 1, 0), new Point(0, image.Height - 1)}, rect, GraphicsUnit.Pixel, imageAttr);
                                }

                            }
                            ControlPaint.DrawImageDisabled(g, bitmapMono, 0, 0, this.BackColor);
                        }

                    }
                    else
                    {
                        // Three points provided are upper-left, upper-right and
                        // lower-left of the destination parallelogram.
                        Point[] pts = new Point[3]();
                        if (Enabled && m_mouseOver && m_mouseCapture)
                        {
                            pts[0].X = 1;
                            pts[0].Y = 1;
                        }
                        else
                        {
                            pts[0].X = 0;
                            pts[0].Y = 0;
                        }
                        pts[1].X = pts[0].X + ClientRectangle.Width;
                        pts[1].Y = pts[0].Y;
                        pts[2].X = pts[0].X;
                        pts[2].Y = pts[1].Y + ClientRectangle.Height;
                        if (imageAttr == null)
                        {
                            g.DrawImage(image, pts, rect, GraphicsUnit.Pixel);
                        }
                        else
                        {
                            g.DrawImage(image, pts, rect, GraphicsUnit.Pixel, imageAttr);
                        }
                    }
                }
Example #48
0
  private void DrawFeatures(Graphics graphics, string layerId, StringCollection ids, Color color, double opacity, string polygonMode, int penWidth, int dotSize)
  {
    if (ids.Count == 0)
    {
      return;
    }

    bool drawPolygonOutlines = polygonMode == "outline";

    // get the layer

    Configuration config = AppContext.GetConfiguration();
    Configuration.LayerRow layerRow = config.Layer.FindByLayerID(layerId);

    CommonDataFrame dataFrame = AppContext.GetDataFrame(_appState.MapTab);
    CommonLayer layer = dataFrame.Layers.FirstOrDefault(lyr => String.Compare(lyr.Name, layerRow.LayerName, true) == 0);

    // build the query string and select the features

    CommonField field = layer.FindField(layerRow.KeyField);
    string joinedIds = field.IsNumeric ? ids.Join(",") : String.Format("'{0}'", ids.Join("','"));
    string query = String.Format("{0} in ({1})", field.Name, joinedIds);

    string levelQuery = layerRow.GetLevelQuery(layer, _appState.Level);

    if (!String.IsNullOrEmpty(levelQuery))
    {
      query += " and " + levelQuery;
    }

    CommonField keyField = layer.FindField(layerRow.KeyField);
    DataTable table = layer.GetFeatureTable(String.Format("{0},{1}", layer.GeometryField.Name, keyField.Name), query);

    if (table == null || table.Rows.Count == 0)
    {
      return;
    }

    OgcGeometryType geometryType = ((IGeometry)table.Rows[0][layer.GeometryField.Name]).OgcGeometryType;

    // prepare the temporary image for drawing transparent highlight graphics

    int width = Convert.ToInt32(graphics.VisibleClipBounds.Width);
    int height = Convert.ToInt32(graphics.VisibleClipBounds.Height);

    Bitmap bitMap = new Bitmap(width, height);
    Graphics imageGraphics = Graphics.FromImage(bitMap);
    imageGraphics.Clear(Color.Transparent);

    // prepare the drawing objects

    Brush brush = new SolidBrush(color);
    Pen pen = new Pen(color, Convert.ToSingle(penWidth * _resolution));
    pen.EndCap = System.Drawing.Drawing2D.LineCap.Square;
    pen.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;
    Pen bufferPen = new Pen(color, Convert.ToSingle(5 * _resolution));
    bufferPen.EndCap = System.Drawing.Drawing2D.LineCap.Round;
    bufferPen.LineJoin = System.Drawing.Drawing2D.LineJoin.Round;

    float dot = Convert.ToSingle(dotSize * _resolution);

    // draw each shape in the table

    foreach (DataRow row in table.Rows)
    {
      switch (geometryType)
      {
        case OgcGeometryType.Point:
          IPoint point = (IPoint)row[layer.GeometryField.Name];
          DrawPoint(imageGraphics, point, brush, dot);
          break;

        case OgcGeometryType.MultiPoint:
          IMultiPoint multiPoint = (IMultiPoint)row[layer.GeometryField.Name];
          DrawPoint(imageGraphics, (IPoint)multiPoint[0], brush, dot);
          break;

        case OgcGeometryType.MultiLineString:
          DrawMultiLineString(imageGraphics, (IMultiLineString)row[layer.GeometryField.Name], pen);
          break;

        case OgcGeometryType.MultiPolygon:
          if (drawPolygonOutlines)
          {
            DrawMultiPolygon(imageGraphics, (IMultiPolygon)row[layer.GeometryField.Name], null, null, pen);
          }
          else
          {
            DrawMultiPolygon(imageGraphics, (IMultiPolygon)row[layer.GeometryField.Name], brush, bufferPen);
          }

          break;
      }
    }

    // draw the temporary image containing the highlight graphics on the output image at
    // the specified opacity

    float[][] matrixItems ={
      new float[] {1, 0, 0, 0, 0},
      new float[] {0, 1, 0, 0, 0},
      new float[] {0, 0, 1, 0, 0},
      new float[] {0, 0, 0, Convert.ToSingle(opacity), 0}, 
      new float[] {0, 0, 0, 0, 1}};

    ColorMatrix colorMatrix = new ColorMatrix(matrixItems);

    ImageAttributes imageAtts = new ImageAttributes();
    imageAtts.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

    Rectangle drawRect = new Rectangle(0, 0, width, height);
    graphics.DrawImage(bitMap, drawRect, 0, 0, width, height, GraphicsUnit.Pixel, imageAtts);
  }
        /// <summary>
        /// Load and display an image moniker in a PictureBox
        /// </summary>
        private void LoadMoniker(object sender, EventArgs e)
        {
            IVsImageService2 imageService = (IVsImageService2)OptionsPagePackageCS.GetGlobalService(typeof(SVsImageService));

            ImageAttributes attributes = new ImageAttributes
            {
                StructSize = Marshal.SizeOf(typeof(ImageAttributes)),
                ImageType = (uint)_UIImageType.IT_Bitmap,
                Format = (uint)_UIDataFormat.DF_WinForms,
                LogicalWidth = 32,
                LogicalHeight = 32,
                // Desired RGBA color, don't set IAF_Background below unless you also use this
                Background = 0xFFFFFFFF,
                // (uint)(_ImageAttributesFlags.IAF_RequiredFlags | _ImageAttributesFlags.IAF_Background)
                Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags,
            };

            IVsUIObject uIObj = imageService.GetImage(KnownMonikers.Search, attributes);

            bitmapPictureBox.Image = (Bitmap)GelUtilities.GetObjectData(uIObj);
        }
Example #50
0
        public static Image CreateBanner(int nWidth, int nHeight, BannerStyle bs,
                                         Image imgIcon, string strTitle, string strLine, bool bNoCache)
        {
            // imgIcon may be null
            if (strTitle == null)
            {
                Debug.Assert(false); strTitle = string.Empty;
            }
            if (strLine == null)
            {
                Debug.Assert(false); strLine = string.Empty;
            }

            Debug.Assert((nHeight == StdHeight) || DpiUtil.ScalingRequired ||
                         UISystemFonts.OverrideUIFont);
            if (MonoWorkarounds.IsRequired(12525) && (nHeight > 0))
            {
                --nHeight;
            }

            if (bs == BannerStyle.Default)
            {
                bs = Program.Config.UI.BannerStyle;
            }
            if (bs == BannerStyle.Default)
            {
                Debug.Assert(false);
                bs = BannerStyle.WinVistaBlack;
            }

            NumberFormatInfo nfi       = NumberFormatInfo.InvariantInfo;
            ulong            uIconHash = ((imgIcon != null) ? GfxUtil.HashImage64(imgIcon) : 0);
            string           strID     = nWidth.ToString(nfi) + "x" + nHeight.ToString(nfi) +
                                         ":" + ((uint)bs).ToString(nfi) + ":" + strTitle + ":/:" + strLine +
                                         ":" + uIconHash.ToString(nfi);

            Image img = null;

            if (!bNoCache && g_dCache.TryGetValue(strID, out img))
            {
                return(img);
            }

            if (g_pCustomGen != null)
            {
                img = g_pCustomGen(new BfBannerInfo(nWidth, nHeight, bs, imgIcon,
                                                    strTitle, strLine));
            }

            const float fHorz = 0.90f;
            const float fVert = 90.0f;

            if (img == null)
            {
                img = new Bitmap(nWidth, nHeight, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(img);

                Color clrStart = Color.White;
                Color clrEnd   = Color.LightBlue;
                float fAngle   = fHorz;

                if (bs == BannerStyle.BlueCarbon)
                {
                    fAngle = fVert;

                    g.Clear(Color.Black);                     // Area from 3/8 to 1/2 height

                    clrStart = Color.LightGray;
                    clrEnd   = Color.Black;

                    Rectangle rect = new Rectangle(0, 0, nWidth, (nHeight * 3) / 8);
                    using (LinearGradientBrush brCarbonT = new LinearGradientBrush(
                               rect, clrStart, clrEnd, fAngle, true))
                    {
                        g.FillRectangle(brCarbonT, rect);
                    }

                    // clrStart = Color.FromArgb(0, 0, 32);
                    clrStart = Color.FromArgb(0, 0, 28);
                    // clrEnd = Color.FromArgb(192, 192, 255);
                    clrEnd = Color.FromArgb(155, 155, 214);

                    // rect = new Rectangle(0, nHeight / 2, nWidth, (nHeight * 5) / 8);
                    int hMid = nHeight / 2;
                    rect = new Rectangle(0, hMid - 1, nWidth, nHeight - hMid);
                    using (LinearGradientBrush brCarbonB = new LinearGradientBrush(
                               rect, clrStart, clrEnd, fAngle, true))
                    {
                        g.FillRectangle(brCarbonB, rect);
                    }

                    // Workaround gradient drawing bug (e.g. occuring on
                    // Windows 8.1 with 150% DPI)
                    using (Pen pen = new Pen(Color.Black))
                    {
                        g.DrawLine(pen, 0, hMid - 1, nWidth - 1, hMid - 1);
                    }
                }
                else
                {
                    if (bs == BannerStyle.WinXPLogin)
                    {
                        clrStart = Color.FromArgb(200, 208, 248);
                        clrEnd   = Color.FromArgb(40, 64, 216);
                    }
                    else if (bs == BannerStyle.WinVistaBlack)
                    {
                        clrStart = Color.FromArgb(151, 154, 173);
                        clrEnd   = Color.FromArgb(27, 27, 37);

                        fAngle = fVert;
                    }
                    else if (bs == BannerStyle.KeePassWin32)
                    {
                        clrStart = Color.FromArgb(235, 235, 255);
                        clrEnd   = Color.FromArgb(192, 192, 255);
                    }

                    Rectangle rect = new Rectangle(0, 0, nWidth, nHeight);
                    using (LinearGradientBrush brBack = new LinearGradientBrush(
                               rect, clrStart, clrEnd, fAngle, true))
                    {
                        g.FillRectangle(brBack, rect);
                    }
                }

                bool bRtl = Program.Translation.Properties.RightToLeft;
                // Matrix mxTrfOrg = g.Transform;
                // if(bRtl)
                // {
                //	g.TranslateTransform(nWidth, 0.0f);
                //	g.ScaleTransform(-1.0f, 1.0f);
                // }

                int xIcon       = DpiScaleInt(10, nHeight);
                int wIconScaled = StdIconDim;
                int hIconScaled = StdIconDim;
                if (imgIcon != null)
                {
                    float fIconRel = (float)imgIcon.Width / (float)imgIcon.Height;
                    wIconScaled = (int)Math.Round(DpiScaleFloat(fIconRel *
                                                                (float)StdIconDim, nHeight));
                    hIconScaled = DpiScaleInt(StdIconDim, nHeight);

                    int xIconR = (bRtl ? (nWidth - xIcon - wIconScaled) : xIcon);
                    int yIconR = (nHeight - hIconScaled) / 2;
                    if (hIconScaled == imgIcon.Height)
                    {
                        g.DrawImageUnscaled(imgIcon, xIconR, yIconR);
                    }
                    else
                    {
                        g.DrawImage(imgIcon, xIconR, yIconR, wIconScaled, hIconScaled);
                    }

                    ColorMatrix cm = new ColorMatrix();
                    cm.Matrix33 = 0.1f;
                    ImageAttributes ia = new ImageAttributes();
                    ia.SetColorMatrix(cm);

                    int       w = wIconScaled * 3, h = hIconScaled * 3;
                    int       x        = (bRtl ? xIcon : (nWidth - w - xIcon));
                    int       y        = (nHeight - h) / 2;
                    Rectangle rectDest = new Rectangle(x, y, w, h);
                    g.DrawImage(imgIcon, rectDest, 0, 0, imgIcon.Width, imgIcon.Height,
                                GraphicsUnit.Pixel, ia);
                }

                if ((bs == BannerStyle.WinXPLogin) || (bs == BannerStyle.WinVistaBlack) ||
                    (bs == BannerStyle.BlueCarbon))
                {
                    int sh = DpiUtil.ScaleIntY(20) / 10;                     // Force floor

                    Rectangle rect = new Rectangle(0, nHeight - sh, 0, sh);

                    rect.Width = nWidth / 2 + 1;
                    rect.X     = nWidth / 2;
                    clrStart   = Color.FromArgb(248, 136, 24);
                    clrEnd     = Color.White;
                    using (LinearGradientBrush brushOrangeWhite = new LinearGradientBrush(
                               rect, clrStart, clrEnd, fHorz, true))
                    {
                        g.FillRectangle(brushOrangeWhite, rect);
                    }

                    rect.Width = nWidth / 2 + 1;
                    rect.X     = 0;
                    clrStart   = Color.White;
                    clrEnd     = Color.FromArgb(248, 136, 24);
                    using (LinearGradientBrush brushWhiteOrange = new LinearGradientBrush(
                               rect, clrStart, clrEnd, fHorz, true))
                    {
                        g.FillRectangle(brushWhiteOrange, rect);
                    }
                }
                else if (bs == BannerStyle.KeePassWin32)
                {
                    int sh = DpiUtil.ScaleIntY(10) / 10;                     // Force floor

                    // Black separator line
                    using (Pen penBlack = new Pen(Color.Black))
                    {
                        for (int i = 0; i < sh; ++i)
                        {
                            g.DrawLine(penBlack, 0, nHeight - i - 1,
                                       nWidth - 1, nHeight - i - 1);
                        }
                    }
                }

                // if(bRtl) g.Transform = mxTrfOrg;

                // Brush brush;
                Color clrText;
                if (bs == BannerStyle.KeePassWin32)
                {
                    // brush = Brushes.Black;
                    clrText = Color.Black;
                }
                else
                {
                    // brush = Brushes.White;
                    clrText = Color.White;
                }

                // float fx = 2 * xIcon, fy = 9.0f;
                int tx = 2 * xIcon, ty = DpiScaleInt(9, nHeight);
                if (imgIcon != null)
                {
                    tx += wIconScaled;                                 // fx
                }
                // TextFormatFlags tff = (TextFormatFlags.PreserveGraphicsClipping |
                //	TextFormatFlags.NoPrefix);
                // if(bRtl) tff |= TextFormatFlags.RightToLeft;

                float fFontSize = DpiScaleFloat((12.0f * 96.0f) / g.DpiY, nHeight);
                using (Font font = FontUtil.CreateFont(FontFamily.GenericSansSerif,
                                                       fFontSize, FontStyle.Bold))
                {
                    int txT = (!bRtl ? tx : (nWidth - tx));
                    // - TextRenderer.MeasureText(g, strTitle, font).Width));
                    // g.DrawString(strTitle, font, brush, fx, fy);
                    BannerFactory.DrawText(g, strTitle, txT, ty, font,
                                           clrText, bRtl, nWidth);
                }

                tx += xIcon;                 // fx
                ty += xIcon * 2 + 2;         // fy

                float fFontSizeSm = DpiScaleFloat((9.0f * 96.0f) / g.DpiY, nHeight);
                using (Font fontSmall = FontUtil.CreateFont(FontFamily.GenericSansSerif,
                                                            fFontSizeSm, FontStyle.Regular))
                {
                    int txL = (!bRtl ? tx : (nWidth - tx));
                    // - TextRenderer.MeasureText(g, strLine, fontSmall).Width));
                    // g.DrawString(strLine, fontSmall, brush, fx, fy);
                    BannerFactory.DrawText(g, strLine, txL, ty, fontSmall,
                                           clrText, bRtl, nWidth);
                }

                g.Dispose();
            }

            if (!bNoCache)
            {
                if (g_dCache.Count >= MaxCachedImages)
                {
                    List <string> lK = new List <string>(g_dCache.Keys);
                    g_dCache.Remove(lK[Program.GlobalRandom.Next(lK.Count)]);
                }

                g_dCache[strID] = img;
            }

            return(img);
        }
    public static void AdjustContrastMatrix(Bitmap img, float value)
    {

        if (value == 0) // No change, so just return

            return;



        float co = 1F-(float)value / 255F;

        float[][] colorMatrixElements =

                  { 

                        new float[] {co,  0,  0,  0, 0},

                        new float[] {0,  co,  0,  0, 0},

                        new float[] {0,  0,  co,  0, 0},

                        new float[] {0,  0,  0, 1, 0},

                        new float[] {0,  0,  0,  0, 1}

                  };



        ColorMatrix cm = new ColorMatrix(colorMatrixElements);

        ImageAttributes imgattr = new ImageAttributes();

        Rectangle rc = new Rectangle(0, 0, img.Width, img.Height);

        Graphics g = Graphics.FromImage(img);

        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        imgattr.SetColorMatrix(cm);

        g.DrawImage(img, rc, 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, imgattr);

        imgattr.Dispose();

        g.Dispose();

    }
Example #52
0
        public override void SetImage(Image image, Size sz)
        {
            if (image == null)
            {
                noback = true;
                return;
            }

            var width  = sz.Width;
            var height = sz.Height;

            var destRect  = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height, PixelFormat.Format16bppRgb555);

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

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode    = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            var imgf = Path.Combine(WorkingDir, "sharpboot.bmp");

            destImage.Save(imgf, ImageFormat.Bmp);

            var convertdir = Path.Combine(WorkingDir, "imagemagick");

            Directory.CreateDirectory(convertdir);
            File.WriteAllBytes(Path.Combine(convertdir, "convert.7z"), Resources.imagemagick);

            var ext = new SevenZipExtractor();

            ext.Extract(Path.Combine(convertdir, "convert.7z"), convertdir);


            var p = new Process
            {
                StartInfo =
                {
                    UseShellExecute  = false,
                    FileName         = Path.Combine(convertdir, "convert.exe"),
                    CreateNoWindow   = true,
                    WorkingDirectory = convertdir
                }
            };

            p.StartInfo.Arguments += " ../sharpboot.bmp ../sharpboot.xpm.lzma";
            Thread.Sleep(300);
            var begin = DateTime.Now;

            while (!File.Exists(p.StartInfo.FileName))
            {
                if ((DateTime.Now - begin).TotalSeconds > 15)
                {
                    break;
                }
            }
            begin = DateTime.Now;
            p.Start();
            while (!File.Exists(Path.Combine(WorkingDir, "sharpboot.xpm.lzma")))
            {
                if (p.HasExited)
                {
                    p.Start();
                    continue;
                }
                if ((DateTime.Now - begin).TotalSeconds > 15)
                {
                    break;
                }
            }
            Thread.Sleep(1000);
            File.Delete(imgf);
            ext.Close();
            while (Directory.Exists(convertdir))
            {
                try
                {
                    Directory.Delete(convertdir, true);
                }
                catch
                {
                }
            }
        }
Example #53
0
    public static void Main(string[] args)
    {
        if (args.Length != 2) usage();

        // Using early initialization of System.Console
        Console.WriteLine("Adjusting the image: " + args[0]);

        try
        {
            float contrastRatio = float.Parse(args[1]);
            /* -------------------------------------------------------------------- */
            /*      Register driver(s).                                             */
            /* -------------------------------------------------------------------- */
            Gdal.AllRegister();

            /* -------------------------------------------------------------------- */
            /*      Open dataset.                                                   */
            /* -------------------------------------------------------------------- */
            Dataset ds = Gdal.Open(args[0], Access.GA_Update);

            if (ds == null)
            {
                Console.WriteLine("Can't open " + args[0]);
                System.Environment.Exit(-1);
            }

            Bitmap bmp = CreateCompatibleBitmap(ds, ds.RasterXSize, ds.RasterYSize);
            LoadBitmapDirect(ds, bmp, 0, 0, ds.RasterXSize, ds.RasterYSize, ds.RasterXSize, ds.RasterYSize, 0);
            Bitmap newBitmap = (Bitmap)bmp.Clone();

            //create the ColorMatrix
            float[][] colormatrix = new float[][]
              {
                 new float[] {contrastRatio, 0, 0, 0, 0},
                 new float[] {0, contrastRatio, 0, 0, 0},
                 new float[] {0, 0, contrastRatio, 0, 0},
                 new float[] {0, 0, 0, 1, 0},
                 new float[] {0, 0, 0, 0, 1}
              };
            ColorMatrix colorMatrix = new ColorMatrix(colormatrix);

            //create the image attributes
            ImageAttributes attributes = new ImageAttributes();

            //set the color matrix attribute
            attributes.SetColorMatrix(colorMatrix);

            //get a graphics object from the new image
            Graphics g = Graphics.FromImage(newBitmap);
            //draw the original image on the new image
            g.DrawImage(bmp,
               new Rectangle(0, 0, bmp.Width, bmp.Height),
               0, 0, bmp.Width, bmp.Height,
               GraphicsUnit.Pixel, attributes);

            SaveBitmapDirect(ds, newBitmap, 0, 0, ds.RasterXSize, ds.RasterYSize, ds.RasterXSize, ds.RasterYSize);

            ds.FlushCache();

        }
        catch (Exception e)
        {
            Console.WriteLine("Application error: " + e.Message);
        }
    }
Example #54
0
 /// <summary>
 ///     Initializes a new <see cref="T:Common.Drawing.TextureBrush" /> object that uses the specified image, bounding
 ///     rectangle, and image attributes.
 /// </summary>
 /// <param name="image">
 ///     The <see cref="T:Common.Drawing.Image" /> object with which this
 ///     <see cref="T:Common.Drawing.TextureBrush" /> object fills interiors.
 /// </param>
 /// <param name="dstRect">
 ///     A <see cref="T:Common.Drawing.Rectangle" /> structure that represents the bounding rectangle for
 ///     this <see cref="T:Common.Drawing.TextureBrush" /> object.
 /// </param>
 /// <param name="imageAttr">
 ///     An <see cref="T:Common.Drawing.Imaging.ImageAttributes" /> object that contains additional
 ///     information about the image used by this <see cref="T:Common.Drawing.TextureBrush" /> object.
 /// </param>
 public TextureBrush(Image image, Rectangle dstRect, ImageAttributes imageAttr)
 {
     WrappedTextureBrush = new System.Drawing.TextureBrush(image, dstRect, imageAttr);
 }
Example #55
0
        private static ImageSource GetImage(IVsImageService2 imageService, ImageMoniker imageMoniker) {
            var imageAttributes = new ImageAttributes {
                ImageType = (uint)_UIImageType.IT_Bitmap,
                Flags = (uint)_ImageAttributesFlags.IAF_RequiredFlags,
                Format = (uint)_UIDataFormat.DF_WPF,
                LogicalHeight = 16,
                LogicalWidth = 16,
                StructSize = Marshal.SizeOf(typeof(ImageAttributes))
            };

            IVsUIObject uiObject = imageService.GetImage(imageMoniker, imageAttributes);

            object data;
            if (uiObject.get_Data(out data) != VSConstants.S_OK) {
                return null;
            }

            var imageSource = data as ImageSource;
            imageSource?.Freeze();
            return imageSource;
        }
        public override void OnDraw(Graphics g)
        {
            bool bInDesign = false;

            if (this.Page != null)
            {
                bInDesign = this.Page.InDesignMode;
            }
            if (bInDesign)
            {
                base.OnDraw(g);
                int nRows   = this.Rows;
                int nCol    = this.Columns;
                int nWidth  = this.Width;
                int nHeight = this.Height;
                if (nRows <= 0)
                {
                    nRows = 1;
                }
                if (nCol <= 0)
                {
                    nCol = 1;
                }
                if (nRows == 1 && nCol == 1)
                {
                    return;
                }
                int nGapX = this.GapX;
                int nGapY = this.GapY;
                if (nGapX < 0)
                {
                    nGapX = 0;
                }
                if (nGapY < 0)
                {
                    nGapY = 0;
                }
                bool bGetBmp = (_bmp == null);
                if (!bGetBmp)
                {
                    if (this.Page != null && !this.Page.ShowingTextInput)
                    {
                        if (this.Page.Left >= 0 && this.Page.Top >= 0)
                        {
                            if (this.Page.AutoScrollPosition.X == 0 && this.Page.AutoScrollPosition.Y == 0)
                            {
                                bGetBmp = true;
                            }
                        }
                    }
                }
                if (bGetBmp)
                {
                    _bmp = WinUtil.CaptureScreenImage(Page.Handle, this.Left, this.Top, this.Width, this.Height, Page.FormBorderStyle != FormBorderStyle.None);
                }
                ImageAttributes ia = null;
                if (_linePen == null)
                {
                    _linePen = new Pen(new SolidBrush(Color.LightGray));
                }
                ColorMatrix cm = new ColorMatrix();
                ia          = new ImageAttributes();
                cm.Matrix33 = 0.5f;
                ia.SetColorMatrix(cm);
                int w = this.Width * nCol;
                int h = this.Height * nRows;
                for (int r = 0, dh = this.Top; r <= nRows; r++, dh += this.Height)
                {
                    g.DrawLine(_linePen, this.Left, dh, this.Left + w, dh);
                }
                for (int c = 0, dw = this.Left; c <= nCol; c++, dw += this.Width)
                {
                    g.DrawLine(_linePen, dw, this.Top, dw, this.Top + h);
                }
                if (_bmp != null)
                {
                    int incH = this.Height + nGapY;
                    int incW = this.Width + nGapX;
                    for (int r = 0, dh = this.Top; r < nRows; r++, dh += incH)
                    {
                        for (int c = 0, dw = this.Left; c < nCol; c++, dw += incW)
                        {
                            if (r != 0 || c != 0)
                            {
                                Rectangle rc = new Rectangle(dw, dh, _bmp.Width, _bmp.Height);
                                if (bInDesign)
                                {
                                    g.DrawImage(_bmp, rc, 0, 0, _bmp.Width, _bmp.Height, GraphicsUnit.Pixel, ia);
                                }
                                else
                                {
                                    g.DrawImage(_bmp, rc, 0, 0, _bmp.Width, _bmp.Height, GraphicsUnit.Pixel);
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (_drawItems != null)
                {
                    for (int r = 0; r < _drawItems.Length; r++)
                    {
                        for (int c = 0; c < _drawItems[r].Length; c++)
                        {
                            _drawItems[r][c].OnDraw(g);
                        }
                    }
                }
            }
        }
Example #57
0
                public static void ImageWithAlpha(Graphics aGraph, Image aImage, Rectangle aTarget, int aAlpha)
                {
                    double lA = aAlpha / 100.0f > 1 ? 1 : aAlpha / 100.0f;
                    float[][] lMItems ={
                                                       new float[] {1, 0, 0, 0, 0},
                                                       new float[] {0, 1, 0, 0, 0},
                                                       new float[] {0, 0, 1, 0, 0},
                                                       new float[] {0, 0, 0, aAlpha / 100.0f, 0},
                                                       new float[] {0, 0, 0, 0, 1}};
                    ColorMatrix lCMatrix = new ColorMatrix(lMItems);

                    ImageAttributes lImgAttr = new ImageAttributes();
                    lImgAttr.SetColorMatrix(
                                   lCMatrix,
                                   ColorMatrixFlag.Default,
                                   ColorAdjustType.Bitmap);

                    aGraph.DrawImage(
                            aImage,
                            aTarget,
                            0, 0,
                            aImage.Width, aImage.Height,
                            GraphicsUnit.Pixel,
                            lImgAttr
                        );
                }
        public void ResizeImage(
            string sourceFilePath,
            string targetDirectoryPath,
            string newFileName,
            string mimeType,
            int maxWidth,
            int maxHeight,
            bool allowEnlargement = false,
            long quality          = 90,
            Color backgroundColor = default(Color)
            )
        {
            if (string.IsNullOrEmpty(sourceFilePath))
            {
                throw new ArgumentException("imageFilePath must be provided");
            }

            if (string.IsNullOrEmpty(targetDirectoryPath))
            {
                throw new ArgumentException("targetDirectoryPath must be provided");
            }

            if (string.IsNullOrEmpty(newFileName))
            {
                throw new ArgumentException("newFileName must be provided");
            }

            if (!File.Exists(sourceFilePath))
            {
                log.LogError("imageFilePath does not exist " + sourceFilePath);
                return;
            }

            if (!Directory.Exists(targetDirectoryPath))
            {
                log.LogError("targetDirectoryPath does not exist " + targetDirectoryPath);
                return;
            }

            double scaleFactor        = 0;
            bool   imageNeedsResizing = true;
            var    targetFilePath     = Path.Combine(targetDirectoryPath, newFileName);

            try
            {
                using (Stream tmpFileStream = File.OpenRead(sourceFilePath))
                {
                    using (Image fullsizeImage = Image.FromStream(tmpFileStream))
                    {
                        scaleFactor = GetScaleFactor(fullsizeImage.Width, fullsizeImage.Height, maxWidth, maxHeight);

                        if (!allowEnlargement)
                        {
                            // don't need to resize since image is smaller than max
                            if (scaleFactor > 1)
                            {
                                imageNeedsResizing = false;
                            }
                            if (scaleFactor == 0)
                            {
                                imageNeedsResizing = false;
                            }
                        }

                        if (imageNeedsResizing)
                        {
                            int newWidth  = (int)(fullsizeImage.Width * scaleFactor);
                            int newHeight = (int)(fullsizeImage.Height * scaleFactor);

                            var codecInfo = GetEncoderInfo(mimeType);

                            using (Bitmap resizedBitmap = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb))
                            {
                                using (Graphics graphics = Graphics.FromImage(resizedBitmap))
                                {
                                    using (var attributes = new ImageAttributes())
                                    {
                                        attributes.SetWrapMode(WrapMode.TileFlipXY);
                                        graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                                        graphics.CompositingQuality = CompositingQuality.HighSpeed;
                                        graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                                        graphics.CompositingMode    = CompositingMode.SourceCopy;
                                        graphics.DrawImage(
                                            fullsizeImage,
                                            Rectangle.FromLTRB(0, 0, newWidth, newHeight),
                                            0, 0, fullsizeImage.Width, fullsizeImage.Height, GraphicsUnit.Pixel, attributes);
                                        // Save the results
                                        using (var output = File.Open(targetFilePath, FileMode.Create))
                                        {
                                            using (EncoderParameters encoderParams = new EncoderParameters(1))
                                            {
                                                encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality);
                                                resizedBitmap.Save(output, codecInfo, encoderParams);
                                            }
                                        }
                                    } //end attributes
                                }     //end graphics
                            }         //end using resized bitmap
                        }             //if (imageNeedsResizing)
                    }                 //end using bitmap
                }                     //end using stream
            }
            catch (OutOfMemoryException ex)
            {
                log.LogError(MediaLoggingEvents.RESIZE_OPERATION, ex, ex.Message);
                return;
            }
            catch (ArgumentException ex)
            {
                log.LogError(MediaLoggingEvents.RESIZE_OPERATION, ex, ex.Message);
                return;
            }
        }
Example #59
0
        private void Grayscale()
        {
            RenderTargetBitmap rtb = new RenderTargetBitmap((int)_canvas.RenderSize.Width,
                                                            (int)_canvas.RenderSize.Height, 96d, 96d, PixelFormats.Default);

            DrawingVisual drawingVisual = new DrawingVisual();

            using (DrawingContext drawingContext = drawingVisual.RenderOpen())
                drawingContext.DrawRectangle(_canvas.Background, null,
                                             new Rect(0, 0, _canvas.ActualWidth, _canvas.ActualHeight));

            rtb.Render(drawingVisual);
            foreach (object paintSurfaceChild in _canvas.Children)
            {
                rtb.Render((Visual)paintSurfaceChild);
            }

            Bitmap canvasBitmap;

            using (MemoryStream outStream = new MemoryStream())
            {
                BitmapEncoder enc = new BmpBitmapEncoder();
                enc.Frames.Add(BitmapFrame.Create(rtb));
                enc.Save(outStream);
                canvasBitmap = new Bitmap(outStream);
            }

            Bitmap newBitmap = new Bitmap(canvasBitmap.Width, canvasBitmap.Height);

            Graphics g = Graphics.FromImage(newBitmap);

            //create the grayscale ColorMatrix
            ColorMatrix colorMatrix = new ColorMatrix(
                new float[][]
            {
                new float[] { .3f, .3f, .3f, 0, 0 },
                new float[] { .59f, .59f, .59f, 0, 0 },
                new float[] { .11f, .11f, .11f, 0, 0 },
                new float[] { 0, 0, 0, 1, 0 },
                new float[] { 0, 0, 0, 0, 1 }
            });

            //create some image attributes
            ImageAttributes attributes = new ImageAttributes();

            //set the color matrix attribute
            attributes.SetColorMatrix(colorMatrix);

            //draw the original image on the new image
            //using the grayscale color matrix
            g.DrawImage(canvasBitmap, new Rectangle(0, 0, canvasBitmap.Width, canvasBitmap.Height),
                        0, 0, canvasBitmap.Width, canvasBitmap.Height, GraphicsUnit.Pixel, attributes);

            //dispose the Graphics object
            g.Dispose();

            _canvas.Background = new ImageBrush(Imaging.CreateBitmapSourceFromHBitmap(newBitmap.GetHbitmap(),
                                                                                      IntPtr.Zero, Int32Rect.Empty,
                                                                                      BitmapSizeOptions.FromEmptyOptions()));
            _canvas.Children.Clear();
        }
Example #60
0
    /// <summary>

    ///   加水印图片

    /// </summary>

    /// <param name="picture">imge 对象</param>

    /// <param name="iTheImage">Image对象(以此图片为水印)</param>

    /// <param name="_watermarkPosition">水印位置</param>

    /// <param name="_width">被加水印图片的宽</param>

    /// <param name="_height">被加水印图片的高</param>

    private void addWatermarkImage(Graphics picture, Image iTheImage,

        string _watermarkPosition, int _width, int _height)
    {

        Image watermark = new Bitmap(iTheImage);

        var imageAttributes = new ImageAttributes();

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

        var colorMatrix = new ColorMatrix(colorMatrixElements);

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

        var xpos = 0;

        var ypos = 0;

        var WatermarkWidth = 0;

        var WatermarkHeight = 0;

        var bl = 1d;

        //计算水印图片的比率

        //取背景的1/4宽度来比较

        if ((_width > watermark.Width * 4) && (_height > watermark.Height * 4))
        {

            bl = 1;

        }

        else if ((_width > watermark.Width * 4) && (_height < watermark.Height * 4))
        {

            bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);



        }

        else if ((_width < watermark.Width * 4) && (_height > watermark.Height * 4))
        {

            bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);

        }

        else
        {

            if ((_width * watermark.Height) > (_height * watermark.Width))
            {

                bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);



            }

            else
            {

                bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);



            }



        }

        WatermarkWidth = Convert.ToInt32(watermark.Width * bl);

        WatermarkHeight = Convert.ToInt32(watermark.Height * bl);

        switch (_watermarkPosition)
        {

            case "WM_TOP_LEFT":

                xpos = 10;

                ypos = 10;

                break;

            case "WM_TOP_RIGHT":

                xpos = _width - WatermarkWidth - 10;

                ypos = 10;

                break;

            case "WM_BOTTOM_RIGHT":

                xpos = _width - WatermarkWidth - 10;

                ypos = _height - WatermarkHeight - 10;

                break;

            case "WM_BOTTOM_LEFT":

                xpos = 10;

                ypos = _height - WatermarkHeight - 10;

                break;

        }

        picture.DrawImage(

            watermark,

            new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight),

            0,

            0,

            watermark.Width,

            watermark.Height,

            GraphicsUnit.Pixel,

            imageAttributes);

        watermark.Dispose();

        imageAttributes.Dispose();

    }