//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); }
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); }
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); }
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 FormDisplay(Root root) { Root = root; ColorMatrix cm = new ColorMatrix(); cm.Matrix00 = 1f; cm.Matrix11 = 1f; cm.Matrix22 = 1f; cm.Matrix33 = Root.ToolbarBGColor[0] / 255f; iaToolBarTransparency.SetColorMatrix(cm); InitializeComponent(); this.Left = SystemInformation.VirtualScreen.Left; this.Top = SystemInformation.VirtualScreen.Top; //int targetbottom = 0; //foreach (Screen screen in Screen.AllScreens) //{ // if (screen.WorkingArea.Bottom > targetbottom) // targetbottom = screen.WorkingArea.Bottom; //} //int virwidth = SystemInformation.VirtualScreen.Width; //this.Width = virwidth; //this.Height = targetbottom - this.Top; this.Width = SystemInformation.VirtualScreen.Width; this.Height = SystemInformation.VirtualScreen.Height - 2; Bitmap InitCanvus = new Bitmap(this.Width, this.Height); Bitmap Init2Canvus = new Bitmap(this.Width, this.Height); Canvus = InitCanvus.GetHbitmap(Color.FromArgb(0)); OneStrokeCanvus = InitCanvus.GetHbitmap(Color.FromArgb(0)); OutCanvus = Init2Canvus.GetHbitmap(Color.FromArgb(0)); IntPtr screenDc = GetDC(IntPtr.Zero); canvusDc = CreateCompatibleDC(screenDc); SelectObject(canvusDc, Canvus); onestrokeDc = CreateCompatibleDC(screenDc); SelectObject(onestrokeDc, OneStrokeCanvus); OutcanvusDc = CreateCompatibleDC(screenDc); SelectObject(OutcanvusDc, OutCanvus); gCanvus = Graphics.FromHdc(canvusDc); gCanvus.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; // source Over else we get some issues displaying text gCanvus.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; gOneStrokeCanvus = Graphics.FromHdc(onestrokeDc); gOneStrokeCanvus.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; gOutCanvus = Graphics.FromHdc(OutcanvusDc); gOutCanvus.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; if (Root.AutoScroll) { hScreenBitmap = InitCanvus.GetHbitmap(Color.FromArgb(0)); memscreenDc = CreateCompatibleDC(screenDc); SelectObject(memscreenDc, hScreenBitmap); screenbits = new byte[50000000]; lastscreenbits = new byte[50000000]; } ReleaseDC(IntPtr.Zero, screenDc); /* PPzz : * this is my understandarding about drawing: * gCanvus is the graphics where in standard the strokes are drawn, I've introduced there also the drawing * gOnestrokeCanvus is filled with the current screen before drawing : it seems to be used when deleting(undo ?) a strike. * I've introduced gOutCanvus in order to have a graphics where I can draw in the inprogress shapes (Line,Ellipsis,Rectangular,Arrow) the previous ones, being strokes, are drawn on gCanvus * the timer1 refresh the window regularly */ InitCanvus.Dispose(); Init2Canvus.Dispose(); //this.DoubleBuffered = true; int gpheight = (int)(Screen.PrimaryScreen.Bounds.Height * Root.ToolbarHeight); gpButtonsImage = new Bitmap(2400, gpheight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); gpPenWidthImage = new Bitmap(200, gpheight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); TransparentBrush = new SolidBrush(Color.Transparent); SemiTransparentBrush = new SolidBrush(Color.FromArgb(120, 255, 255, 255)); ToTopMostThrough(); }
/// <summary> /// Save the text as an image file, will overwrite it if the file already exists /// </summary> /// <param name="text">The text to save</param> /// <param name="filename">Filename to save</param> /// <param name="font">Font to use for the text</param> /// <param name="textcolor">Color of the text</param> /// <param name="backgroundcolor">Color of the background</param> /// <param name="scale">Percentage scale of the image, 1.0-100.0</param> /// <param name="greyscale">Save the image as greyscale?</param> /// <returns>did the file save without errors?</returns> public static bool SaveTextAsImage(string text, string filename, Font font, Color textcolor, Color backgroundcolor, float scale, bool greyscale) { System.Guid format; switch (System.IO.Path.GetExtension(filename).ToLower()) { case ".png": format = ImageFormat.Png.Guid; break; case ".jpg": case ".jpeg": case ".jpe": format = ImageFormat.Jpeg.Guid; break; case ".gif": format = ImageFormat.Gif.Guid; break; case ".tif": case ".tiff": format = ImageFormat.Tiff.Guid; break; case ".bmp": case ".rle": case ".dib": default: format = ImageFormat.Bmp.Guid; break; } using (Bitmap bmpFullSize = FontFunctions.DrawText(text, font, textcolor, backgroundcolor)) { if (scale < 100f) { float fMagnification = scale / 100f; Size newSize = new Size((int)((bmpFullSize.Width * fMagnification) + 0.5), (int)((bmpFullSize.Height * fMagnification) + 0.5)); if (newSize.Width < 1) { newSize.Width = 1; } if (newSize.Height < 1) { newSize.Height = 1; } using (Bitmap bmpOutput = new Bitmap(newSize.Width, newSize.Height)) { using (ImageAttributes ia = new ImageAttributes()) { ia.SetColorMatrix(greyscale ? Matrices.Grayscale() : Matrices.Identity()); using (Graphics g = Graphics.FromImage(bmpOutput)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(bmpFullSize, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, bmpFullSize.Width, bmpFullSize.Height, GraphicsUnit.Pixel, ia); } } bmpOutput.Save(filename, new ImageFormat(format)); } } else { bmpFullSize.Save(filename, new ImageFormat(format)); } } return(true); }
public void SetColorMatrix_InvalidType() { using (ImageAttributes ia = new ImageAttributes()) { Assert.Throws <ArgumentException> (() => ia.SetColorMatrix(global_color_matrix, ColorMatrixFlag.Default, (ColorAdjustType)Int32.MinValue)); } }
public void SetColorMatrix_AltGrays_Brush() { using (ImageAttributes ia = new ImageAttributes()) { Assert.Throws <ArgumentException> (() => ia.SetColorMatrix(global_color_matrix, ColorMatrixFlag.AltGrays, ColorAdjustType.Brush)); } }
public void SetColorMatrix_Null() { using (ImageAttributes ia = new ImageAttributes()) { Assert.Throws <ArgumentException> (() => ia.SetColorMatrix(null)); } }
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); } }
/// <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(); } }
private void DrawCellBackground(GridControl.Cell cell, Rectangle area, Graphics graphics) { Image texture = GetTileTexture(cell.X, cell.Y); if (texture == null) { switch (map[cell.X, cell.Y].Type) { case TileType.Tunnel: graphics.FillRectangle(Brushes.White, area); break; case TileType.Rock: graphics.FillRectangle(Brushes.Gray, area); break; default: graphics.FillRectangle(Brushes.Green, area); break; } } else { TileStatus tile = map[cell.X, cell.Y]; if (tile.Estimates == null && tile.Found == null) { float b = 0.7f; ColorMatrix cm = new ColorMatrix(new float[][] { new float[] { b, 0, 0, 0, 0 }, new float[] { 0, b, 0, 0, 0 }, new float[] { 0, 0, b, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 }, }); ImageAttributes imgAttr = new ImageAttributes(); imgAttr.SetColorMatrix(cm); Point[] points = { new Point(area.Left, area.Top), new Point(area.Right, area.Top), new Point(area.Left, area.Bottom), }; Rectangle srcRect = new Rectangle(0, 0, area.Width, area.Height); graphics.DrawImage(texture, points, srcRect, GraphicsUnit.Pixel, imgAttr); } else { graphics.DrawImage(texture, area); } } texture = GetSaltTexture(CellToTile(cell)); if (texture != null) { graphics.DrawImage(texture, area); } texture = GetFlintTexture(CellToTile(cell)); if (texture != null) { graphics.DrawImage(texture, area); } }
/// <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(); }
public Bitmap ChangeBrightness(int redColor, int greenColor, int blueColor) { if (CurrentImage == null) { return(null); } var newImage = new Bitmap(CurrentImage); ImageAttributes imageAttributes = new ImageAttributes(); int width = newImage.Width; int height = newImage.Height; float basicFactor = 0.008F; float noChangeFactor = 1F; float redColorFactor; float greenColorFactor; float blueColorFactor; if (redColor != 0) { redColorFactor = basicFactor * redColor; } else { redColorFactor = noChangeFactor; } if (greenColor != 0) { greenColorFactor = basicFactor * greenColor; } else { greenColorFactor = noChangeFactor; } if (blueColor != 0) { blueColorFactor = basicFactor * blueColor; } else { blueColorFactor = noChangeFactor; } float[][] colorMatrixElements = { new float[] { redColorFactor, 0, 0, 0, 0 }, new float[] { 0, greenColorFactor, 0, 0, 0 }, new float[] { 0, 0, blueColorFactor, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }; ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix( colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); Graphics graphics = Graphics.FromImage(newImage); graphics.DrawImage(newImage, new Rectangle(0, 0, width, height), 0, 0, width, height, GraphicsUnit.Pixel, imageAttributes); ChangedImage = newImage; return(newImage); }
/// <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(HttpContext context, string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) { byte[] _ImageBytes = File.ReadAllBytes(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 = null; if (IsPixelFormatIndexed(img.PixelFormat)) { Bitmap bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb); using (Graphics g2 = Graphics.FromImage(bmp)) { g2.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g2.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g2.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g2.DrawImage(img, 0, 0); } img = bmp; } g = Graphics.FromImage(img); //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.AntiAlias; g.PixelOffsetMode = PixelOffsetMode.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; context.Response.ContentType = "image/jpeg"; //将叠加后的图片以指定的格式保存到Response的输出流中。 if (ici != null) { img.Save(context.Response.OutputStream, ici, encoderParams); } else { img.Save(context.Response.OutputStream, ImageFormat.Jpeg); } g.Dispose(); img.Dispose(); watermark.Dispose(); imageAttributes.Dispose(); context.Response.End(); }
//Draws timer protected override void OnPaint(PaintEventArgs p) { base.OnPaint(p); Graphics g = p.Graphics; if (minutes < 10) { if (seconds < 10) { g.DrawString("0" + minutes + ":" + "0" + seconds, new Font(FontFamily.GenericMonospace, 14F), new SolidBrush(Color.White), clockation); } else { g.DrawString("0" + minutes + ":" + seconds, new Font(FontFamily.GenericMonospace, 14F), new SolidBrush(Color.White), clockation); } } else { if (seconds < 10) { g.DrawString(minutes + ":" + "0" + seconds, new Font(FontFamily.GenericMonospace, 14F), new SolidBrush(Color.White), clockation); } else { g.DrawString(minutes + ":" + seconds, new Font(FontFamily.GenericMonospace, 14F), new SolidBrush(Color.White), clockation); } } foreach (Draw d in drawables) { if (Darkness.CalculateSize(player, d)) { if (!(d.source == null)) { if (d is Wall wall) { wall.checkErrors(drawables); } else if (d is Door door) { door.checkErrors(drawables); } ColorMatrix colorizer = new ColorMatrix(); colorizer.Matrix33 = Darkness.DarkLevel(player, d); ImageAttributes attr = new ImageAttributes(); attr.SetColorMatrix(colorizer, ColorMatrixFlag.Default); Rectangle rect = new Rectangle((int)d.location.x * tileSize, (int)d.location.y * tileSize, (int)d.width * tileSize, (int)d.height * tileSize); g.DrawImage(d.source, rect, 0, 0, tileSize, tileSize, GraphicsUnit.Pixel, attr); } else { //Troubleshooting g.FillRectangle(d.brush, d.location.x * tileSize, d.location.y * tileSize, d.width * tileSize, d.height * tileSize); } } } //Player Rectangle player_sprite = new Rectangle((int)player.location.x * tileSize, (int)player.location.y * tileSize, (int)player.width * tileSize, (int)player.height * tileSize); g.DrawImage(player.source, player_sprite); int times = 0; if (refreshBar) { times++; Debug.WriteLine("Bar refreshed: " + times + "times"); Graphics g2 = panel1.CreateGraphics(); g2.DrawImage(Properties.Resources.inventory, new PointF(494, 0)); int n = 1; foreach (Draw d in player.inventory.inventory_items) { Image texture = d.source; PointF point = new PointF(0, 0); switch (n) { case 1: point = Inventory.inventory_slot1; n += 1; break; case 2: point = Inventory.inventory_slot2; n += 1; break; case 3: point = Inventory.inventory_slot3; n += 1; break; case 4: point = Inventory.inventory_slot4; n += 1; break; case 5: point = Inventory.inventory_slot5; break; } Rectangle rect_location = new Rectangle((int)point.X + 7, (int)point.Y + 7, 32, 32); Debug.WriteLine("Location: " + rect_location); g2.DrawImage(texture, rect_location); if (d is Key key) { g2.DrawString(key.door.door_name, new Font(FontFamily.GenericMonospace, 7.0F), new SolidBrush(Color.White), new PointF(point.X + 2, 32)); } } //Empty hearts under full heart for (int lives = player.max_hitpoints; lives > 0; lives--) { Rectangle hp_position = new Rectangle(15 + lives * 35 - 35, 5, 32, 32); g2.DrawImage(Properties.Resources.hpEmpty, hp_position); } //Full hearts on top for (int lives = 0; lives < player.hitpoints; lives++) { Rectangle hp_position = new Rectangle(15 + lives * 35, 5, 32, 32); g2.DrawImage(Properties.Resources.hpFull, hp_position); } refreshBar = false; } UI.DisplayMessage(g); }
public void DrawImage(MapGraphics g, string imageName, bool drawShadow) { if (drawShadow && this.ShadowOffset == 0.0) { return; } Image image = this.Common.ImageLoader.LoadImage(imageName); if (image.Width != 0 && image.Height != 0) { RectangleF absoluteRectangle = g.GetAbsoluteRectangle(new RectangleF(0f, 0f, 100f, 100f)); Rectangle rectangle = Rectangle.Empty; if (this.ResizeMode == ResizeMode.AutoFit) { rectangle = new Rectangle((int)absoluteRectangle.X, (int)absoluteRectangle.Y, (int)absoluteRectangle.Width, (int)absoluteRectangle.Height); } else { rectangle = new Rectangle(0, 0, image.Width, image.Height); PointF absolutePoint = g.GetAbsolutePoint(new PointF(50f, 50f)); rectangle.X = (int)(absolutePoint.X - (float)(rectangle.Size.Width / 2)); rectangle.Y = (int)(absolutePoint.Y - (float)(rectangle.Size.Height / 2)); } ImageAttributes imageAttributes = new ImageAttributes(); if (this.ImageTransColor != Color.Empty) { imageAttributes.SetColorKey(this.ImageTransColor, this.ImageTransColor, ColorAdjustType.Default); } float num = (float)((100.0 - this.Transparency) / 100.0); float num2 = (float)(this.Common.MapCore.ShadowIntensity / 100.0); if (drawShadow) { ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.Matrix00 = 0f; colorMatrix.Matrix11 = 0f; colorMatrix.Matrix22 = 0f; colorMatrix.Matrix33 = num2 * num; imageAttributes.SetColorMatrix(colorMatrix); } else if (this.Transparency > 0.0) { ColorMatrix colorMatrix2 = new ColorMatrix(); colorMatrix2.Matrix33 = num; imageAttributes.SetColorMatrix(colorMatrix2); } if (this.Angle != 0.0) { PointF point = new PointF((float)(absoluteRectangle.X + absoluteRectangle.Width / 2.0), (float)(absoluteRectangle.Y + absoluteRectangle.Height / 2.0)); Matrix transform = g.Transform; Matrix matrix = g.Transform.Clone(); float offsetX = matrix.OffsetX; float offsetY = matrix.OffsetY; point.X += offsetX; point.Y += offsetY; matrix.RotateAt(this.Angle, point, MatrixOrder.Append); if (drawShadow) { matrix.Translate(this.ShadowOffset, this.ShadowOffset, MatrixOrder.Append); } g.Transform = matrix; g.DrawImage(image, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes); g.Transform = transform; } else { if (drawShadow) { rectangle.X += (int)this.ShadowOffset; rectangle.Y += (int)this.ShadowOffset; } g.DrawImage(image, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes); } if (!drawShadow) { using (GraphicsPath graphicsPath = new GraphicsPath()) { graphicsPath.AddRectangle(rectangle); if (this.Angle != 0.0) { PointF point2 = new PointF((float)(absoluteRectangle.X + absoluteRectangle.Width / 2.0), (float)(absoluteRectangle.Y + absoluteRectangle.Height / 2.0)); using (Matrix matrix2 = new Matrix()) { matrix2.RotateAt(this.Angle, point2, MatrixOrder.Append); graphicsPath.Transform(matrix2); } } this.Common.MapCore.HotRegionList.SetHotRegion(g, this, graphicsPath); } } } }
public (Stream fontStream, Image fontImage) Save(List <CharacterInfo> characterInfos, Size imageSize) { // Generating font textures var adjustedGlyphs = FontMeasurement.MeasureWhiteSpace(characterInfos.Select(x => (Bitmap)x.Glyph)).ToList(); // Adjust image size for at least the biggest letter var height = Math.Max(adjustedGlyphs.Max(x => x.WhiteSpaceAdjustment.GlyphSize.Height), imageSize.Height); var width = Math.Max(adjustedGlyphs.Max(x => x.WhiteSpaceAdjustment.GlyphSize.Width), imageSize.Width); imageSize = new Size(width, height); var generator = new FontTextureGenerator(imageSize, 0); var textureInfos = generator.GenerateFontTextures(adjustedGlyphs, 3).ToList(); // Join important lists var joinedCharacters = characterInfos.OrderBy(x => x.CodePoint).Join(adjustedGlyphs, c => c.Glyph, ag => ag.Glyph, (c, ag) => new { character = c, adjustedGlyph = ag }) .Select(cag => new { cag.character, cag.adjustedGlyph, textureIndex = textureInfos.FindIndex(x => x.Glyphs.Any(y => y.Item1 == cag.adjustedGlyph.Glyph)), texturePosition = textureInfos.SelectMany(x => x.Glyphs).FirstOrDefault(x => x.Item1 == cag.adjustedGlyph.Glyph).Item2 }); // Create character information var charMaps = new List <(AdjustedGlyph, XfCharMap)>(adjustedGlyphs.Count); var charSizeInfos = new List <XfCharSizeInfo>(); foreach (var joinedCharacter in joinedCharacters) { if (joinedCharacter.textureIndex == -1) { continue; } var charSizeInfo = new XfCharSizeInfo { offsetX = (sbyte)joinedCharacter.adjustedGlyph.WhiteSpaceAdjustment.GlyphPosition.X, offsetY = (sbyte)joinedCharacter.adjustedGlyph.WhiteSpaceAdjustment.GlyphPosition.Y, glyphWidth = (byte)joinedCharacter.adjustedGlyph.WhiteSpaceAdjustment.GlyphSize.Width, glyphHeight = (byte)joinedCharacter.adjustedGlyph.WhiteSpaceAdjustment.GlyphSize.Height }; if (!charSizeInfos.Contains(charSizeInfo)) { charSizeInfos.Add(charSizeInfo); } // Only used for Time Travelers var codePoint = ConvertChar(joinedCharacter.character.CodePoint); //var codePoint = joinedCharacter.character.CodePoint; var charInformation = new XfCharInformation { charSizeInfoIndex = charSizeInfos.IndexOf(charSizeInfo), charWidth = char.IsWhiteSpace((char)codePoint) ? joinedCharacter.character.CharacterSize.Width : joinedCharacter.character.CharacterSize.Width - charSizeInfo.offsetX }; charMaps.Add((joinedCharacter.adjustedGlyph, new XfCharMap { codePoint = (ushort)codePoint, charInformation = charInformation, imageInformation = new XfImageInformation { colorChannel = joinedCharacter.textureIndex, imageOffsetX = joinedCharacter.texturePosition.X, imageOffsetY = joinedCharacter.texturePosition.Y } })); if (codePoint != joinedCharacter.character.CodePoint) { charInformation = new XfCharInformation { charSizeInfoIndex = charSizeInfos.IndexOf(charSizeInfo), charWidth = char.IsWhiteSpace((char)joinedCharacter.character.CodePoint) ? joinedCharacter.character.CharacterSize.Width : joinedCharacter.character.CharacterSize.Width - charSizeInfo.offsetX }; charMaps.Add((joinedCharacter.adjustedGlyph, new XfCharMap { codePoint = (ushort)joinedCharacter.character.CodePoint, charInformation = charInformation, imageInformation = new XfImageInformation { colorChannel = joinedCharacter.textureIndex, imageOffsetX = joinedCharacter.texturePosition.X, imageOffsetY = joinedCharacter.texturePosition.Y } })); } } // Set escape characters var escapeIndex = charMaps.FindIndex(x => x.Item2.codePoint == '?'); Header.largeEscapeCharacter = escapeIndex < 0 ? (short)0 : (short)escapeIndex; Header.smallEscapeCharacter = 0; // Minimize top value and line height Header.largeCharHeight = (short)charSizeInfos.Max(x => x.glyphHeight + x.offsetY); Header.smallCharHeight = 0; // Draw textures var img = new Bitmap(imageSize.Width, imageSize.Height); var chn = new Bitmap(imageSize.Width, imageSize.Height); var gfx = Graphics.FromImage(chn); for (var i = 0; i < textureInfos.Count; i++) { var destPoints = new[] { new PointF(0, 0), new PointF(textureInfos[i].FontTexture.Width, 0), new PointF(0, textureInfos[i].FontTexture.Height) }; var rect = new RectangleF(0, 0, textureInfos[i].FontTexture.Width, textureInfos[i].FontTexture.Height); var attr = new ImageAttributes(); attr.SetColorMatrix(_inverseColorMatrices[i]); gfx.DrawImage(textureInfos[i].FontTexture, destPoints, rect, GraphicsUnit.Pixel, attr); img.PutChannel(chn); } // Save fnt.bin var savedFntBin = new MemoryStream(); using (var bw = new BinaryWriterX(savedFntBin, true)) { //Table0 bw.BaseStream.Position = 0x28; Header.charSizeCount = (short)charSizeInfos.Count; WriteMultipleCompressed(bw, charSizeInfos, _t0Comp); bw.WriteAlignment(4); //Table1 Header.largeCharOffset = (short)(bw.BaseStream.Position >> 2); Header.largeCharCount = (short)charMaps.Count; WriteMultipleCompressed(bw, charMaps.OrderBy(x => x.Item2.codePoint).Select(x => x.Item2).ToArray(), _t1Comp); bw.WriteAlignment(4); //Table2 Header.smallCharOffset = (short)(bw.BaseStream.Position >> 2); Header.smallCharCount = 0; WriteMultipleCompressed(bw, Array.Empty <XfCharMap>(), _t2Comp); bw.WriteAlignment(4); //Header bw.BaseStream.Position = 0; bw.WriteType(Header); } return(savedFntBin, img); }
/// <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(); } }
/// <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 void RenderLoop() { float[][] ptArray = { 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, 0.2F, 0 }, new float[] { 0, 0, 0, 0, 1 } }; ColorMatrix matrix = new ColorMatrix(ptArray); imgAtt = new ImageAttributes(); imgAtt.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); pen_y = new Pen(new SolidBrush(Color.FromArgb(90, Color.Yellow))); pen_x = new Pen(new SolidBrush(Color.FromArgb(90, Color.LimeGreen))); g = Graphics.FromImage(grid); for (int x = 0; x < 13; x++) { g.DrawLine(Pens.AliceBlue, x * 32, 0, x * 32, 320); } for (int y = 0; y < 10; y++) { g.DrawLine(Pens.AliceBlue, 0, y * 32, 416, y * 32); } while (gameRunning) { g = Graphics.FromImage(backBuffer); g.Clear(Color.Black); if (play == false) { //#################################################################### // Desenha todas as camadas #region Desenho Camadas if (ItemTool_Previous.Checked) { if (Static.frame.Count > 1) { if (currentFrame > 0) { RenderLayerBefore(currentFrame - 1, pen_y); } } } RenderLayer(currentFrame); if (ItemTool_Next.Checked) { if ((currentFrame + 1) < Static.frame.Count) { RenderLayerBefore(currentFrame + 1, pen_x); } } #endregion //#################################################################### // Desenhar o Grid if (ItemTool_Grid.Checked) { g.DrawImage(grid, 0, 0); } g.DrawRectangle(Pens.Coral, selectedRect); //#################################################################### //Desenha o Item selecionado if (currentObject != null) { g.DrawImage(currentObject, new Point(mousePosition.X - currentObject.Width / 2, mousePosition.Y - currentObject.Height / 2)); g.DrawRectangle(Pens.Peru, new Rectangle(new Point(mousePosition.X - currentObject.Width / 2, mousePosition.Y - currentObject.Height / 2), new Size(currentObject.Width, currentObject.Height))); } //#################################################################### g.DrawRectangle(new Pen(Brushes.Red, 2), cutScreen); } else { // ################ ANIM PLAY ############## if (Environment.TickCount >= (tick + frameRate)) { frameCount++; tick = Environment.TickCount; if (frameCount > Static.frame.Count - 1) { frameCount = 0; } } RenderLayer(frameCount); //########################################### } //FPSSS g.DrawString("FPS: " + fps, new Font("Verdana", 9), Brushes.Coral, new PointF(350, 5)); g.Dispose(); g = picAnim.CreateGraphics(); g.DrawImage(backBuffer, 0, 0); g.Dispose(); if (Environment.TickCount >= (fpsTick + 1000)) { fpsTick = Environment.TickCount; fps = fpsCount; fpsCount = 0; } else { fpsCount++; } Application.DoEvents(); } Application.Exit(); }
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(); }
protected override void OnPaint(PaintEventArgs e) { if (!e.ClipRectangle.Equals(this.ClientRectangle)) // always repaint whole { Invalidate(); return; } if (backImageControlBitmap == null || RowCount != lastrowcount) // First time, we have size.. or if multiline changes { CleanUp(); backImageControlBitmap = new Bitmap(Width, Height); Graphics backGraphics = Graphics.FromImage(backImageControlBitmap); PaintTransparentBackground(backGraphics, ClientRectangle); // force the paint of the background into this bitmap. backImageBitmap = new Bitmap(Width, Height); backImageGraphics = Graphics.FromImage(backImageBitmap); tabImageBitmap = new Bitmap(this.Width, this.Height); tabImageGraphics = Graphics.FromImage(this.tabImageBitmap); tabcontrolborder = new Rectangle(0, DisplayRectangle.Y - 2, ClientRectangle.Width - 1, DisplayRectangle.Height + 4); } backImageGraphics.Clear(Color.Transparent); backImageGraphics.DrawImageUnscaled(backImageControlBitmap, 0, 0); tabImageGraphics.Clear(Color.Transparent); // so I tried just drawing on the backImage.. but it did not work. No idea DrawBorder(tabImageGraphics); if (TabCount > 0) { for (int i = TabCount - 1; i >= 0; i--) { if (i != SelectedIndex) { DrawTab(i, tabImageGraphics, false, mouseover == i); } } System.Diagnostics.Debug.Assert(SelectedIndex < TabCount); if (SelectedIndex >= 0 && SelectedIndex < TabCount) // and if its selected, we did not draw it -- seen it above TabCount.. protect { DrawTab(SelectedIndex, tabImageGraphics, true, false); // we paint the selected one last, in case it overwrites the other ones. } } tabImageGraphics.Flush(); ColorMatrix alphaMatrix = new ColorMatrix(); alphaMatrix.Matrix00 = alphaMatrix.Matrix11 = alphaMatrix.Matrix22 = alphaMatrix.Matrix44 = 1; alphaMatrix.Matrix33 = TabOpaque / 100F; // Create a new image attribute object and set the color matrix to // the one just created using (ImageAttributes alphaAttributes = new ImageAttributes()) { alphaAttributes.SetColorMatrix(alphaMatrix); this.backImageGraphics.DrawImage(this.tabImageBitmap, new Rectangle(0, 0, this.tabImageBitmap.Width, this.tabImageBitmap.Height), 0, 0, this.tabImageBitmap.Width, this.tabImageBitmap.Height, GraphicsUnit.Pixel, alphaAttributes); } backImageGraphics.Flush(); e.Graphics.DrawImageUnscaled(backImageBitmap, 0, 0); }
/// <summary> /// converts an image to an ascii string /// </summary> /// <param name="imgStream">opened stream containing an image</param> /// <param name="fileStream">opened file to write HTML</param> /// <param name="imgBlockSize"> /// used to determine the width in pixels of one ascii character /// which is then used to determine the block size in pixels /// of one ascii character /// <remarks> /// acceptable values are [1, 2, 6, 8, 16, 24, 32] /// </remarks> /// </param> /// <param name="fontSize"> /// fixed width font size in pixels /// <remarks>5 pixels seems to be a good value</remarks> /// </param> /// <param name="quick"> /// true to perform a quick brightness calculation /// <param name="monitor"></param> /// <remarks> /// quick brightness calculation is only done on first row of pixels in a block /// </remarks> /// </param> /// <param name="colour">true to generate a colour ascii image</param> /// <param name="monitor"> /// optional callback to monitor progress, <seealso cref="IAsciiArtProgress"/> /// <remarks>pass in null to not monitor progress</remarks> /// </param> /// <returns></returns> public static void ConvertImage(Stream imgStream, StreamWriter fileStream, int imgBlockSize, int fontSize, bool quick, bool colour, IAsciiArtProgress monitor) { const string WebPage1 = "<html>" + "<body>" + "<pre>" + "<span style=\"font-size: {0}px\">"; fileStream.Write(WebPage1, fontSize); Bitmap bmp = null; try { #region load image using (var img = Image.FromStream(imgStream)) { bmp = new Bitmap(img, new Size(img.Width, img.Height)); } var bounds = new Rectangle(0, 0, bmp.Width, bmp.Height); #endregion #region greyscale image var matrix = new ColorMatrix(); matrix[0, 0] = 1 / 3f; matrix[0, 1] = 1 / 3f; matrix[0, 2] = 1 / 3f; matrix[1, 0] = 1 / 3f; matrix[1, 1] = 1 / 3f; matrix[1, 2] = 1 / 3f; matrix[2, 0] = 1 / 3f; matrix[2, 1] = 1 / 3f; matrix[2, 2] = 1 / 3f; var attributes = new ImageAttributes(); attributes.SetColorMatrix(matrix); if (!colour) { using (var gphGrey = Graphics.FromImage(bmp)) { gphGrey.DrawImage(bmp, bounds, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, attributes); } } #endregion #region ascii image var pixWidth = imgBlockSize; var pixHeight = pixWidth * 2; var pixSeg = pixWidth * pixHeight; var numHeightIter = bmp.Height / pixHeight; var numWidthIter = bmp.Width / pixWidth; var percentIter = (numHeightIter * numWidthIter / 100) + 1; var currIter = 0; for (var h = 0; h < numHeightIter; h++, currIter++) { // segment height var startY = (h * pixHeight); // segment width for (var w = 0; w < numWidthIter; w++, currIter++) { if (monitor != null && (currIter % percentIter) == 0) { monitor.Progress(currIter / percentIter); } var startX = (w * pixWidth); var allBrightness = 0; var allAlpha = 0; var allRed = 0; var allGreen = 0; var allBlue = 0; if (quick) { // each pix of this segment for (var y = 0; y < pixWidth; y++) { try { var clr = bmp.GetPixel(startX, y + startY); allAlpha += clr.A; allRed += clr.R; allGreen += clr.G; allBlue += clr.B; var brt = (int)(clr.GetBrightness() * 100); allBrightness = allBrightness + brt; } catch { allBrightness = (allBrightness + 50); } } } else { // each pix of this segment for (var y = 0; y < pixWidth; y++) { for (var x = 0; x < pixHeight; x++) { var cY = y + startY; var cX = x + startX; try { if (cX < bmp.Width) { var clr = bmp.GetPixel(cX, cY); allAlpha += clr.A; allRed += clr.R; allGreen += clr.G; allBlue += clr.B; var brt = (int)(clr.GetBrightness() * 100); allBrightness = allBrightness + brt; } } catch { allBrightness = (allBrightness + 50); } } } } var avgAlpha = (allAlpha / pixSeg); var avgRed = (allRed / pixSeg); var avgGreen = (allGreen / pixSeg); var avgBlue = (allBlue / pixSeg); var avgClr = Color.FromArgb(avgAlpha, avgRed, avgGreen, avgBlue); var sbrt = (allBrightness / pixSeg); string asciiChar; if (sbrt < 10) { asciiChar = "#"; } else if (sbrt < 17) { asciiChar = "@"; } else if (sbrt < 24) { asciiChar = "&"; } else if (sbrt < 31) { asciiChar = "$"; } else if (sbrt < 38) { asciiChar = "%"; } else if (sbrt < 45) { asciiChar = "|"; } else if (sbrt < 52) { asciiChar = "!"; } else if (sbrt < 59) { asciiChar = ";"; } else if (sbrt < 66) { asciiChar = ":"; } else if (sbrt < 73) { asciiChar = "'"; } else if (sbrt < 80) { asciiChar = "`"; } else if (sbrt < 87) { asciiChar = "."; } else { asciiChar = " "; } if (colour) { const string ColourCharElement = "<code style=\"color:{0}\">{1}</code>"; var clrHex = string.Format("#{0:x}{1:x}{2:x}", avgClr.R, avgClr.G, avgClr.B); var asciiStr = string.Format(ColourCharElement, clrHex, asciiChar); fileStream.Write(asciiStr); } else { fileStream.Write(asciiChar); } } fileStream.Write("\n"); } #endregion } finally { //clean up bmp.Dispose(); } const string WebPage3 = "</span>" + "</pre>" + "</body>" + "</html>"; fileStream.Write(WebPage3); }
/// <summary> /// 图片等比缩放 /// </summary> /// <remarks>谭光洪 2015-05-09</remarks> /// <param name="fromFile">原图Stream对象</param> /// <param name="savePath">缩略图存放地址</param> /// <param name="targetWidth">指定的最大宽度</param> /// <param name="targetHeight">指定的最大高度</param> /// <param name="watermarkText">水印文字(为""表示不使用水印)</param> /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param> public static void ZoomAuto(System.IO.Stream fromFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText, string watermarkImage) { //创建目录 string dir = Path.GetDirectoryName(savePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= targetWidth && initImage.Height <= targetHeight) { //文字水印 if (watermarkText != "") { using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage)) { System.Drawing.Font fontWater = new Font("黑体", 10); System.Drawing.Brush brushWater = new SolidBrush(Color.White); gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10); gWater.Dispose(); } } //透明图片水印 if (watermarkImage != "") { if (File.Exists(watermarkImage)) { //获取水印图片 using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage)) { //水印绘制条件:原始图片宽高均大于或等于水印图片 if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height) { Graphics gWater = Graphics.FromImage(initImage); //透明属性 ImageAttributes imgAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5 new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes); gWater.Dispose(); } wrImage.Dispose(); } } } //保存 initImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //缩略图宽、高计算 double newWidth = initImage.Width; double newHeight = initImage.Height; //宽大于高或宽等于高(横图或正方) if (initImage.Width > initImage.Height || initImage.Width == initImage.Height) { //如果宽大于模版 if (initImage.Width > targetWidth) { //宽按模版,高按比例缩放 newWidth = targetWidth; newHeight = initImage.Height * (targetWidth / initImage.Width); } } //高大于宽(竖图) else { //如果高大于模版 if (initImage.Height > targetHeight) { //高按模版,宽按比例缩放 newHeight = targetHeight; newWidth = initImage.Width * (targetHeight / initImage.Height); } } //生成新图 //新建一个bmp图片 System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight); //新建一个画板 System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage); //设置质量 newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; newG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //置背景色 newG.Clear(Color.White); //画图 newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); //文字水印 if (watermarkText != "") { using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(newImage)) { System.Drawing.Font fontWater = new Font("宋体", 10); System.Drawing.Brush brushWater = new SolidBrush(Color.White); gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10); gWater.Dispose(); } } //透明图片水印 if (watermarkImage != "") { if (File.Exists(watermarkImage)) { //获取水印图片 using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage)) { //水印绘制条件:原始图片宽高均大于或等于水印图片 if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height) { Graphics gWater = Graphics.FromImage(newImage); //透明属性 ImageAttributes imgAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5 new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes); gWater.Dispose(); } wrImage.Dispose(); } } } //保存缩略图 newImage.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg); //释放资源 newG.Dispose(); newImage.Dispose(); initImage.Dispose(); } }
public void SetColorMatrix_Default_Any() { using (ImageAttributes ia = new ImageAttributes()) { Assert.Throws <ArgumentException> (() => ia.SetColorMatrix(global_color_matrix, ColorMatrixFlag.Default, ColorAdjustType.Any)); } }
/// <summary> /// 生成水印图 /// </summary> /// <param name="originalImagePath">源图绝对路径</param> /// <param name="watermarkType">水印类型:文字水印,图片水印</param> /// <param name="watermarkImage">水印图绝对路径</param> /// <param name="watermarkText">水印文字</param> /// <param name="fontSize">字体大小</param> /// <param name="fontColor">字体颜色</param> /// <param name="fontFamily">字体</param> /// <param name="watermarkPosition">水印位置</param> /// <param name="alpha">透明度</param> /// <param name="watermarkFilePath">水印图片保存路径,不填写则自动创建</param> /// <returns></returns> public static string AddWatermark(string originalImagePath, string watermarkType, string watermarkImage , string watermarkText, int fontSize, string fontColor, string fontFamily, WatermarkPosition watermarkPosition, float alpha, string watermarkFilePath = "") { Image img = Image.FromFile(originalImagePath); // 封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。 Bitmap bmPhoto = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppRgb); // 设定分辨率 bmPhoto.SetResolution(72, 72); System.Drawing.Graphics g = Graphics.FromImage(bmPhoto); //设置高质量插值法 g.InterpolationMode = InterpolationMode.High; //消除锯齿 g.SmoothingMode = SmoothingMode.AntiAlias; //g.SmoothingMode = SmoothingMode.HighQuality; g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel); //文件扩展名 string strExt = Path.GetExtension(originalImagePath); //生成的水印图文件名 if (watermarkFilePath.IsNullOrEmpty()) { watermarkFilePath = originalImagePath.Replace(strExt, "_watermark" + strExt); } 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[][] 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 colorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); //水印所在位置 int xpos = 0; int ypos = 0; int intWatermarkWidth = 0; int intWatermarkHeight = 0; Image watermark = null; if (watermarkType.Equals("图片水印") && File.Exists(watermarkImage)) { //加载水印图片 watermark = new Bitmap(watermarkImage); intWatermarkWidth = watermark.Width; intWatermarkHeight = watermark.Height; } else if (watermarkType.Equals("文字水印") && watermarkText.Trim().Length > 0) { SizeF size = g.MeasureString(watermarkText, new Font(new FontFamily(fontFamily), fontSize)); intWatermarkWidth = (int)size.Width; intWatermarkHeight = (int)size.Height; } switch (watermarkPosition) { case WatermarkPosition.TopLeft: xpos = (int)(img.Width * (float).01); ypos = (int)(img.Height * (float).01); break; case WatermarkPosition.TopCenter: xpos = (int)((img.Width * (float).50) - (intWatermarkWidth / 2)); ypos = (int)(img.Height * (float).01); break; case WatermarkPosition.TopRight: xpos = (int)((img.Width * (float).99) - (intWatermarkWidth)); ypos = (int)(img.Height * (float).01); break; case WatermarkPosition.MiddleLeft: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).50) - (intWatermarkHeight / 2)); break; case WatermarkPosition.MiddleCenter: xpos = (int)((img.Width * (float).50) - (intWatermarkWidth / 2)); ypos = (int)((img.Height * (float).50) - (intWatermarkHeight / 2)); break; case WatermarkPosition.MiddleRight: xpos = (int)((img.Width * (float).99) - (intWatermarkWidth)); ypos = (int)((img.Height * (float).50) - (intWatermarkHeight / 2)); break; case WatermarkPosition.BottomLeft: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).99) - intWatermarkHeight); break; case WatermarkPosition.BottomCenter: xpos = (int)((img.Width * (float).50) - (intWatermarkWidth / 2)); ypos = (int)((img.Height * (float).99) - intWatermarkHeight); break; case WatermarkPosition.BottomRight: xpos = (int)((img.Width * (float).99) - (intWatermarkWidth)); ypos = (int)((img.Height * (float).99) - intWatermarkHeight); break; } if (watermark != null) //在原图上画图片水印 { g.DrawImage(watermark, new Rectangle(xpos, ypos, intWatermarkWidth, intWatermarkHeight), 0, 0, intWatermarkWidth, intWatermarkHeight, GraphicsUnit.Pixel, imageAttributes); } else { //在原图上画文本水印 Font font = new Font(fontFamily, fontSize); //文字字体 Color fColor = ColorTranslator.FromHtml(fontColor); Color txtColor = Color.FromArgb(Convert.ToInt32(alpha * 255), fColor); //文字颜色 SolidBrush brush = new SolidBrush(txtColor); g.DrawString(watermarkText, font, brush, xpos, ypos); } 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]; qualityParam[0] = 80; //图片质量 EncoderParameter encoderParam = new EncoderParameter(Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) { bmPhoto.Save(watermarkFilePath, ici, encoderParams); } else { bmPhoto.Save(watermarkFilePath); } g.Dispose(); img.Dispose(); if (watermark != null) { watermark.Dispose(); } imageAttributes.Dispose(); return(watermarkFilePath); }
public void SetColorMatrix_SkipGrays_Count() { using (ImageAttributes ia = new ImageAttributes()) { Assert.Throws <ArgumentException> (() => ia.SetColorMatrix(global_color_matrix, ColorMatrixFlag.SkipGrays, ColorAdjustType.Count)); } }
public static Image CreateBanner(int nWidth, int nHeight, BannerStyle bs, Image imgIcon, string strTitle, string strLine) { // imgIcon may be null. Debug.Assert(strTitle != null); if (strTitle == null) { throw new ArgumentNullException("strTitle"); } Debug.Assert(strLine != null); if (strLine == null) { throw new ArgumentNullException("strLine"); } string strImageID = nWidth.ToString() + "x" + nHeight.ToString() + ":"; if (strTitle != null) { strImageID += strTitle; } strImageID += ":"; if (strLine != null) { strImageID += strLine; } if (bs == BannerStyle.Default) { bs = Program.Config.UI.BannerStyle; } strImageID += ":" + ((uint)bs).ToString(); // Try getting the banner from the banner cache. Image img; if (m_vImageCache.TryGetValue(strImageID, out img)) { return(img); } // Banner not in cache already -> create new banner. img = new Bitmap(nWidth, nHeight, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(img); const int offsetIcon = 10; Color clrStart = Color.White; Color clrEnd = Color.LightBlue; float fAngle = 0.90f; if (bs == BannerStyle.BlueCarbon) { fAngle = 90.0f; clrStart = Color.LightGray; clrEnd = Color.Black; Rectangle rect = new Rectangle(0, 0, nWidth, (nHeight * 3) / 8); LinearGradientBrush washBrush = new LinearGradientBrush(rect, clrStart, clrEnd, fAngle, true); g.FillRectangle(washBrush, rect); clrStart = Color.FromArgb(0, 0, 32); clrEnd = Color.FromArgb(192, 192, 255); rect = new Rectangle(0, nHeight / 2, nWidth, (nHeight * 5) / 8); washBrush = new LinearGradientBrush(rect, clrStart, clrEnd, fAngle, true); g.FillRectangle(washBrush, rect); } 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 = 90.0f; } 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); LinearGradientBrush washBrush = new LinearGradientBrush(rect, clrStart, clrEnd, fAngle, true); g.FillRectangle(washBrush, rect); } if (imgIcon != null) { int yIcon = (nHeight - imgIcon.Height) / 2; g.DrawImageUnscaled(imgIcon, offsetIcon, yIcon); ColorMatrix cm = new ColorMatrix(); cm.Matrix33 = 0.1f; ImageAttributes ia = new ImageAttributes(); ia.SetColorMatrix(cm); int w = imgIcon.Width * 3, h = imgIcon.Height * 3; int x = nWidth - w - 10, 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)) { Rectangle rect = new Rectangle(0, nHeight - 2, 0, 2); rect.Width = nWidth / 2 + 1; rect.X = nWidth / 2; clrStart = Color.FromArgb(248, 136, 24); clrEnd = Color.White; LinearGradientBrush brushOrangeWhite = new LinearGradientBrush(rect, clrStart, clrEnd, 0.90f, true); g.FillRectangle(brushOrangeWhite, rect); rect.Width = nWidth / 2 + 1; rect.X = 0; clrStart = Color.White; clrEnd = Color.FromArgb(248, 136, 24); LinearGradientBrush brushWhiteOrange = new LinearGradientBrush(rect, clrStart, clrEnd, 0.90f, true); g.FillRectangle(brushWhiteOrange, rect); } else if (bs == BannerStyle.KeePassWin32) { // Black separator line Pen penBlack = new Pen(Color.Black); g.DrawLine(penBlack, 0, nHeight - 1, nWidth - 1, nHeight - 1); } Font font = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold); Brush brush; if (bs == BannerStyle.KeePassWin32) { brush = Brushes.Black; } else { brush = Brushes.White; } float fx = 2 * offsetIcon, fy = 9.0f; if (imgIcon != null) { fx += imgIcon.Width; } g.DrawString(strTitle, font, brush, fx, fy); Font fontSmall = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Regular); fx += offsetIcon; fy += offsetIcon * 2 + 2; g.DrawString(strLine, fontSmall, brush, fx, fy); if (m_vImageCache.Count >= MaxCachedImages) { foreach (string strKey in m_vImageCache.Keys) { m_vImageCache.Remove(strKey); break; } } // Save in cache. m_vImageCache[strImageID] = img; g.Dispose(); return(img); }
/// <summary> /// Modify and convert an Image to an OutputSize array of Byte values /// </summary> /// <param name="image">Image to convert</param> /// <param name="outputSize">Size of the array to be returned</param> /// <param name="matrix">ColorMatrix to be applied to the image</param> /// <param name="section">The part of the image to be used</param> /// <returns>2d array of bytes of size [OutputSize.Width, OutputSize.Height]</returns> public static byte[,] ImageToTextValues(Image image, Size outputSize, ColorMatrix matrix, Rectangle section) { if (image == null || matrix == null) { return(null); } byte[,] OutputArray; try { OutputArray = new byte[outputSize.Width, outputSize.Height]; } catch (System.OutOfMemoryException) { return(null); } using (Bitmap Resized = new Bitmap(outputSize.Width, outputSize.Height)) { // draw a resized version onto the new bitmap using (Graphics g = Graphics.FromImage(Resized)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(image, new Rectangle(0, 0, outputSize.Width, outputSize.Height), section.X, section.Y, section.Width, section.Height, GraphicsUnit.Pixel); } // copy the resized version onto a new bitmap, applying the matrix using (Bitmap Target = new Bitmap(outputSize.Width, outputSize.Height)) { // create the image attributes and pass it the matrix using (ImageAttributes ia = new ImageAttributes()) { // merge the passed matrix with the matrix for converting to greyscale ColorMatrix cm = Matrices.Multiply(Matrices.Grayscale(), matrix); ia.SetColorMatrix(cm); using (Graphics grap = Graphics.FromImage(Target)) { grap.DrawImage(Resized, new Rectangle(0, 0, outputSize.Width, outputSize.Height), 0, 0, outputSize.Width, outputSize.Height, GraphicsUnit.Pixel, ia); } } // loop for all rows for (int y = 0; y < outputSize.Height; y++) { // loop for all pixels in the row for (int x = 0; x < outputSize.Width; x++) { // TODO: Check overhead, use unsafe code? // get and store the R component of the pixel (R=G=B) OutputArray[x, y] = Target.GetPixel(x, y).R; } } } } // return the array return(OutputArray); }
/// <summary> /// Renders the layer /// </summary> /// <param name="g">Graphics object reference</param> /// <param name="map">Map which is rendered</param> public override void Render(Graphics g, Map map) { if (map.Center == null) { throw (new ApplicationException("Cannot render map. View center not specified")); } if (_image == null) { throw new Exception("Image not set"); } if (m_BorderDataProvider == null || m_ImageDataProvider == null) { return; } // Style enabled? var doRender = Style.Enabled; // Valid for this zoom if (map.Zoom < Style.MinVisible || Style.MaxVisible < map.Zoom) { doRender = false; } // View to render var mapView = map.Envelope; // Layer view var lyrView = _envelope; // Get the view intersection var vi = mapView.Intersection(lyrView); if (doRender && !vi.IsNull) { // Image part // ReSharper disable InconsistentNaming var imgLT = Clip(_worldFile.ToRaster(new Coordinate(vi.MinX, vi.MaxY))); var imgRB = Clip(_worldFile.ToRaster(new Coordinate(vi.MaxX, vi.MinY))); var imgRect = new Rectangle(imgLT, PointDiff(imgLT, imgRB, 1)); // Map Part var mapLT = Point.Truncate(map.WorldToImage(new Coordinate(vi.MinX, vi.MaxY))); var mapRB = Point.Ceiling(map.WorldToImage(new Coordinate(vi.MaxX, vi.MinY))); var mapRect = new Rectangle(mapLT, PointDiff(mapLT, mapRB, 1)); // ReSharper restore InconsistentNaming // Set the interpolation mode var tmpInterpolationMode = g.InterpolationMode; g.InterpolationMode = InterpolationMode; // Render the image using (var ia = new ImageAttributes()) { ia.SetColorMatrix(new ColorMatrix { Matrix44 = 1 - Transparency }, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); //mapRect.X = 0; //mapRect.Y = 0; g.DrawImage(_image, mapRect, imgRect.X, imgRect.Y, imgRect.Width, imgRect.Height, GraphicsUnit.Pixel, ia); //g.DrawImage(_image, imgRect, imgRect.X, imgRect.Y, imgRect.Width, imgRect.Height, // GraphicsUnit.Pixel, ia); } RenderBorder(g, mapRect, imgRect); // reset the interpolation mo de g.InterpolationMode = tmpInterpolationMode; } base.Render(g, map); }
/// <summary> /// 图片水印 /// </summary> /// <param name="ImgFile">原图文件地址</param> /// <param name="WaterImg">水印图片地址</param> /// <param name="sImgPath">水印图片保存地址</param> /// <param name="Alpha">水印透明度设置</param> /// <param name="iScale">水印图片在原图上的显示比例</param> /// <param name="intDistance">水印图片在原图上的边距确定,以图片的右边和下边为准,当设定的边距超过一定大小后参数会自动失效</param> public bool zzsImgWater( string ImgFile , string WaterImg , string sImgPath , float Alpha , float iScale , int intDistance ) { try { //装载图片 FileStream fs = new FileStream(ImgFile, FileMode.Open); BinaryReader br = new BinaryReader(fs); byte[] bytes = br.ReadBytes((int)fs.Length); br.Close(); fs.Close(); MemoryStream ms = new MemoryStream(bytes); System.Drawing.Image imgPhoto = System.Drawing.Image.FromStream(ms); //System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(ImgFile); int imgPhotoWidth = imgPhoto.Width; int imgPhotoHeight = imgPhoto.Height; System.Drawing.Image imgWatermark = new Bitmap(WaterImg); int imgWatermarkWidth = imgWatermark.Width; int imgWatermarkHeight = imgWatermark.Height; //计算水印图片尺寸 decimal aScale = Convert.ToDecimal(iScale); decimal pScale = 0.05M; decimal MinScale = aScale - pScale; decimal MaxScale = aScale + pScale; int imgWatermarkWidthNew = imgWatermarkWidth; int imgWatermarkHeightNew = imgWatermarkHeight; if (imgPhotoWidth >= imgWatermarkWidth && imgPhotoHeight >= imgWatermarkHeight && imgPhotoWidth >= imgPhotoHeight) { if (imgWatermarkWidth > imgWatermarkHeight) { if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7) <= MaxScale)) { } else { imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale); imgWatermarkHeightNew = Convert.ToInt32((imgPhotoWidth * aScale / imgWatermarkWidth) * imgWatermarkHeight); } } else if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7) <= MaxScale)) { } else { imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale); imgWatermarkWidthNew = Convert.ToInt32((imgPhotoHeight * aScale / imgWatermarkHeight) * imgWatermarkWidth); } } if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgWatermarkWidth >= imgWatermarkHeight) { imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale); imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight); } if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight <= imgPhotoHeight && imgPhotoWidth >= imgPhotoHeight) { imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale); imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight); } if (imgWatermarkWidth <= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgPhotoWidth >= imgPhotoHeight) { imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale); imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth); } if (imgPhotoWidth >= imgWatermarkWidth && imgPhotoHeight >= imgWatermarkHeight && imgPhotoWidth <= imgPhotoHeight) { if (imgWatermarkWidth > imgWatermarkHeight) { if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkWidth) / Convert.ToDecimal(imgPhotoWidth)), 7) <= MaxScale)) { } else { imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale); imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight); } } else if ((MinScale <= Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7)) && (Math.Round((Convert.ToDecimal(imgWatermarkHeight) / Convert.ToDecimal(imgPhotoHeight)), 7) <= MaxScale)) { } else { imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale); imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth); } } if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgWatermarkWidth <= imgWatermarkHeight) { imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale); imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth); } if (imgWatermarkWidth >= imgPhotoWidth && imgWatermarkHeight <= imgPhotoHeight && imgPhotoWidth <= imgPhotoHeight) { imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale); imgWatermarkHeightNew = Convert.ToInt32(((imgPhotoWidth * aScale) / imgWatermarkWidth) * imgWatermarkHeight); } if (imgWatermarkWidth <= imgPhotoWidth && imgWatermarkHeight >= imgPhotoHeight && imgPhotoWidth <= imgPhotoHeight) { imgWatermarkHeightNew = Convert.ToInt32(imgPhotoHeight * aScale); imgWatermarkWidthNew = Convert.ToInt32(((imgPhotoHeight * aScale) / imgWatermarkHeight) * imgWatermarkWidth); } //将原图画出来 Bitmap bmPhoto = new Bitmap(imgPhotoWidth, imgPhotoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb); bmPhoto.SetResolution(72, 72); Graphics gbmPhoto = Graphics.FromImage(bmPhoto); gbmPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; gbmPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gbmPhoto.Clear(Color.White); gbmPhoto.DrawImage( imgPhoto , new Rectangle(0, 0, imgPhotoWidth, imgPhotoHeight) , 0 , 0 , imgPhotoWidth , imgPhotoHeight , GraphicsUnit.Pixel ); Bitmap bmWatermark = new Bitmap(bmPhoto); bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics gWatermark = Graphics.FromImage(bmWatermark); //指定高质量显示水印图片质量 gWatermark.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; gWatermark.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 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, System.Drawing.Imaging.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, Alpha, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; System.Drawing.Imaging.ColorMatrix wmColorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(wmColorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap); //确定水印边距 int xPos = imgPhotoWidth - imgWatermarkWidthNew; int yPos = imgPhotoHeight - imgWatermarkHeightNew; int xPosOfWm = 0; int yPosOfWm = 0; if (xPos > intDistance) { xPosOfWm = xPos - intDistance; } else { xPosOfWm = xPos; } if (yPos > intDistance) { yPosOfWm = yPos - intDistance; } else { yPosOfWm = yPos; } gWatermark.DrawImage( imgWatermark , new Rectangle(xPosOfWm, yPosOfWm, imgWatermarkWidthNew, imgWatermarkHeightNew) , 0 , 0 , imgWatermarkWidth , imgWatermarkHeight , GraphicsUnit.Pixel , imageAttributes ); imgPhoto = bmWatermark; //以jpg格式保存图片 imgPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg); //销毁对象 gbmPhoto.Dispose(); gWatermark.Dispose(); imgPhoto.Dispose(); imgWatermark.Dispose(); return(true); } catch { return(false); } }
/// <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(); }
/// <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(); }
/// <summary> /// ͼƬˮӡ /// </summary> /// <param name="srcPath">ԭͼ·��</param> /// <param name="waterImg">ˮӡͼ</param> /// <param name="markx">X����</param> /// <param name="marky">Y����</param> /// <param name="transparence">����</param> /// <param name="outPath">ˮӡ���·��</param> /// <returns>�Ƿ�ɹ�ˮӡ</returns> public static bool ImageMark(Image img, Image markImg, int markx, int marky, float transparence, string outPath) { //Image img = Image.FromFile(srcPath); //�������жϸ�ͼƬ�Ƿ��� gif���������Ϊgif��������ͼƬ���иĶ� foreach (Guid guid in img.FrameDimensionsList) { FrameDimension dimension = new FrameDimension(guid); if (img.GetFrameCount(dimension) > 1) { return(false); } } try { //���ˮӡͼ�� //Image markImg = waterImg; //������ɫ���� float[][] ptsArray = { 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, transparence, 0 }, //ע�⣺�˴�Ϊ0.0fΪ��ȫ����1.0fΪ��ȫ���� new float[] { 0, 0, 0, 0, 1 } }; ColorMatrix colorMatrix = new ColorMatrix(ptsArray); //�½�һ��Image���� ImageAttributes imageAttributes = new ImageAttributes(); //����ɫ������ӵ����� imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default); //����λͼ��ͼ�� Bitmap newBitmap = new Bitmap(img.Width, img.Height, PixelFormat.Format24bppRgb); //���÷ֱ��� newBitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution); //����Graphics Graphics g = Graphics.FromImage(newBitmap); //������� g.SmoothingMode = SmoothingMode.AntiAlias; //����ԭͼ����ͼ�� g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel); //���ԭͼ��С if (markImg.Width > img.Width || markImg.Height > img.Height) { System.Drawing.Image.GetThumbnailImageAbort callb = null; //��ˮӡͼƬ��������ͼ,��С��ԭͼ��1/4 System.Drawing.Image new_img = markImg.GetThumbnailImage(img.Width / 4, markImg.Height * img.Width / markImg.Width, callb, new System.IntPtr()); //���ˮӡ g.DrawImage(new_img, new Rectangle(markx, marky, new_img.Width, new_img.Height), 0, 0, new_img.Width, new_img.Height, GraphicsUnit.Pixel, imageAttributes); //�ͷ�����ͼ new_img.Dispose(); //�ͷ�Graphics g.Dispose(); img.Dispose(); newBitmap.Save(outPath); return(true); } //ԭͼ�㹻�� else { //���ˮӡ g.DrawImage(markImg, new Rectangle(markx, marky, markImg.Width, markImg.Height), 0, 0, markImg.Width, markImg.Height, GraphicsUnit.Pixel, imageAttributes); //�ͷ�Graphics g.Dispose(); img.Dispose(); newBitmap.Save(outPath); return(true); } } catch { return(false); } }
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> /// 设置水印 /// </summary> /// <param name="imgPath"></param> /// <param name="model"></param> /// <returns></returns> public static Image SetWaterMark(string imgPath, WaterMark model) { Image imgSource = null; //背景图 Image markImg = null; //水印图片 if (!TryFromFile(imgPath, ref imgSource)) { return(null); } //水印检验(文字,图片[路径下是否存在图片]) #region 水印校验+水印处理 if (model == null) { return(null); } if (!System.IO.File.Exists(imgPath)) { return(null); } //看看原图是否存在 //根据水印类型校验+水印处理 switch (model.WaterMarkType) { case WaterMarkTypeEnum.Text: if (string.IsNullOrEmpty(model.Text)) { return(null); } else { markImg = TextToImager(model); //水印处理-如果是文字就转换成图片 } break; case WaterMarkTypeEnum.Image: if (!System.IO.File.Exists(model.ImgPath)) { return(null); } else { if (!TryFromFile(model.ImgPath, ref markImg)) //获得水印图像 { return(imgSource); } } break; case WaterMarkTypeEnum.NoneMark: return(imgSource); } #endregion #region 创建颜色矩阵 //创建颜色矩阵 float[][] ptsArray = { 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, model.Transparency, 0 }, //注意:0.0f为完全透明,1.0f为完全不透明 new float[] { 0, 0, 0, 0, 1 } }; ColorMatrix colorMatrix = new ColorMatrix(ptsArray); //新建一个Image属性 ImageAttributes imageAttributes = new ImageAttributes(); //将颜色矩阵添加到属性 imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default); #endregion //原图格式检验+水印 #region 原图格式检验+水印 //判断是否是索引图像格式 if (imgSource.PixelFormat == PixelFormat.Format1bppIndexed || imgSource.PixelFormat == PixelFormat.Format4bppIndexed || imgSource.PixelFormat == PixelFormat.Format8bppIndexed) { #region 索引图片,转成位图再加图片 //转成位图,这步很重要 Bitmap bitmap = new Bitmap(imgSource.Width, imgSource.Height); Graphics graphic = Graphics.FromImage(bitmap); #region 缩放处理 //如果原图小于水印图片 等比缩放水印图 if (markImg.Width >= imgSource.Width || markImg.Height >= imgSource.Height) { markImg = ImageShrink(imgSource, markImg); } #endregion #region 水印位置 //水印位置 int x; int y; WaterMarkLocations(model, imgSource, markImg, out x, out y); #endregion //将原图画在位图上 graphic.DrawImage(imgSource, new Point(0, 0)); //将水印加在位图上 graphic.DrawImage(markImg, new Rectangle(x, y, markImg.Width, markImg.Height), 0, 0, markImg.Width, markImg.Height, GraphicsUnit.Pixel, imageAttributes); graphic.Dispose(); return(bitmap); #endregion } else { #region 非索引图片,直接在上面加上水印 Graphics graphic = Graphics.FromImage(imgSource); #region 缩放处理 //如果原图小于水印图片 等比缩放水印图 if (markImg.Width >= imgSource.Width || markImg.Height >= imgSource.Height) { markImg = ImageShrink(imgSource, markImg); } #endregion #region 水印位置 //水印位置 int x; int y; WaterMarkLocations(model, imgSource, markImg, out x, out y); #endregion //将水印加在原图上 graphic.DrawImage(markImg, new Rectangle(x, y, markImg.Width, markImg.Height), 0, 0, markImg.Width, markImg.Height, GraphicsUnit.Pixel, imageAttributes); graphic.Dispose(); return(imgSource); #endregion } #endregion }
/// <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; }
/// <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 static void BuildWatermark(string rSrcImgPath, string rMarkImgPath, string rMarkText, string rDstImgPath) { //以下(代码)从一个指定文件创建了一个Image 对象,然后为它的 Width 和 Height定义变量。 //这些长度待会被用来建立一个以24 bits 每像素的格式作为颜色数据的Bitmap对象。 Image imgPhoto = Image.FromFile(rSrcImgPath); int phWidth = imgPhoto.Width; int phHeight = imgPhoto.Height; Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(72, 72); 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[] { 92, 62, 42, 32, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4 }; Font crFont = null; SizeF crSize = new SizeF(); for (int i = 0; i < sizes.Length; i++) { crFont = new Font("华文彩云", 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 = (int)(phHeight * .05); float yPosFromBottom = ((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, 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); //随着两个颜色处理加入到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; } int xPosOfWm = ((phWidth - markWidth) - 10); int yPosOfWm = 10; 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.Png); imgPhoto.Dispose(); imgWatermark.Dispose(); }
/// <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(); } }
private static void DrawTilesInTileLayer(Graphics g, TmxMap tmxMap, TmxLayer layer) { // Set the opacity for the layer (Not supported on Mac builds) #if !TILED2UNITY_MAC ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.Matrix33 = layer.Opacity; ImageAttributes imageAttributes = new ImageAttributes(); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); #endif // The range of x and y depends on the render order of the tiles // By default we draw right and down but may reverse the tiles we visit var range_x = Enumerable.Range(0, GetMaxTilesWide(layer)); var range_y = Enumerable.Range(0, GetMaxTilesHigh(layer)); if (tmxMap.DrawOrderHorizontal == -1) { range_x = range_x.Reverse(); } if (tmxMap.DrawOrderVertical == -1) { range_y = range_y.Reverse(); } // Visit the tiles we are going to draw var tiles = from y in range_y from x in range_x let rawTileId = layer.GetRawTileIdAt(x, y) let tileId = layer.GetTileIdAt(x, y) where tileId != 0 let tile = tmxMap.Tiles[tileId] // Support for animated tiles. Just show the first frame of the animation. let frame = tmxMap.Tiles[tile.Animation.Frames[0].GlobalTileId] select new { Tile = frame, Position = TmxMath.TileCornerInScreenCoordinates(tmxMap, x, y), Bitmap = frame.TmxImage.ImageBitmap, IsFlippedDiagnoally = TmxMath.IsTileFlippedDiagonally(rawTileId), IsFlippedHorizontally = TmxMath.IsTileFlippedHorizontally(rawTileId), IsFlippedVertically = TmxMath.IsTileFlippedVertically(rawTileId), }; PointF[] destPoints = new PointF[4]; PointF[] destPoints3 = new PointF[3]; foreach (var t in tiles) { PointF location = t.Position; // Individual tiles may be larger than the given tile size of the overall map location.Y = (t.Position.Y - t.Tile.TileSize.Height) + tmxMap.TileHeight; // Take tile offset into account location.X += t.Tile.Offset.X; location.Y += t.Tile.Offset.Y; // Make up the 'quad' of texture points and transform them PointF center = new PointF(t.Tile.TileSize.Width * 0.5f, t.Tile.TileSize.Height * 0.5f); destPoints[0] = new Point(0, 0); destPoints[1] = new Point(t.Tile.TileSize.Width, 0); destPoints[2] = new Point(t.Tile.TileSize.Width, t.Tile.TileSize.Height); destPoints[3] = new Point(0, t.Tile.TileSize.Height); // Transform the points based on our flipped flags TmxMath.TransformPoints(destPoints, center, t.IsFlippedDiagnoally, t.IsFlippedHorizontally, t.IsFlippedVertically); // Put the destination points back into world space TmxMath.TranslatePoints(destPoints, location); // Stupid DrawImage function only takes 3 destination points otherwise it throws an exception destPoints3[0] = destPoints[0]; destPoints3[1] = destPoints[1]; destPoints3[2] = destPoints[3]; // Draw the tile Rectangle source = new Rectangle(t.Tile.LocationOnSource, t.Tile.TileSize); #if !TILED2UNITY_MAC g.DrawImage(t.Bitmap, destPoints3, source, GraphicsUnit.Pixel, imageAttributes); #else g.DrawImage(t.Bitmap, destPoints3, source, GraphicsUnit.Pixel); #endif } }
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(); }
/// <summary> /// Processes the image. /// </summary> /// <param name="source">The current image to process</param> /// <param name="destination">The new Image to return</param> /// <returns> /// The processed <see cref="System.Drawing.Bitmap"/>. /// </returns> public override Bitmap TransformImage(Image source, Image destination) { // Bitmaps for comic pattern Bitmap highBitmap = null; Bitmap lowBitmap = null; Bitmap patternBitmap = null; Bitmap edgeBitmap = null; int width = source.Width; int height = source.Height; try { using (var attributes = new ImageAttributes()) { var rectangle = new Rectangle(0, 0, source.Width, source.Height); attributes.SetColorMatrix(ColorMatrixes.ComicHigh); // Draw the image with the high comic colormatrix. highBitmap = new Bitmap(rectangle.Width, rectangle.Height, PixelFormat.Format32bppPArgb); highBitmap.SetResolution(source.HorizontalResolution, source.VerticalResolution); // Apply a oil painting filter to the image. highBitmap = new OilPaintingFilter(3, 5).ApplyFilter((Bitmap)source); // Draw the edges. edgeBitmap = new Bitmap(width, height, PixelFormat.Format32bppPArgb); edgeBitmap.SetResolution(source.HorizontalResolution, source.VerticalResolution); edgeBitmap = Effects.Trace(source, edgeBitmap, 120); using (var graphics = Graphics.FromImage(highBitmap)) { graphics.DrawImage(highBitmap, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); } // Create a bitmap for overlaying. lowBitmap = new Bitmap(rectangle.Width, rectangle.Height, PixelFormat.Format32bppPArgb); lowBitmap.SetResolution(source.HorizontalResolution, source.VerticalResolution); // Set the color matrix attributes.SetColorMatrix(this.Matrix); // Draw the image with the losatch colormatrix. using (var graphics = Graphics.FromImage(lowBitmap)) { graphics.DrawImage(highBitmap, rectangle, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, attributes); } // We need to create a new image now with a pattern mask to paint it // onto the other image with. patternBitmap = new Bitmap(rectangle.Width, rectangle.Height, PixelFormat.Format32bppPArgb); patternBitmap.SetResolution(source.HorizontalResolution, source.VerticalResolution); // Create the pattern mask. using (var graphics = Graphics.FromImage(patternBitmap)) { graphics.Clear(Color.Transparent); for (int y = 0; y < height; y += 8) { for (int x = 0; x < width; x += 4) { graphics.FillEllipse(Brushes.White, x, y, 3, 3); graphics.FillEllipse(Brushes.White, x + 2, y + 4, 3, 3); } } } // Transfer the alpha channel from the mask to the low saturation image. lowBitmap = Effects.ApplyMask(lowBitmap, patternBitmap); using (var graphics = Graphics.FromImage(destination)) { graphics.Clear(Color.Transparent); // Overlay the image. graphics.DrawImage(highBitmap, 0, 0); graphics.DrawImage(lowBitmap, 0, 0); graphics.DrawImage(edgeBitmap, 0, 0); // Draw an edge around the image. using (var blackPen = new Pen(Color.Black)) { blackPen.Width = 4; graphics.DrawRectangle(blackPen, rectangle); } // Dispose of the other images highBitmap.Dispose(); lowBitmap.Dispose(); patternBitmap.Dispose(); edgeBitmap.Dispose(); } } // Reassign the image. source.Dispose(); source = destination; } catch { destination?.Dispose(); highBitmap?.Dispose(); lowBitmap?.Dispose(); patternBitmap?.Dispose(); edgeBitmap?.Dispose(); } return((Bitmap)source); }
/// <summary> /// 生成图片水印 /// </summary> /// <param name="originalPath">源图路径</param> /// <param name="watermarkPath">水印图片路径</param> /// <param name="targetPath">保存路径</param> /// <param name="position">位置</param> /// <param name="opacity">透明度</param> /// <param name="quality">质量</param> public static void GenerateImageWatermark(string originalPath, string watermarkPath, string targetPath, int position, int opacity, int quality) { Image originalImage = null; Image watermarkImage = null; //图片属性 ImageAttributes attributes = null; //画板 Graphics g = null; try { originalImage = Image.FromFile(originalPath); watermarkImage = new Bitmap(watermarkPath); if (watermarkImage.Height >= originalImage.Height || watermarkImage.Width >= originalImage.Width) { originalImage.Save(targetPath); return; } if (quality < 0 || quality > 100) { quality = 80; } //水印透明度 float iii; if (opacity > 0 && opacity <= 10) { iii = (float)(opacity / 10.0F); } else { iii = 0.5F; } //水印位置 int x = 0; int y = 0; switch (position) { case 1: x = (int)(originalImage.Width * (float).01); y = (int)(originalImage.Height * (float).01); break; case 2: x = (int)((originalImage.Width * (float).50) - (watermarkImage.Width / 2)); y = (int)(originalImage.Height * (float).01); break; case 3: x = (int)((originalImage.Width * (float).99) - (watermarkImage.Width)); y = (int)(originalImage.Height * (float).01); break; case 4: x = (int)(originalImage.Width * (float).01); y = (int)((originalImage.Height * (float).50) - (watermarkImage.Height / 2)); break; case 5: x = (int)((originalImage.Width * (float).50) - (watermarkImage.Width / 2)); y = (int)((originalImage.Height * (float).50) - (watermarkImage.Height / 2)); break; case 6: x = (int)((originalImage.Width * (float).99) - (watermarkImage.Width)); y = (int)((originalImage.Height * (float).50) - (watermarkImage.Height / 2)); break; case 7: x = (int)(originalImage.Width * (float).01); y = (int)((originalImage.Height * (float).99) - watermarkImage.Height); break; case 8: x = (int)((originalImage.Width * (float).50) - (watermarkImage.Width / 2)); y = (int)((originalImage.Height * (float).99) - watermarkImage.Height); break; case 9: x = (int)((originalImage.Width * (float).99) - (watermarkImage.Width)); y = (int)((originalImage.Height * (float).99) - watermarkImage.Height); break; } //颜色映射表 ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] newColorMap = { colorMap }; //颜色变换矩阵,iii是设置透明度的范围0到1中的单精度类型 float[][] newColorMatrix = { 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, iii, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; //定义一个 5 x 5 矩阵 ColorMatrix matrix = new ColorMatrix(newColorMatrix); //图片属性 attributes = new ImageAttributes(); attributes.SetRemapTable(newColorMap, ColorAdjustType.Bitmap); attributes.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); //画板 g = Graphics.FromImage(originalImage); //绘制水印 g.DrawImage(watermarkImage, new Rectangle(x, y, watermarkImage.Width, watermarkImage.Height), 0, 0, watermarkImage.Width, watermarkImage.Height, GraphicsUnit.Pixel, attributes); //保存图片 EncoderParameters encoderParams = new EncoderParameters(); encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, new long[] { quality }); if (GetJPEGCodec() != null) { originalImage.Save(targetPath, _jpegcodec, encoderParams); } else { originalImage.Save(targetPath); } } catch (Exception ex) { throw ex; } finally { if (g != null) { g.Dispose(); } if (attributes != null) { attributes.Dispose(); } if (watermarkImage != null) { watermarkImage.Dispose(); } if (originalImage != null) { originalImage.Dispose(); } } }
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 ); }