public void ElementsTest1() { ColorMatrix m1 = ColorMatrix.Identity; ColorMatrix m2 = new ColorMatrix(0.5, 0.5, 0.5, 1, 0, 0, 0, 0); Assert.Equal(5, m1.RowCount); Assert.Equal(5, m2.ColumnCount); DoubleComponent[][] expected = new DoubleComponent[][] { new DoubleComponent[] {0.5, 0, 0, 0, 0}, new DoubleComponent[] {0, 0.5, 0, 0, 0}, new DoubleComponent[] {0, 0, 0.5, 0, 0}, new DoubleComponent[] {0, 0, 0, 1, 0}, new DoubleComponent[] {0, 0, 0, 0, 1} }; //DoubleComponent[][] actual = m2.Elements; Assert.Equal(expected[0][0], m2[0, 0]); Assert.Equal(expected[0][1], m2[0, 1]); Assert.Equal(expected[0][2], m2[0, 2]); Assert.Equal(expected[1][0], m2[1, 0]); Assert.Equal(expected[1][1], m2[1, 1]); Assert.Equal(expected[1][2], m2[1, 2]); Assert.Equal(expected[2][0], m2[2, 0]); Assert.Equal(expected[2][1], m2[2, 1]); Assert.Equal(expected[2][2], m2[2, 2]); //m1.Elements = expected; m1 = new ColorMatrix(new Matrix(MatrixFormat.RowMajor, expected)); Assert.Equal(m1, m2); Assert.True(m1.Equals(m2 as IMatrix<DoubleComponent>)); }
public void ElementsTest1() { ColorMatrix m1 = ColorMatrix.Identity; ColorMatrix m2 = new ColorMatrix(0.5, 0.5, 0.5, 1, 0, 0, 0); Assert.AreEqual(5, m1.RowCount); Assert.AreEqual(5, m2.ColumnCount); DoubleComponent[][] expected = new DoubleComponent[][] { new DoubleComponent[] { 0.5, 0, 0, 0, 0 }, new DoubleComponent[] { 0, 0.5, 0, 0, 0 }, new DoubleComponent[] { 0, 0, 0.5, 0, 0 }, new DoubleComponent[] { 0, 0, 0, 1, 0 }, new DoubleComponent[] { 0, 0, 0, 0, 1 } }; DoubleComponent[][] actual = m2.Elements; Assert.AreEqual(expected[0][0], actual[0][0]); Assert.AreEqual(expected[0][1], actual[0][1]); Assert.AreEqual(expected[0][2], actual[0][2]); Assert.AreEqual(expected[1][0], actual[1][0]); Assert.AreEqual(expected[1][1], actual[1][1]); Assert.AreEqual(expected[1][2], actual[1][2]); Assert.AreEqual(expected[2][0], actual[2][0]); Assert.AreEqual(expected[2][1], actual[2][1]); Assert.AreEqual(expected[2][2], actual[2][2]); m1.Elements = expected; Assert.AreEqual(m1, m2); Assert.IsTrue(m1.Equals(m2 as IMatrix<DoubleComponent>)); }
//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); }
public void ResetTest() { ColorMatrix m1 = new ColorMatrix(1, 1, 1, 1, 0, 0, 0, 0); m1.Reset(); Assert.Equal(m1, ColorMatrix.Identity); }
public static Bitmap AdjustBrightness(this Bitmap Image, int Value) { float FinalValue = (float)Value / 255.0f; ColorMatrix TempMatrix = new ColorMatrix(); TempMatrix.Matrix = new float[][]{ 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[] {FinalValue, FinalValue, FinalValue, 1, 1} }; return TempMatrix.Apply(Image); }
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); }
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 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 void InvertTest() { ColorMatrix m1 = new ColorMatrix(0.5, 0.5, 0.5, 0.5, 10, 20, 30); IMatrix<DoubleComponent> expected = new Matrix<DoubleComponent>(MatrixFormat.RowMajor, new DoubleComponent[][] { new DoubleComponent[] {2, 0, 0, 0, 0}, new DoubleComponent[] {0, 2, 0, 0, 0}, new DoubleComponent[] {0, 0, 2, 0, 0}, new DoubleComponent[] {0, 0, 0, 2, 0}, new DoubleComponent[] {-20, -40, -60, 0, 1} }); IMatrix<DoubleComponent> m1Inverse = m1.Inverse; for (int i = 0; i < m1.RowCount; i++) { for (int j = 0; j < m1.ColumnCount; j++) { Assert.AreEqual((double)expected[i, j], (double)m1Inverse[i, j], _e); } } }
public void InvertTest() { ColorMatrix m1 = new ColorMatrix(0.5, 0.5, 0.5, 0.5, 10, 20, 30, 0); IMatrix<DoubleComponent> expected = new Matrix(MatrixFormat.RowMajor, new DoubleComponent[][] { new DoubleComponent[] {2, 0, 0, 0, 0}, new DoubleComponent[] {0, 2, 0, 0, 0}, new DoubleComponent[] {0, 0, 2, 0, 0}, new DoubleComponent[] {0, 0, 0, 2, 0}, new DoubleComponent[] {-20, -40, -60, 0, 1} }); IMatrix<DoubleComponent> m1Inverse = m1.Inverse; for (Int32 i = 0; i < m1.RowCount; i++) { for (Int32 j = 0; j < m1.ColumnCount; j++) { Assert.Equal<Double>((Double)expected[i, j], (Double)m1Inverse[i, j], EpsilonComparer.Default); } } }
/// <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(); }
private IEnumerable <Wait> RoutineSlap(Creature user, Creature target) { var offset = Util.AngleToVector(Random.NextFloat() * MathHelper.TwoPi) * (40 + Random.Next(30)); var bullet = new BulletSpeed(user.World, SpriteLoader.Instance.AddSprite("content/highspeed"), target.VisualTarget + offset, ColorMatrix.Tint(Color.Black), 6); bullet.Move(target.VisualTarget, 6); yield return(new WaitBullet(bullet)); user.Attack(target, Vector2.Zero, AttackSlap); }
public override IEnumerable <Wait> RoutineUse(Creature user, object target) { Wallhach wallhach = user as Wallhach; if (target is Creature targetCreature) { Consume(); ShowSkill(user); var chirality = user.GetStatusEffect <Chirality>(); chirality?.AddBuildup(-8); if (wallhach != null) { yield return(Scheduler.Instance.RunAndWait(wallhach.RoutineOpenWing(0.6f, 50, LerpHelper.Quadratic))); } user.VisualPose = user.FlickPose(CreaturePose.Cast, CreaturePose.Stand, 70); if (wallhach != null) { Scheduler.Instance.Run(wallhach.RoutineFlashWing(15)); } yield return(user.WaitSome(10)); int chiralStacks = user.GetStatusStacks <Chirality>(); List <Wait> waits = new List <Wait>(); int hands = chiralStacks + 1; hands = 16; int timeLeft = hands + 90; for (int i = 0; i < hands; i++) { List <Vector2> wingPositions = Wallhach.GetWingPositions(user.VisualTarget, 1.0f); Vector2 velocity = Util.AngleToVector(Random.NextFloat() * MathHelper.TwoPi) * 160; Vector2 emitPos = wingPositions.Pick(Random); var bullet = new MissileHand(user.World, emitPos, targetCreature.VisualTarget, velocity, ColorMatrix.Tint(Color.Goldenrod), 60, timeLeft - i); waits.Add(new WaitBullet(bullet)); yield return(user.WaitSome(1)); } yield return(new WaitAll(waits)); targetCreature.AddStatusEffect(new Wedlock(user) { Duration = new Slider(float.PositiveInfinity), Buildup = 1.0, }); if (wallhach != null) { Scheduler.Instance.Run(wallhach.RoutineOpenWing(1f, 50, LerpHelper.Linear)); } yield return(user.WaitSome(50)); } }
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); }
public void DrawImageAlpha(float alpha, AbstractImage mimage, RectangleF targetRect) { // Clamp and Quantize alpha = Util.Clamp(alpha, 0f, 1f); alpha = (float)Math.Round(alpha * 16f) / 16f; if (alpha <= 0f) { return; } if (alpha >= 1f) { g.DrawImage(mimage.XImage, targetRect); return; } int key = (int)Math.Round(alpha * 16); Image image = mimage.Image; XImage ximage; int w, h; lock (image) { w = image.Width; h = image.Height; if (image.Tag == null || !(image.Tag is Dictionary <int, XImage>)) { image.Tag = new Dictionary <int, XImage>(); } Dictionary <int, XImage> dict = image.Tag as Dictionary <int, XImage>; if (dict.ContainsKey(key)) { ximage = dict[key]; } else { // Need to construct a new image (PdfSharp can't alpha-render images) // Memoize these in the image itself, since most requests will be from // a small set Bitmap scratchBitmap = new Bitmap(w, h, PixelFormat.Format32bppArgb); using (var scratchGraphics = Graphics.FromImage(scratchBitmap)) { ColorMatrix matrix = new ColorMatrix(); matrix.Matrix00 = matrix.Matrix11 = matrix.Matrix22 = 1; matrix.Matrix33 = alpha; ImageAttributes attr = new ImageAttributes(); attr.SetColorMatrix(matrix); scratchGraphics.DrawImage(image, new Rectangle(0, 0, w, h), 0, 0, w, h, GraphicsUnit.Pixel, attr); } ximage = XImage.FromGdiPlusImage(scratchBitmap); dict[key] = ximage; } } lock (ximage) { g.DrawImage(ximage, targetRect); } }
private float _alpha = 0.3f; //default /// <summary> /// Executes this filter on the input image and returns the image with the WaterMark /// </summary> /// <param name="source">input image</param> /// <returns>transformed image</returns> /// <example> /// <code> /// Image transformed; /// ImageWatermarkFilter imageWaterMark = new ImageWatermarkFilter(); /// imageWaterMark.Valign = ImageWatermarkFilter.VAlign.Right; /// imageWaterMark.Halign = ImageWatermarkFilter.HAlign.Bottom; /// imageWaterMark.WaterMarkImage = Image.FromFile("Images/pacman.gif"); /// transformed = imageWaterMark.ExecuteFilter(myImg); /// </code> /// </example> public override Image ExecuteFilter(Image source) { _height = source.Height; _width = source.Width; Bitmap bmWatermark = new Bitmap(source); bmWatermark.SetResolution(source.HorizontalResolution, source.VerticalResolution); //Load this Bitmap into a new Graphic Object Graphics grWatermark = Graphics.FromImage(bmWatermark); //To achieve a transulcent watermark we will apply (2) color //manipulations by defineing a ImageAttributes object and //seting (2) of its properties. ImageAttributes imageAttributes = new ImageAttributes(); //The first step in manipulating the watermark image is to replace //the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0) //to do this we will use a Colormap and use this to define a RemapTable ColorMap colorMap = new ColorMap(); //My watermark was defined with a background of 100% Green this will //be the color we search for and replace with transparency colorMap.OldColor = TransparentColor; colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); //The second color manipulation is used to change the opacity of the //watermark. This is done by applying a 5x5 matrix that contains the //coordinates for the RGBA space. By setting the 3rd row and 3rd column //to 0.3f we achive a level of opacity float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, _alpha, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); //For this example we will place the watermark in the upper right //hand corner of the photograph. offset down 10 pixels and to the //left 10 pixles float xPosOfWm;// = ((rawImage.Width - _waterMarkImage.Width) - 2); float yPosOfWm; CalcDrawPosition(WaterMarkImage.Width, WaterMarkImage.Height, 0, out yPosOfWm, out xPosOfWm); grWatermark.DrawImage(WaterMarkImage, new Rectangle((int)xPosOfWm, (int)yPosOfWm, WaterMarkImage.Width, WaterMarkImage.Height), //Set the detination Position 0, // x-coordinate of the portion of the source image to draw. 0, // y-coordinate of the portion of the source image to draw. WaterMarkImage.Width, // Watermark Width WaterMarkImage.Height, // Watermark Height GraphicsUnit.Pixel, // Unit of measurment imageAttributes); //ImageAttributes Object //Replace the original photgraphs bitmap with the new Bitmap //imgPhoto = bmWatermark; //grWatermark.Dispose(); //save new image to file system. return(bmWatermark); // bmPhoto; }
public override void Render(GdiGraphicsRenderer renderer) { base.Render(renderer); var graphics = renderer.GdiGraphics; SvgImageElement iElement = (SvgImageElement)_svgElement; ImageAttributes imageAttributes = new ImageAttributes(); float opacityValue = -1; string opacity = iElement.GetAttribute("opacity"); if (string.IsNullOrWhiteSpace(opacity)) { opacity = iElement.GetPropertyValue("opacity"); } if (!string.IsNullOrWhiteSpace(opacity)) { opacityValue = (float)SvgNumber.ParseNumber(opacity); opacityValue = Math.Min(opacityValue, 1); opacityValue = Math.Max(opacityValue, 0); } if (opacityValue >= 0 && opacityValue < 1) { ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.Matrix00 = 1.00f; // Red colorMatrix.Matrix11 = 1.00f; // Green colorMatrix.Matrix22 = 1.00f; // Blue colorMatrix.Matrix33 = opacityValue; // alpha colorMatrix.Matrix44 = 1.00f; // w imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); } float width = (float)iElement.Width.AnimVal.Value; float height = (float)iElement.Height.AnimVal.Value; RectangleF destRect = new RectangleF((float)iElement.X.AnimVal.Value, (float)iElement.Y.AnimVal.Value, (float)iElement.Width.AnimVal.Value, (float)iElement.Height.AnimVal.Value); RectangleF srcRect; RectangleF clipRect = destRect; // var container = graphics.BeginContainer(); graphics.SetClip(new Region(clipRect), CombineMode.Intersect); Image image = null; SvgWindow svgWnd = null; if (iElement.IsSvgImage) { svgWnd = GetSvgWindow(graphics); if (width > 0 && height > 0) { srcRect = new RectangleF(0, 0, width, height); } else { SvgSvgElement svgEl = (SvgSvgElement)svgWnd.Document.RootElement; SvgSizeF size = svgEl.GetSize(); srcRect = new RectangleF(new PointF(0, 0), new SizeF(size.Width, size.Height)); } } else { image = GetBitmap(iElement); if (image == null) { return; } srcRect = new RectangleF(0, 0, image.Width, image.Height); } ISvgAnimatedPreserveAspectRatio animatedAspectRatio = iElement.PreserveAspectRatio; if (animatedAspectRatio != null && animatedAspectRatio.AnimVal != null) { SvgPreserveAspectRatio aspectRatio = animatedAspectRatio.AnimVal as SvgPreserveAspectRatio; SvgPreserveAspectRatioType aspectRatioType = (aspectRatio != null) ? aspectRatio.Align : SvgPreserveAspectRatioType.Unknown; if (aspectRatio != null && aspectRatioType != SvgPreserveAspectRatioType.None && aspectRatioType != SvgPreserveAspectRatioType.Unknown) { var fScaleX = destRect.Width / srcRect.Width; var fScaleY = destRect.Height / srcRect.Height; var xOffset = 0.0f; var yOffset = 0.0f; SvgMeetOrSlice meetOrSlice = aspectRatio.MeetOrSlice; if (meetOrSlice == SvgMeetOrSlice.Slice) { fScaleX = Math.Max(fScaleX, fScaleY); fScaleY = Math.Max(fScaleX, fScaleY); } else { fScaleX = Math.Min(fScaleX, fScaleY); fScaleY = Math.Min(fScaleX, fScaleY); } switch (aspectRatioType) { case SvgPreserveAspectRatioType.XMinYMin: break; case SvgPreserveAspectRatioType.XMidYMin: xOffset = (destRect.Width - srcRect.Width * fScaleX) / 2; break; case SvgPreserveAspectRatioType.XMaxYMin: xOffset = (destRect.Width - srcRect.Width * fScaleX); break; case SvgPreserveAspectRatioType.XMinYMid: yOffset = (destRect.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatioType.XMidYMid: xOffset = (destRect.Width - srcRect.Width * fScaleX) / 2; yOffset = (destRect.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatioType.XMaxYMid: xOffset = (destRect.Width - srcRect.Width * fScaleX); yOffset = (destRect.Height - srcRect.Height * fScaleY) / 2; break; case SvgPreserveAspectRatioType.XMinYMax: yOffset = (destRect.Height - srcRect.Height * fScaleY); break; case SvgPreserveAspectRatioType.XMidYMax: xOffset = (destRect.Width - srcRect.Width * fScaleX) / 2; yOffset = (destRect.Height - srcRect.Height * fScaleY); break; case SvgPreserveAspectRatioType.XMaxYMax: xOffset = (destRect.Width - srcRect.Width * fScaleX); yOffset = (destRect.Height - srcRect.Height * fScaleY); break; } destRect = new RectangleF(destRect.X + xOffset, destRect.Y + yOffset, srcRect.Width * fScaleX, srcRect.Height * fScaleY); } if (image != null) { SvgColorProfileElement colorProfile = (SvgColorProfileElement)iElement.ColorProfile; if (colorProfile != null) { SvgUriReference svgUri = colorProfile.UriReference; Uri profileUri = new Uri(svgUri.AbsoluteUri); imageAttributes.SetOutputChannelColorProfile(profileUri.LocalPath, ColorAdjustType.Default); } graphics.DrawImage(this, image, destRect, srcRect, GraphicsUnit.Pixel, imageAttributes); image.Dispose(); image = null; } else if (iElement.IsSvgImage && svgWnd != null) { svgWnd.Resize((int)srcRect.Width, (int)srcRect.Height); var currOffset = new PointF(graphics.Transform.OffsetX, graphics.Transform.OffsetY); if (!currOffset.IsEmpty) { graphics.TranslateTransform(-currOffset.X, -currOffset.Y); } graphics.ScaleTransform(destRect.Width / srcRect.Width, destRect.Height / srcRect.Height); if (!currOffset.IsEmpty) { graphics.TranslateTransform(currOffset.X + destRect.X, currOffset.Y + destRect.Y); } _embeddedRenderer.Render(svgWnd.Document); } graphics.ResetClip(); // graphics.EndContainer(container); } if (_embeddedRenderer != null) { _embeddedRenderer.GdiGraphics = null; _embeddedRenderer.Dispose(); _embeddedRenderer = null; } if (imageAttributes != null) { imageAttributes.Dispose(); imageAttributes = null; } }
public System.IO.MemoryStream AddImageSignPic(Image img, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) { Graphics graphics = null; Image image = null; ImageAttributes imageAttributes = null; System.IO.MemoryStream result; try { graphics = Graphics.FromImage(img); image = new Bitmap(watermarkFilename); imageAttributes = new ImageAttributes(); ColorMap[] map = new ColorMap[] { new ColorMap { OldColor = Color.FromArgb(255, 0, 255, 0), NewColor = Color.FromArgb(0, 0, 0, 0) } }; imageAttributes.SetRemapTable(map, ColorAdjustType.Bitmap); float num = 0.5f; if (watermarkTransparency >= 1 && watermarkTransparency <= 10) { num = (float)watermarkTransparency / 10f; } float[][] array = new float[5][]; float[][] arg_A1_0 = array; int arg_A1_1 = 0; float[] array2 = new float[5]; array2[0] = 1f; arg_A1_0[arg_A1_1] = array2; float[][] arg_B8_0 = array; int arg_B8_1 = 1; float[] array3 = new float[5]; array3[1] = 1f; arg_B8_0[arg_B8_1] = array3; float[][] arg_CF_0 = array; int arg_CF_1 = 2; float[] array4 = new float[5]; array4[2] = 1f; arg_CF_0[arg_CF_1] = array4; float[][] arg_E3_0 = array; int arg_E3_1 = 3; float[] array5 = new float[5]; array5[3] = num; arg_E3_0[arg_E3_1] = array5; array[4] = new float[] { 0f, 0f, 0f, 0f, 1f }; float[][] newColorMatrix = array; ColorMatrix newColorMatrix2 = new ColorMatrix(newColorMatrix); imageAttributes.SetColorMatrix(newColorMatrix2, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); int x = 0; int y = 0; switch (watermarkStatus) { case 1: x = (int)((float)img.Width * 0.01f); y = (int)((float)img.Height * 0.01f); break; case 2: x = (int)((float)img.Width * 0.5f - (float)(image.Width / 2)); y = (int)((float)img.Height * 0.01f); break; case 3: x = (int)((float)img.Width * 0.99f - (float)image.Width); y = (int)((float)img.Height * 0.01f); break; case 4: x = (int)((float)img.Width * 0.01f); y = (int)((float)img.Height * 0.5f - (float)(image.Height / 2)); break; case 5: x = (int)((float)img.Width * 0.5f - (float)(image.Width / 2)); y = (int)((float)img.Height * 0.5f - (float)(image.Height / 2)); break; case 6: x = (int)((float)img.Width * 0.99f - (float)image.Width); y = (int)((float)img.Height * 0.5f - (float)(image.Height / 2)); break; case 7: x = (int)((float)img.Width * 0.01f); y = (int)((float)img.Height * 0.99f - (float)image.Height); break; case 8: x = (int)((float)img.Width * 0.5f - (float)(image.Width / 2)); y = (int)((float)img.Height * 0.99f - (float)image.Height); break; case 9: x = (int)((float)img.Width * 0.99f - (float)image.Width); y = (int)((float)img.Height * 0.99f - (float)image.Height); break; } graphics.DrawImage(image, new Rectangle(x, y, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes); ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo imageCodecInfo = null; ImageCodecInfo[] array6 = imageEncoders; for (int i = 0; i < array6.Length; i++) { ImageCodecInfo imageCodecInfo2 = array6[i]; if (imageCodecInfo2.MimeType.IndexOf("jpeg") > -1) { imageCodecInfo = imageCodecInfo2; } } EncoderParameters encoderParameters = new EncoderParameters(); long[] array7 = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } array7[0] = (long)quality; EncoderParameter encoderParameter = new EncoderParameter(Encoder.Quality, array7); encoderParameters.Param[0] = encoderParameter; System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); if (imageCodecInfo != null) { img.Save(memoryStream, imageCodecInfo, encoderParameters); } result = memoryStream; } catch { System.IO.MemoryStream memoryStream = null; result = memoryStream; } finally { if (graphics != null) { graphics.Dispose(); } if (img != null) { img.Dispose(); } if (image != null) { image.Dispose(); } if (imageAttributes != null) { imageAttributes.Dispose(); } } return(result); }
public static string ConvertImage(Stream stream, string ImageSize, string Quick) { StringBuilder _asciiart = new StringBuilder(); #region load image Image _img = Image.FromStream(stream); Bitmap _image = new Bitmap(_img, new Size(_img.Width, _img.Height)); _img.Dispose(); Rectangle bounds = new Rectangle(0, 0, _image.Width, _image.Height); #endregion #region greyscale image ColorMatrix _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; ImageAttributes _attributes = new ImageAttributes(); _attributes.SetColorMatrix(_matrix); Graphics gphGrey = Graphics.FromImage(_image); gphGrey.DrawImage(_image, bounds, 0, 0, _image.Width, _image.Height, GraphicsUnit.Pixel, _attributes); gphGrey.Dispose(); #endregion #region ascii image int _pixwidth; switch (ImageSize) { case "1": { _pixwidth = 1; break; } case "2": { _pixwidth = 2; break; } case "4": { _pixwidth = 6; break; } case "5": { _pixwidth = 8; break; } default: { _pixwidth = 3; break; } } int _pixhight = _pixwidth * 2; int _pixseg = _pixwidth * _pixhight; for (int h = 0; h < _image.Height / _pixhight; h++) { // segment hight int _startY = (h * _pixhight); // segment width for (int w = 0; w < _image.Width / _pixwidth; w++) { int _startX = (w * _pixwidth); int _allBrightness = 0; if (Quick == "True") { // each pix of this segment for (int y = 0; y < _pixwidth; y++) { try { Color _c = _image.GetPixel(_startX, y + _startY); int _b = (int)(_c.GetBrightness() * 100); _allBrightness = _allBrightness + _b; } catch { _allBrightness = (_allBrightness + 50); } } } else { // each pix of this segment for (int y = 0; y < _pixwidth; y++) { for (int x = 0; x < _pixhight; x++) { int _cY = y + _startY; int _cX = x + _startX; try { Color _c = _image.GetPixel(_cX, _cY); int _b = (int)(_c.GetBrightness() * 100); _allBrightness = _allBrightness + _b; } catch { _allBrightness = (_allBrightness + 50); } } } } int _sb = (_allBrightness / _pixseg); if (_sb < 10) { _asciiart.Append("#"); } else if (_sb < 17) { _asciiart.Append("@"); } else if (_sb < 24) { _asciiart.Append("&"); } else if (_sb < 31) { _asciiart.Append("$"); } else if (_sb < 38) { _asciiart.Append("%"); } else if (_sb < 45) { _asciiart.Append("|"); } else if (_sb < 52) { _asciiart.Append("!"); } else if (_sb < 59) { _asciiart.Append(";"); } else if (_sb < 66) { _asciiart.Append(":"); } else if (_sb < 73) { _asciiart.Append("'"); } else if (_sb < 80) { _asciiart.Append("`"); } else if (_sb < 87) { _asciiart.Append("."); } else { _asciiart.Append(" "); } } _asciiart.Append("\n"); } #endregion //clean up _image.Dispose(); return(_asciiart.ToString()); }
/// <summary> /// Creating a Watermarked Photograph with GDI+ for .NET /// </summary> /// <param name="rSrcImgPath">原始图片的物理路径</param> /// <param name="rMarkImgPath">水印图片的物理路径</param> /// <param name="rMarkText">水印文字(不显示水印文字设为空串)</param> /// <param name="rDstImgPath">输出合成后的图片的物理路径</param> public void BuildWatermark(Image rSrcImgPath, string rMarkImgPath, string rMarkText, string rDstImgPath) { //以下(代码)从一个指定文件创建了一个Image 对象,然后为它的 Width 和 Height定义变量。 //这些长度待会被用来建立一个以24 bits 每像素的格式作为颜色数据的Bitmap对象。 Image imgPhoto = rSrcImgPath; int phWidth = imgPhoto.Width; int phHeight = imgPhoto.Height; Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(100, 100); Graphics grPhoto = Graphics.FromImage(bmPhoto); //这个代码载入水印图片,水印图片已经被保存为一个BMP文件,以绿色(A=0,R=0,G=255,B=0)作为背景颜色。 //再一次,会为它的Width 和Height定义一个变量。 Image imgWatermark = new Bitmap(rMarkImgPath); int wmWidth = imgWatermark.Width; int wmHeight = imgWatermark.Height; //这个代码以100%它的原始大小绘制imgPhoto 到Graphics 对象的(x=0,y=0)位置。 //以后所有的绘图都将发生在原来照片的顶部。 grPhoto.SmoothingMode = SmoothingMode.AntiAlias; grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, phWidth, phHeight), 0, 0, phWidth, phHeight, GraphicsUnit.Pixel); //为了最大化版权信息的大小,我们将测试7种不同的字体大小来决定我们能为我们的照片宽度使用的可能的最大大小。 //为了有效地完成这个,我们将定义一个整型数组,接着遍历这些整型值测量不同大小的版权字符串。 //一旦我们决定了可能的最大大小,我们就退出循环,绘制文本 int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 }; Font crFont = null; SizeF crSize = new SizeF(); for (int i = 0; i < 7; i++) { crFont = new Font("arial", sizes[i], FontStyle.Bold); crSize = grPhoto.MeasureString(rMarkText, crFont); if ((ushort)crSize.Width < (ushort)phWidth) { break; } } //因为所有的照片都有各种各样的高度,所以就决定了从图象底部开始的5%的位置开始。 //使用rMarkText字符串的高度来决定绘制字符串合适的Y坐标轴。 //通过计算图像的中心来决定X轴,然后定义一个StringFormat 对象,设置StringAlignment 为Center。 //int yPixlesFromBottom = 100; //(int)(phHeight * .05); float yPosFromBottom = 100;//((phHeight - yPixlesFromBottom) - (crSize.Height / 2)); float xCenterOfImg = (phWidth / 2); StringFormat StrFormat = new StringFormat(); StrFormat.Alignment = StringAlignment.Center; //现在我们已经有了所有所需的位置坐标来使用60%黑色的一个Color(alpha值153)创建一个SolidBrush 。 //在偏离右边1像素,底部1像素的合适位置绘制版权字符串。 //这段偏离将用来创建阴影效果。使用Brush重复这样一个过程,在前一个绘制的文本顶部绘制同样的文本。 SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0)); grPhoto.DrawString(rMarkText, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat); SolidBrush semiTransBrush = new SolidBrush( Color.FromArgb(153, 255, 255, 255)); grPhoto.DrawString(rMarkText, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), StrFormat); //根据前面修改后的照片创建一个Bitmap。把这个Bitmap载入到一个新的Graphic对象。 Bitmap bmWatermark = new Bitmap(bmPhoto); bmWatermark.SetResolution( imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grWatermark = Graphics.FromImage(bmWatermark); //通过定义一个ImageAttributes 对象并设置它的两个属性,我们就是实现了两个颜色的处理,以达到半透明的水印效果。 //处理水印图象的第一步是把背景图案变为透明的(Alpha=0, R=0, G=0, B=0)。我们使用一个Colormap 和定义一个RemapTable来做这个。 //就像前面展示的,我的水印被定义为100%绿色背景,我们将搜到这个颜色,然后取代为透明。 ImageAttributes imageAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; //第二个颜色处理用来改变水印的不透明性。 //通过应用包含提供了坐标的RGBA空间的5x5矩阵来做这个。 //通过设定第三行、第三列为0.3f我们就达到了一个不透明的水平。结果是水印会轻微地显示在图象底下一些。 imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); //随着两个颜色处理加入到imageAttributes 对象,我们现在就能在照片右手边上绘制水印了。 //我们会偏离10像素到底部,10像素到左边。 int markWidth; int markHeight; //mark比原来的图宽 //if (phWidth <= wmWidth) //{ // markWidth = phWidth - 10; // markHeight = (markWidth * wmHeight) / wmWidth; //} //else if (phHeight <= wmHeight) //{ // markHeight = phHeight - 10; // markWidth = (markHeight * wmWidth) / wmHeight; //} //else //{ // markWidth = wmWidth; // markHeight = wmHeight; //} markHeight = phWidth / 6; //wmHeight/2; markWidth = phWidth / 6; //wmWidth/2; int xPosOfWm = phWidth / 2; //((phWidth - markWidth) - 10); int yPosOfWm = phHeight - (phHeight / 3); grWatermark.DrawImage(imgWatermark, new Rectangle(xPosOfWm, yPosOfWm, markWidth, markHeight), 0, 0, wmWidth, wmHeight, GraphicsUnit.Pixel, imageAttributes); //最后的步骤将是使用新的Bitmap取代原来的Image。 销毁两个Graphic对象,然后把Image 保存到文件系统。 imgPhoto = bmWatermark; grPhoto.Dispose(); grWatermark.Dispose(); imgPhoto.Save(rDstImgPath, ImageFormat.Jpeg); imgPhoto.Dispose(); imgWatermark.Dispose(); }
/// <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(); } }
void paint(bool force) { string s = "(no tags yet)"; if (tag != null) { s = tag.tag.tag; } if (!force && s == lastTag && this.Size == lastSize) { return; } lastTag = s; lastSize = this.Size; gTags.Text = s; if (!gPic.Visible) { return; } if (gPic.Image != null) { var old = gPic.Image; gPic.Image = null; old.Dispose(); } // label kerning is busted if non-cleartype, // graphics hinting is busted if non-cleartype, // win by grayscaling cleartype (orz) var brushBG = new SolidBrush(gTags.BackColor); var bmFG = new Bitmap(gPic.Width, gPic.Height, PixelFormat.Format24bppRgb); using (var g = Graphics.FromImage(bmFG)) { setGraphicOptions(g); g.TextRenderingHint = gTags.Hinting; g.TextContrast = 0; // 0..12 var sz = g.MeasureString(s, gTags.Font, gPic.Width); var al = settings.tboxAlign; int margin = 4; var x = -1; if (al == 1 || al == 4 || al == 7) { x = margin; } else if (al == 3 || al == 6 || al == 9) { x = (int)((gPic.Width - margin) - sz.Width); } else { x = (int)((gPic.Width - sz.Width) / 2); } var y = -1; if (al == 1 || al == 2 || al == 3) { y = margin; } else if (al == 7 || al == 8 || al == 9) { y = (int)((gPic.Height - margin) - sz.Height); } else { y = (int)((gPic.Height - sz.Height) / 2); } g.FillRectangle(Brushes.Black, 0, 0, gPic.Width, gPic.Height); g.DrawString(s, gTags.Font, Brushes.White, new RectangleF( x, y, gPic.Width - margin * 2, gPic.Height - margin * 2)); } var bmBG = new Bitmap(gPic.Width, gPic.Height); using (Graphics g = Graphics.FromImage(bmBG)) { setGraphicOptions(g); g.FillRectangle(brushBG, 0, 0, gPic.Width, gPic.Height); float cr = gTags.ForeColor.R / 256f; float cg = gTags.ForeColor.G / 256f; float cb = gTags.ForeColor.B / 256f; var tab = new float[][] { new float[] { 0, 0, 0, .30f, 0 }, new float[] { 0, 0, 0, .59f, 0 }, new float[] { 0, 0, 0, .11f, 0 }, new float[] { 0, 0, 0, 0, 0 }, new float[] { cr, cg, cb, 0, 1 } }; var cm = new ColorMatrix(tab); using (var iattr = new ImageAttributes()) { iattr.SetColorMatrix(cm); g.DrawImage(bmFG, new Rectangle(Point.Empty, gPic.Size), 0, 0, gPic.Width, gPic.Height, GraphicsUnit.Pixel, iattr); } } bmFG.Dispose(); brushBG.Dispose(); gPic.Image = bmBG; }
/// <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> /// 图片水印 /// </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(); }
internal void DrawImage(GaugeGraphics g, bool primary, bool drawShadow) { if (!Visible || (drawShadow && base.ShadowOffset == 0f)) { return; } float width = Width; width = g.GetAbsoluteDimension(width); Image image = null; image = ((!primary) ? Common.ImageLoader.LoadImage(CapImage) : Common.ImageLoader.LoadImage(Image)); if (image.Width == 0 || image.Height == 0) { return; } Point empty = Point.Empty; empty = ((!primary) ? CapImageOrigin : ImageOrigin); if (empty.IsEmpty) { empty.X = image.Width / 2; empty.Y = image.Height / 2; } int num = (image.Height <= image.Width) ? image.Width : image.Height; if (num != 0) { float num2 = (!primary) ? (g.GetAbsoluteDimension(CapWidth * 2f) / (float)num) : (g.GetAbsoluteDimension(Width * 2f) / (float)num); Rectangle rectangle = new Rectangle(0, 0, (int)((float)image.Width * num2), (int)((float)image.Height * num2)); ImageAttributes imageAttributes = new ImageAttributes(); if (primary && ImageTransColor != Color.Empty) { imageAttributes.SetColorKey(ImageTransColor, ImageTransColor, ColorAdjustType.Default); } if (!primary && CapImageTransColor != Color.Empty) { imageAttributes.SetColorKey(CapImageTransColor, CapImageTransColor, ColorAdjustType.Default); } Matrix transform = g.Transform; Matrix matrix = g.Transform.Clone(); float positionFromValue = GetScale().GetPositionFromValue(base.Position); PointF absolutePoint = g.GetAbsolutePoint(GetScale().GetPivotPoint()); PointF pointF = new PointF((float)empty.X * num2, (float)empty.Y * num2); float offsetX = matrix.OffsetX; float offsetY = matrix.OffsetY; matrix.Translate(absolutePoint.X - pointF.X, absolutePoint.Y - pointF.Y, MatrixOrder.Append); absolutePoint.X += offsetX; absolutePoint.Y += offsetY; matrix.RotateAt(positionFromValue, absolutePoint, MatrixOrder.Append); if (drawShadow) { ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.Matrix00 = 0f; colorMatrix.Matrix11 = 0f; colorMatrix.Matrix22 = 0f; colorMatrix.Matrix33 = Common.GaugeCore.ShadowIntensity / 100f; imageAttributes.SetColorMatrix(colorMatrix); matrix.Translate(base.ShadowOffset, base.ShadowOffset, MatrixOrder.Append); } else if (primary && !ImageHueColor.IsEmpty) { Color color = g.TransformHueColor(ImageHueColor); ColorMatrix colorMatrix2 = new ColorMatrix(); colorMatrix2.Matrix00 = (float)(int)color.R / 255f; colorMatrix2.Matrix11 = (float)(int)color.G / 255f; colorMatrix2.Matrix22 = (float)(int)color.B / 255f; imageAttributes.SetColorMatrix(colorMatrix2); } else if (!primary && !CapImageHueColor.IsEmpty) { Color color2 = g.TransformHueColor(CapImageHueColor); ColorMatrix colorMatrix3 = new ColorMatrix(); colorMatrix3.Matrix00 = (float)(int)color2.R / 255f; colorMatrix3.Matrix11 = (float)(int)color2.G / 255f; colorMatrix3.Matrix22 = (float)(int)color2.B / 255f; imageAttributes.SetColorMatrix(colorMatrix3); } g.Transform = matrix; ImageSmoothingState imageSmoothingState = new ImageSmoothingState(g); imageSmoothingState.Set(); g.DrawImage(image, rectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, imageAttributes); imageSmoothingState.Restore(); g.Transform = transform; if (!drawShadow) { matrix.Translate(0f - offsetX, 0f - offsetY, MatrixOrder.Append); GraphicsPath graphicsPath = new GraphicsPath(); graphicsPath.AddRectangle(rectangle); graphicsPath.Transform(matrix); AddHotRegion(graphicsPath, primary); } } }
/// <summary> /// 添加图片水印 /// </summary> /// <param name="sourcePicture">源图片文件名</param> /// <param name="waterImage">水印图片文件名</param> /// <param name="alpha">透明度(0.1-1.0数值越小透明度越高)</param> /// <param name="position">位置</param> /// <param name="PicturePath" >图片的路径</param> /// <returns>返回生成于指定文件夹下的水印文件名</returns> public string DrawImage(string sourcePicture, string waterImage, float alpha, ImagePosition position, string PicturePath) { // // 判断参数是否有效 // if (sourcePicture == string.Empty || waterImage == string.Empty || alpha == 0.0 || PicturePath == string.Empty) { return(sourcePicture); } // // 源图片,水印图片全路径 // string sourcePictureName = PicturePath + sourcePicture; string waterPictureName = PicturePath + waterImage; string fileSourceExtension = System.IO.Path.GetExtension(sourcePictureName).ToLower(); string fileWaterExtension = System.IO.Path.GetExtension(waterPictureName).ToLower(); // // 判断文件是否存在,以及类型是否正确 // if (System.IO.File.Exists(sourcePictureName) == false || System.IO.File.Exists(waterPictureName) == false || ( fileSourceExtension != ".gif" && fileSourceExtension != ".jpg" && fileSourceExtension != ".png") || ( fileWaterExtension != ".gif" && fileWaterExtension != ".jpg" && fileWaterExtension != ".png") ) { return(sourcePicture); } // // 目标图片名称及全路径 // string targetImage = sourcePictureName.Replace(System.IO.Path.GetExtension(sourcePictureName), "") + "_1101.jpg"; // // 将需要加上水印的图片装载到Image对象中 // Image imgPhoto = Image.FromFile(sourcePictureName); // // 确定其长宽 // int phWidth = imgPhoto.Width; int phHeight = imgPhoto.Height; // // 封装 GDI+ 位图,此位图由图形图像及其属性的像素数据组成。 // Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb); // // 设定分辨率 // bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); // // 定义一个绘图画面用来装载位图 // Graphics grPhoto = Graphics.FromImage(bmPhoto); // //同样,由于水印是图片,我们也需要定义一个Image来装载它 // Image imgWatermark = new Bitmap(waterPictureName); // // 获取水印图片的高度和宽度 // int wmWidth = imgWatermark.Width; int wmHeight = imgWatermark.Height; //SmoothingMode:指定是否将平滑处理(消除锯齿)应用于直线、曲线和已填充区域的边缘。 // 成员名称 说明 // AntiAlias 指定消除锯齿的呈现。 // Default 指定不消除锯齿。 // HighQuality 指定高质量、低速度呈现。 // HighSpeed 指定高速度、低质量呈现。 // Invalid 指定一个无效模式。 // None 指定不消除锯齿。 grPhoto.SmoothingMode = SmoothingMode.AntiAlias; // // 第一次描绘,将我们的底图描绘在绘图画面上 // grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, phWidth, phHeight), 0, 0, phWidth, phHeight, GraphicsUnit.Pixel); // // 与底图一样,我们需要一个位图来装载水印图片。并设定其分辨率 // Bitmap bmWatermark = new Bitmap(bmPhoto); bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); // // 继续,将水印图片装载到一个绘图画面grWatermark // Graphics grWatermark = Graphics.FromImage(bmWatermark); // //ImageAttributes 对象包含有关在呈现时如何操作位图和图元文件颜色的信息。 // ImageAttributes imageAttributes = new ImageAttributes(); // //Colormap: 定义转换颜色的映射 // ColorMap colorMap = new ColorMap(); // //我的水印图被定义成拥有绿色背景色的图片被替换成透明 // colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, // red红色 new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, //green绿色 new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, //blue蓝色 new float[] { 0.0f, 0.0f, 0.0f, alpha, 0.0f }, //透明度 new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; // // ColorMatrix:定义包含 RGBA 空间坐标的 5 x 5 矩阵。 // ImageAttributes 类的若干方法通过使用颜色矩阵调整图像颜色。 ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); // //上面设置完颜色,下面开始设置位置 // int xPosOfWm; int yPosOfWm; switch (position) { case ImagePosition.BottomMiddle: xPosOfWm = (phWidth - wmWidth) / 2; yPosOfWm = phHeight - wmHeight - 10; break; case ImagePosition.Center: xPosOfWm = (phWidth - wmWidth) / 2; yPosOfWm = (phHeight - wmHeight) / 2; break; case ImagePosition.LeftBottom: xPosOfWm = 10; yPosOfWm = phHeight - wmHeight - 10; break; case ImagePosition.LeftTop: xPosOfWm = 10; yPosOfWm = 10; break; case ImagePosition.RightTop: xPosOfWm = phWidth - wmWidth - 10; yPosOfWm = 10; break; case ImagePosition.RigthBottom: xPosOfWm = phWidth - wmWidth - 10; yPosOfWm = phHeight - wmHeight - 10; break; case ImagePosition.TopMiddle: xPosOfWm = (phWidth - wmWidth) / 2; yPosOfWm = 10; break; default: xPosOfWm = 10; yPosOfWm = phHeight - wmHeight - 10; break; } // // 第二次绘图,把水印印上去 // grWatermark.DrawImage(imgWatermark, new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight), 0, 0, wmWidth, wmHeight, GraphicsUnit.Pixel, imageAttributes); imgPhoto = bmWatermark; grPhoto.Dispose(); grWatermark.Dispose(); // // 保存文件到服务器的文件夹里面 // imgPhoto.Save(targetImage, ImageFormat.Jpeg); imgPhoto.Dispose(); imgWatermark.Dispose(); return(targetImage.Replace(PicturePath, "")); }
/// <summary> /// 为图片附件图片水印 /// </summary> /// <param name="targetStream">需要打水印的图片流</param> /// <param name="watermarkStream">水印文件的图片流</param> /// <param name="watermarkStatus">图片水印位置 /// 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param> /// <param name="quality">附加水印图片质量,0-100</param> /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param> /// <returns></returns> public static Stream AttachWaterMark(Stream targetStream, Stream watermarkStream, int watermarkStatus = 9, int quality = 80, int watermarkTransparency = 5) { MemoryStream ms = null; if (null == targetStream || null == watermarkStream) { return(ms); } //构造源图对象GDI Image img = Image.FromStream(targetStream); Graphics g = Graphics.FromImage(img); //设置高质量插值法 //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; Image watermark = new Bitmap(watermarkStream); if (watermark.Height >= img.Height || watermark.Width >= img.Width) { return(ms); } ImageAttributes imageAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float transparency = 0.5F; if (watermarkTransparency >= 1 && watermarkTransparency <= 10) { transparency = (watermarkTransparency / 10.0F); } float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, transparency, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); int xpos = 0; int ypos = 0; switch (watermarkStatus) { case 1: xpos = (int)(img.Width * (float).01); ypos = (int)(img.Height * (float).01); break; case 2: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)(img.Height * (float).01); break; case 3: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)(img.Height * (float).01); break; case 4: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 5: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 6: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 7: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 8: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 9: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; default: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; } g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) { ici = codec; } } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) { img.Save(ms, ici, encoderParams); } else { img.Save(ms, img.RawFormat); } g.Dispose(); img.Dispose(); watermark.Dispose(); imageAttributes.Dispose(); ms.Position = 0; return(ms); }
public static void GenerateImageWatermark(string originalPath, string watermarkPath, string targetPath, int position, int opacity, int quality) { float single; Image image = null; Image bitmap = null; ImageAttributes imageAttribute = null; Graphics graphic = null; try { try { image = Image.FromFile(originalPath); bitmap = new Bitmap(watermarkPath); if ((bitmap.Height >= image.Height ? false : bitmap.Width < image.Width)) { if ((quality < 0 ? true : quality > 100)) { quality = 80; } single = ((opacity <= 0 ? true : opacity > 10) ? 0.5f : (float)((float)opacity / 10f)); int width = 0; int height = 0; switch (position) { case 1: { width = (int)((float)image.Width * 0.01f); height = (int)((float)image.Height * 0.01f); break; } case 2: { width = (int)((float)image.Width * 0.5f - (float)(bitmap.Width / 2)); height = (int)((float)image.Height * 0.01f); break; } case 3: { width = (int)((float)image.Width * 0.99f - (float)bitmap.Width); height = (int)((float)image.Height * 0.01f); break; } case 4: { width = (int)((float)image.Width * 0.01f); height = (int)((float)image.Height * 0.5f - (float)(bitmap.Height / 2)); break; } case 5: { width = (int)((float)image.Width * 0.5f - (float)(bitmap.Width / 2)); height = (int)((float)image.Height * 0.5f - (float)(bitmap.Height / 2)); break; } case 6: { width = (int)((float)image.Width * 0.99f - (float)bitmap.Width); height = (int)((float)image.Height * 0.5f - (float)(bitmap.Height / 2)); break; } case 7: { width = (int)((float)image.Width * 0.01f); height = (int)((float)image.Height * 0.99f - (float)bitmap.Height); break; } case 8: { width = (int)((float)image.Width * 0.5f - (float)(bitmap.Width / 2)); height = (int)((float)image.Height * 0.99f - (float)bitmap.Height); break; } case 9: { width = (int)((float)image.Width * 0.99f - (float)bitmap.Width); height = (int)((float)image.Height * 0.99f - (float)bitmap.Height); break; } } ColorMap colorMap = new ColorMap() { OldColor = Color.FromArgb(255, 0, 255, 0), NewColor = Color.FromArgb(0, 0, 0, 0) }; ColorMap[] colorMapArray = new ColorMap[] { colorMap }; float[][] singleArray = new float[5][]; float[] singleArray1 = new float[] { 1f, default(float), default(float), default(float), default(float) }; singleArray[0] = singleArray1; singleArray1 = new float[] { default(float), 1f, default(float), default(float), default(float) }; singleArray[1] = singleArray1; singleArray1 = new float[] { default(float), default(float), 1f, default(float), default(float) }; singleArray[2] = singleArray1; singleArray1 = new float[] { default(float), default(float), default(float), single, default(float) }; singleArray[3] = singleArray1; singleArray1 = new float[] { default(float), default(float), default(float), default(float), 1f }; singleArray[4] = singleArray1; ColorMatrix colorMatrix = new ColorMatrix(singleArray); imageAttribute = new ImageAttributes(); imageAttribute.SetRemapTable(colorMapArray, ColorAdjustType.Bitmap); imageAttribute.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); graphic = Graphics.FromImage(image); graphic.DrawImage(bitmap, new Rectangle(width, height, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel, imageAttribute); EncoderParameters encoderParameter = new EncoderParameters(); EncoderParameter[] param = encoderParameter.Param; Encoder encoder = Encoder.Quality; long[] numArray = new long[] { (long)quality }; param[0] = new EncoderParameter(encoder, numArray); if (ImageHelper.GetJPEGCodec() == null) { image.Save(targetPath); } else { image.Save(targetPath, ImageHelper._jpegcodec, encoderParameter); } } else { image.Save(targetPath); return; } } catch (Exception exception) { throw exception; } } finally { if (graphic != null) { graphic.Dispose(); } if (imageAttribute != null) { imageAttribute.Dispose(); } if (bitmap != null) { bitmap.Dispose(); } if (image != null) { image.Dispose(); } } }
private Bitmap CreateBitmap() { Bitmap bitmap = new Bitmap(_backgroundImage.Width, _backgroundImage.Height, PixelFormat.Format32bppArgb); using (Graphics graphics = Graphics.FromImage(bitmap)) { BidiGraphics g = new BidiGraphics(graphics, bitmap.Size); // draw transparent background image g.DrawImage(false, _backgroundImage, new Rectangle(0, 0, _backgroundImage.Width, _backgroundImage.Height)); // draw logo image g.DrawImage(false, _logoImage, new Rectangle( (ClientSize.Width - _logoImage.Width) / 2, 120 - _logoImage.Height, _logoImage.Width, _logoImage.Height)); // draw copyright notice string splashText = Res.Get(StringId.SplashScreenCopyrightNotice); using (Font font = new Font(Font.FontFamily, 7.5f)) { const int TEXT_PADDING_H = 36; const int TEXT_PADDING_V = 26; int textWidth = Size.Width - 2 * TEXT_PADDING_H; int textHeight = Convert.ToInt32( g.MeasureText(splashText, font, new Size(textWidth, 0), TextFormatFlags.WordBreak).Height, CultureInfo.InvariantCulture); // GDI text can't be drawn on an alpha-blended surface. So we render a black-on-white // bitmap, then use a ColorMatrix to effectively turn it into an alpha mask. using (Bitmap textBitmap = new Bitmap(textWidth, textHeight, PixelFormat.Format32bppRgb)) { using (Graphics tbG = Graphics.FromImage(textBitmap)) { tbG.FillRectangle(Brushes.Black, 0, 0, textWidth, textHeight); new BidiGraphics(tbG, textBitmap.Size). DrawText(splashText, font, new Rectangle(0, 0, textWidth, textHeight), Color.White, Color.Black, TextFormatFlags.WordBreak); } Rectangle textRect = new Rectangle(TEXT_PADDING_H, ClientSize.Height - TEXT_PADDING_V - textHeight, textWidth, textHeight); using (ImageAttributes ia = new ImageAttributes()) { ColorMatrix cm = new ColorMatrix(new float[][] { new float[] { 0, 0, 0, 1f / 3f, 0 }, new float[] { 0, 0, 0, 1f / 3f, 0 }, new float[] { 0, 0, 0, 1f / 3f, 0 }, new float[] { 0, 0, 0, 0, 0 }, new float[] { 0.9372f, 0.9372f, 0.9372f, 0, 0 }, }); ia.SetColorMatrix(cm); g.DrawImage(false, textBitmap, textRect, 0, 0, textWidth, textHeight, GraphicsUnit.Pixel, ia); } } } } return(bitmap); }
/// <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(); }
internal virtual int rotateColor(int color, float rad) { float deg = rad * 180 / 3.1415927f; int r = Color.red(color); int g = Color.green(color); int b = Color.blue(color); ColorMatrix cm = new ColorMatrix(); ColorMatrix tmp = new ColorMatrix(); cm.setRGB2YUV(); tmp.setRotate(0, deg); cm.postConcat(tmp); tmp.setYUV2RGB(); cm.postConcat(tmp); //JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final': //ORIGINAL LINE: final float[] a = cm.getArray(); float[] a = cm.Array; int ir = floatToByte(a[0] * r + a[1] * g + a[2] * b); int ig = floatToByte(a[5] * r + a[6] * g + a[7] * b); int ib = floatToByte(a[10] * r + a[11] * g + a[12] * b); return Color.argb(Color.alpha(color), pinToByte(ir), pinToByte(ig), pinToByte(ib)); }
public static Image CreateBanner(int nWidth, int nHeight, BannerStyle bs, Image imgIcon, string strTitle, string strLine, bool bNoCache) { // imgIcon may be null if (strTitle == null) { Debug.Assert(false); strTitle = string.Empty; } if (strLine == null) { Debug.Assert(false); strLine = string.Empty; } Debug.Assert((nHeight == StdHeight) || DpiUtil.ScalingRequired || UISystemFonts.OverrideUIFont); if (MonoWorkarounds.IsRequired(12525) && (nHeight > 0)) { --nHeight; } if (bs == BannerStyle.Default) { bs = Program.Config.UI.BannerStyle; } if (bs == BannerStyle.Default) { Debug.Assert(false); bs = BannerStyle.WinVistaBlack; } NumberFormatInfo nfi = NumberFormatInfo.InvariantInfo; ulong uIconHash = ((imgIcon != null) ? GfxUtil.HashImage64(imgIcon) : 0); string strID = nWidth.ToString(nfi) + "x" + nHeight.ToString(nfi) + ":" + ((uint)bs).ToString(nfi) + ":" + strTitle + ":/:" + strLine + ":" + uIconHash.ToString(nfi); Image img = null; if (!bNoCache && g_dCache.TryGetValue(strID, out img)) { return(img); } if (g_pCustomGen != null) { img = g_pCustomGen(new BfBannerInfo(nWidth, nHeight, bs, imgIcon, strTitle, strLine)); } const float fHorz = 0.90f; const float fVert = 90.0f; if (img == null) { img = new Bitmap(nWidth, nHeight, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(img); Color clrStart = Color.White; Color clrEnd = Color.LightBlue; float fAngle = fHorz; if (bs == BannerStyle.BlueCarbon) { fAngle = fVert; g.Clear(Color.Black); // Area from 3/8 to 1/2 height clrStart = Color.LightGray; clrEnd = Color.Black; Rectangle rect = new Rectangle(0, 0, nWidth, (nHeight * 3) / 8); using (LinearGradientBrush brCarbonT = new LinearGradientBrush( rect, clrStart, clrEnd, fAngle, true)) { g.FillRectangle(brCarbonT, rect); } // clrStart = Color.FromArgb(0, 0, 32); clrStart = Color.FromArgb(0, 0, 28); // clrEnd = Color.FromArgb(192, 192, 255); clrEnd = Color.FromArgb(155, 155, 214); // rect = new Rectangle(0, nHeight / 2, nWidth, (nHeight * 5) / 8); int hMid = nHeight / 2; rect = new Rectangle(0, hMid - 1, nWidth, nHeight - hMid); using (LinearGradientBrush brCarbonB = new LinearGradientBrush( rect, clrStart, clrEnd, fAngle, true)) { g.FillRectangle(brCarbonB, rect); } // Workaround gradient drawing bug (e.g. occuring on // Windows 8.1 with 150% DPI) using (Pen pen = new Pen(Color.Black)) { g.DrawLine(pen, 0, hMid - 1, nWidth - 1, hMid - 1); } } else { if (bs == BannerStyle.WinXPLogin) { clrStart = Color.FromArgb(200, 208, 248); clrEnd = Color.FromArgb(40, 64, 216); } else if (bs == BannerStyle.WinVistaBlack) { clrStart = Color.FromArgb(151, 154, 173); clrEnd = Color.FromArgb(27, 27, 37); fAngle = fVert; } else if (bs == BannerStyle.KeePassWin32) { clrStart = Color.FromArgb(235, 235, 255); clrEnd = Color.FromArgb(192, 192, 255); } Rectangle rect = new Rectangle(0, 0, nWidth, nHeight); using (LinearGradientBrush brBack = new LinearGradientBrush( rect, clrStart, clrEnd, fAngle, true)) { g.FillRectangle(brBack, rect); } } bool bRtl = Program.Translation.Properties.RightToLeft; // Matrix mxTrfOrg = g.Transform; // if(bRtl) // { // g.TranslateTransform(nWidth, 0.0f); // g.ScaleTransform(-1.0f, 1.0f); // } int xIcon = DpiScaleInt(10, nHeight); int wIconScaled = StdIconDim; int hIconScaled = StdIconDim; if (imgIcon != null) { float fIconRel = (float)imgIcon.Width / (float)imgIcon.Height; wIconScaled = (int)Math.Round(DpiScaleFloat(fIconRel * (float)StdIconDim, nHeight)); hIconScaled = DpiScaleInt(StdIconDim, nHeight); int xIconR = (bRtl ? (nWidth - xIcon - wIconScaled) : xIcon); int yIconR = (nHeight - hIconScaled) / 2; if (hIconScaled == imgIcon.Height) { g.DrawImageUnscaled(imgIcon, xIconR, yIconR); } else { g.DrawImage(imgIcon, xIconR, yIconR, wIconScaled, hIconScaled); } ColorMatrix cm = new ColorMatrix(); cm.Matrix33 = 0.1f; ImageAttributes ia = new ImageAttributes(); ia.SetColorMatrix(cm); int w = wIconScaled * 3, h = hIconScaled * 3; int x = (bRtl ? xIcon : (nWidth - w - xIcon)); int y = (nHeight - h) / 2; Rectangle rectDest = new Rectangle(x, y, w, h); g.DrawImage(imgIcon, rectDest, 0, 0, imgIcon.Width, imgIcon.Height, GraphicsUnit.Pixel, ia); } if ((bs == BannerStyle.WinXPLogin) || (bs == BannerStyle.WinVistaBlack) || (bs == BannerStyle.BlueCarbon)) { int sh = DpiUtil.ScaleIntY(20) / 10; // Force floor Rectangle rect = new Rectangle(0, nHeight - sh, 0, sh); rect.Width = nWidth / 2 + 1; rect.X = nWidth / 2; clrStart = Color.FromArgb(248, 136, 24); clrEnd = Color.White; using (LinearGradientBrush brushOrangeWhite = new LinearGradientBrush( rect, clrStart, clrEnd, fHorz, true)) { g.FillRectangle(brushOrangeWhite, rect); } rect.Width = nWidth / 2 + 1; rect.X = 0; clrStart = Color.White; clrEnd = Color.FromArgb(248, 136, 24); using (LinearGradientBrush brushWhiteOrange = new LinearGradientBrush( rect, clrStart, clrEnd, fHorz, true)) { g.FillRectangle(brushWhiteOrange, rect); } } else if (bs == BannerStyle.KeePassWin32) { int sh = DpiUtil.ScaleIntY(10) / 10; // Force floor // Black separator line using (Pen penBlack = new Pen(Color.Black)) { for (int i = 0; i < sh; ++i) { g.DrawLine(penBlack, 0, nHeight - i - 1, nWidth - 1, nHeight - i - 1); } } } // if(bRtl) g.Transform = mxTrfOrg; // Brush brush; Color clrText; if (bs == BannerStyle.KeePassWin32) { // brush = Brushes.Black; clrText = Color.Black; } else { // brush = Brushes.White; clrText = Color.White; } // float fx = 2 * xIcon, fy = 9.0f; int tx = 2 * xIcon, ty = DpiScaleInt(9, nHeight); if (imgIcon != null) { tx += wIconScaled; // fx } // TextFormatFlags tff = (TextFormatFlags.PreserveGraphicsClipping | // TextFormatFlags.NoPrefix); // if(bRtl) tff |= TextFormatFlags.RightToLeft; float fFontSize = DpiScaleFloat((12.0f * 96.0f) / g.DpiY, nHeight); using (Font font = FontUtil.CreateFont(FontFamily.GenericSansSerif, fFontSize, FontStyle.Bold)) { int txT = (!bRtl ? tx : (nWidth - tx)); // - TextRenderer.MeasureText(g, strTitle, font).Width)); // g.DrawString(strTitle, font, brush, fx, fy); BannerFactory.DrawText(g, strTitle, txT, ty, font, clrText, bRtl, nWidth); } tx += xIcon; // fx ty += xIcon * 2 + 2; // fy float fFontSizeSm = DpiScaleFloat((9.0f * 96.0f) / g.DpiY, nHeight); using (Font fontSmall = FontUtil.CreateFont(FontFamily.GenericSansSerif, fFontSizeSm, FontStyle.Regular)) { int txL = (!bRtl ? tx : (nWidth - tx)); // - TextRenderer.MeasureText(g, strLine, fontSmall).Width)); // g.DrawString(strLine, fontSmall, brush, fx, fy); BannerFactory.DrawText(g, strLine, txL, ty, fontSmall, clrText, bRtl, nWidth); } g.Dispose(); } if (!bNoCache) { if (g_dCache.Count >= MaxCachedImages) { List <string> lK = new List <string>(g_dCache.Keys); g_dCache.Remove(lK[Program.GlobalRandom.Next(lK.Count)]); } g_dCache[strID] = img; } return(img); }
public static void 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); } }
private void Grayscale() { RenderTargetBitmap rtb = new RenderTargetBitmap((int)_canvas.RenderSize.Width, (int)_canvas.RenderSize.Height, 96d, 96d, PixelFormats.Default); DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) drawingContext.DrawRectangle(_canvas.Background, null, new Rect(0, 0, _canvas.ActualWidth, _canvas.ActualHeight)); rtb.Render(drawingVisual); foreach (object paintSurfaceChild in _canvas.Children) { rtb.Render((Visual)paintSurfaceChild); } Bitmap canvasBitmap; using (MemoryStream outStream = new MemoryStream()) { BitmapEncoder enc = new BmpBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(rtb)); enc.Save(outStream); canvasBitmap = new Bitmap(outStream); } Bitmap newBitmap = new Bitmap(canvasBitmap.Width, canvasBitmap.Height); Graphics g = Graphics.FromImage(newBitmap); //create the grayscale ColorMatrix ColorMatrix colorMatrix = new ColorMatrix( new float[][] { new float[] { .3f, .3f, .3f, 0, 0 }, new float[] { .59f, .59f, .59f, 0, 0 }, new float[] { .11f, .11f, .11f, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }); //create some image attributes ImageAttributes attributes = new ImageAttributes(); //set the color matrix attribute attributes.SetColorMatrix(colorMatrix); //draw the original image on the new image //using the grayscale color matrix g.DrawImage(canvasBitmap, new Rectangle(0, 0, canvasBitmap.Width, canvasBitmap.Height), 0, 0, canvasBitmap.Width, canvasBitmap.Height, GraphicsUnit.Pixel, attributes); //dispose the Graphics object g.Dispose(); _canvas.Background = new ImageBrush(Imaging.CreateBitmapSourceFromHBitmap(newBitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions())); _canvas.Children.Clear(); }
public override IEnumerable <Wait> RoutineUse(Creature user, object target) { if (target is Creature targetCreature) { List <Creature> targets = new List <Creature>(); Consume(); ShowSkill(user); var chirality = user.GetStatusEffect <Chirality>(); chirality?.AddBuildup(-5); user.VisualPose = user.FlickPose(CreaturePose.Cast, CreaturePose.Stand, 70); yield return(user.WaitSome(50)); var bullet = new BulletSpeed(user.World, SpriteLoader.Instance.AddSprite("content/highspeed"), user.VisualTarget, ColorMatrix.Tint(Color.Black), 15); bullet.Move(targetCreature.VisualTarget, 15); yield return(new WaitBullet(bullet)); SpriteReference triangle = SpriteLoader.Instance.AddSprite("content/triangle"); for (int i = 0; i < 50; i++) { Vector2 emitPos = new Vector2(targetCreature.X * 16, targetCreature.Y * 16) + targetCreature.Mask.GetRandomPixel(Random); Vector2 centerPos = targetCreature.VisualTarget; Vector2 velocity = Vector2.Normalize(emitPos - centerPos) * (Random.NextFloat() + 0.5f) * 40f; new Triangle(user.World, triangle, emitPos, velocity, MathHelper.ToRadians(40 * (Random.NextFloat() - 0.5f)), Color.Black, Random.Next(80) + 5); } yield return(user.WaitSome(20)); List <Wait> waits = new List <Wait>(); for (int i = 0; i < 10; i++) { targets.Add(targetCreature); waits.Add(Scheduler.Instance.RunAndWait(RoutineSlap(user, targetCreature))); yield return(user.WaitSome(4)); } yield return(new WaitAll(waits)); yield return(new WaitAll(targets.Select(GetCurrentAction))); } }
public override void OnDraw(Graphics g) { bool bInDesign = false; if (this.Page != null) { bInDesign = this.Page.InDesignMode; } if (bInDesign) { base.OnDraw(g); int nRows = this.Rows; int nCol = this.Columns; int nWidth = this.Width; int nHeight = this.Height; if (nRows <= 0) { nRows = 1; } if (nCol <= 0) { nCol = 1; } if (nRows == 1 && nCol == 1) { return; } int nGapX = this.GapX; int nGapY = this.GapY; if (nGapX < 0) { nGapX = 0; } if (nGapY < 0) { nGapY = 0; } bool bGetBmp = (_bmp == null); if (!bGetBmp) { if (this.Page != null && !this.Page.ShowingTextInput) { if (this.Page.Left >= 0 && this.Page.Top >= 0) { if (this.Page.AutoScrollPosition.X == 0 && this.Page.AutoScrollPosition.Y == 0) { bGetBmp = true; } } } } if (bGetBmp) { _bmp = WinUtil.CaptureScreenImage(Page.Handle, this.Left, this.Top, this.Width, this.Height, Page.FormBorderStyle != FormBorderStyle.None); } ImageAttributes ia = null; if (_linePen == null) { _linePen = new Pen(new SolidBrush(Color.LightGray)); } ColorMatrix cm = new ColorMatrix(); ia = new ImageAttributes(); cm.Matrix33 = 0.5f; ia.SetColorMatrix(cm); int w = this.Width * nCol; int h = this.Height * nRows; for (int r = 0, dh = this.Top; r <= nRows; r++, dh += this.Height) { g.DrawLine(_linePen, this.Left, dh, this.Left + w, dh); } for (int c = 0, dw = this.Left; c <= nCol; c++, dw += this.Width) { g.DrawLine(_linePen, dw, this.Top, dw, this.Top + h); } if (_bmp != null) { int incH = this.Height + nGapY; int incW = this.Width + nGapX; for (int r = 0, dh = this.Top; r < nRows; r++, dh += incH) { for (int c = 0, dw = this.Left; c < nCol; c++, dw += incW) { if (r != 0 || c != 0) { Rectangle rc = new Rectangle(dw, dh, _bmp.Width, _bmp.Height); if (bInDesign) { g.DrawImage(_bmp, rc, 0, 0, _bmp.Width, _bmp.Height, GraphicsUnit.Pixel, ia); } else { g.DrawImage(_bmp, rc, 0, 0, _bmp.Width, _bmp.Height, GraphicsUnit.Pixel); } } } } } } else { if (_drawItems != null) { for (int r = 0; r < _drawItems.Length; r++) { for (int c = 0; c < _drawItems[r].Length; c++) { _drawItems[r][c].OnDraw(g); } } } } }
public override IEnumerable <Wait> RoutineUse(Creature user, object target) { if (target is Creature targetCreature) { Consume(); ShowSkill(user); user.VisualPose = user.FlickPose(CreaturePose.Cast, CreaturePose.Stand, 70); yield return(user.WaitSome(50)); var bullet = new BulletDelta(user.World, SpriteLoader.Instance.AddSprite("content/delta"), user.VisualTarget, ColorMatrix.Tint(Color.Goldenrod), MathHelper.ToRadians(20), 50); bullet.Move(targetCreature.VisualTarget, 30); yield return(user.WaitSome(30)); new RockTremor(user.World, targetCreature, 30); yield return(new WaitBullet(bullet)); var wait = user.Attack(targetCreature, SkillUtil.SafeNormalize(targetCreature.VisualTarget - user.VisualTarget), AttackDelta); yield return(wait); } }
/// <summary> /// 裁剪图片,返回裁剪后的文件路径 /// </summary> /// <param name="filepath">文件相对路径</param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> static string F3(string filepath, int width, int height) { if (string.IsNullOrEmpty(filepath)) { return(DIRPATH); } string filename = System.IO.Path.GetFileName(filepath); if (string.IsNullOrEmpty(filename)) { return(DIRPATH); } string desfilepath = HttpContext.Current.Server.MapPath(filepath); if (!System.IO.File.Exists(desfilepath)) { return(DIRPATH); } string tofilepath = DIRPATH + System.IO.Path.GetFileNameWithoutExtension(filepath) + "_" + width + "_" + height + System.IO.Path.GetExtension(filepath); string destofilepath = HttpContext.Current.Server.MapPath(tofilepath); if (System.IO.File.Exists(destofilepath)) { return(tofilepath); } Image img = null; try { img = System.Drawing.Image.FromFile(desfilepath); } catch { } if (img == null) { return(DIRPATH); } int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = img.Width; int oh = img.Height; if (img.Width == width && img.Height == height) { return(filepath); } if ((double)img.Width / (double)img.Height > (double)towidth / (double)toheight) { oh = img.Height; ow = img.Height * towidth / toheight; y = 0; x = (img.Width - ow) / 2; } else { ow = img.Width; oh = img.Width * height / towidth; x = 0; y = (img.Height - oh) / 2; } //新建一个bmp图片 Bitmap bitmap = new System.Drawing.Bitmap(towidth, toheight, PixelFormat.Format24bppRgb); //设置分辨率 bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution); //新建一个画板 Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default; //设置高质量,低速度呈现平滑程度 消除锯齿 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(img, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); #region 水印 //获得水印图像 Image markImg = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath("/images/WaterMark.png"));; //创建颜色矩阵 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, 0.2f, 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); //如果原图过小 if (markImg.Width > towidth || markImg.Height > toheight) { int newimgWidth = towidth / 4; int newimgHeight = markImg.Height * towidth / markImg.Width / 4; System.Drawing.Image.GetThumbnailImageAbort callb = null; //对水印图片生成缩略图,缩小到原图得1/4 System.Drawing.Image new_img = markImg.GetThumbnailImage(newimgWidth, newimgHeight, callb, new System.IntPtr()); //添加水印 g.DrawImage(new_img, new Rectangle(10, toheight - newimgHeight - 10, new_img.Width, new_img.Height), 0, 0, new_img.Width, new_img.Height, GraphicsUnit.Pixel, imageAttributes); //释放缩略图 new_img.Dispose(); //释放Graphics g.Dispose(); } //原图足够大 else { //添加水印 g.DrawImage(markImg, new Rectangle(10, toheight - markImg.Height - 10, markImg.Width, markImg.Height), 0, 0, markImg.Width, markImg.Height, GraphicsUnit.Pixel, imageAttributes); //释放Graphics g.Dispose(); } #endregion try { //以jpg格式保存缩略图 bitmap.Save(destofilepath); } catch { tofilepath = DIRPATH; } finally { img.Dispose(); bitmap.Dispose(); g.Dispose(); } return(tofilepath); }
private IEnumerable <Wait> RoutineHand(Creature user, Creature target, int hits) { List <Vector2> wingPositions = Wallhach.GetWingPositions(user.VisualTarget, 1.0f); Vector2 velocity = Util.AngleToVector(Random.NextFloat() * MathHelper.TwoPi) * 160; Vector2 emitPos = wingPositions.Pick(Random); int moveTime = 30 + Random.Next(30); var bullet = new MissileHand(user.World, emitPos, target.VisualTarget, velocity, ColorMatrix.Tint(Color.Goldenrod), moveTime, moveTime); yield return(new WaitBullet(bullet)); if (hits % 3 >= 2) { user.Attack(target, Vector2.Zero, AttackSlap); } }
public void ScaleTest1() { ColorMatrix m1 = new ColorMatrix(0, 0, 0, 0, 0, 0, 0, 0); ColorMatrix m2 = ColorMatrix.Identity; }
public override void Draw(float destX, float destY, Geometry.Rectangle srcRect, float rotationCenterX, float rotationCenterY) { mDisplay.CheckInFrame("Surface.Draw"); PointF destPt = new PointF(destX, destY); System.Diagnostics.Debug.Assert(mImage != null); Drawing_Display disp = Display.Impl as Drawing_Display; Graphics g = disp.FrameGraphics; GraphicsState state = g.Save(); Geometry.PointF translatePoint = Origin.CalcF(DisplayAlignment, DisplaySize); if (DisplaySize.Width < 0) { translatePoint.X += DisplaySize.Width; rotationCenterX += DisplaySize.Width; } if (DisplaySize.Height < 0) { translatePoint.Y += DisplaySize.Height; rotationCenterY += DisplaySize.Height; } // translate to rotation point, rotate, and translate back. // System.Drawing rotates Clockwise! So we must reverse the // rotation angle. g.TranslateTransform(-rotationCenterX, -rotationCenterY, MatrixOrder.Append); g.RotateTransform(-(float)RotationAngleDegrees, MatrixOrder.Append); g.TranslateTransform(rotationCenterX, rotationCenterY, MatrixOrder.Append); SetInterpolation(g); g.TranslateTransform(destPt.X - translatePoint.X, destPt.Y - translatePoint.Y, MatrixOrder.Append); if (Color != Geometry.Color.White) { ImageAttributes imageAttributes = new ImageAttributes(); ColorMatrix colorMatrix = new ColorMatrix(new float[][] { new float[] { Color.R / 255.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, Color.G / 255.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, Color.B / 255.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, (float)Alpha, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); g.DrawImage(mImage, Interop.Convert(DestRect(0, 0, srcRect)), srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, GraphicsUnit.Pixel, imageAttributes); } else { g.DrawImage(mImage, Interop.Convert(DestRect(0, 0, srcRect)), srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, GraphicsUnit.Pixel); } g.Restore(state); }
public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix) {}
protected override void OnPaint(PaintEventArgs pevent) { Rectangle r = ClientRectangle; Image imageBackground = null; ImageAttributes imageAttributes = null; if (Enabled) { if (m_hover) { imageBackground = Form.Skin.ButtonHoverImage; } else { imageBackground = Form.Skin.ButtonNormalImage; } } else { imageBackground = Form.Skin.ButtonDisabledImage; ColorMatrix imageColorMatrix = new ColorMatrix(); imageAttributes = new ImageAttributes(); imageColorMatrix.Matrix33 = 0.2f; imageAttributes.SetColorMatrix(imageColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); } pevent.Graphics.DrawImage(imageBackground, r); Brush brushText = Form.Skin.ForeBrush; if (Enabled == false) { brushText = Form.Skin.ForeDisabledBrush; } if (Image == null) { pevent.Graphics.DrawString(Text, Font, brushText, r, GuiUtils.StringFormatCenterMiddle); } else if (Text == "") { Image mainImage = Image; if ((ImageHover != null) && (m_hover)) { mainImage = ImageHover; } Form.DrawImageContain(pevent.Graphics, mainImage, r, ImageInflatePerc); } else { /* * Not yet used * SizeF sText = pevent.Graphics.MeasureString(Text, Font); * * int width = Image.Width + 10 + sText.Width; * int height = Math.Max(Image.Height, sText.Height); */ } if (DrawBorder) { r.Width--; r.Height--; pevent.Graphics.DrawRectangle(Pens.Gray, r); } if (imageAttributes != null) { imageAttributes.Dispose(); } }
public void ConstructorInitializedPropertiesTest() { ColorMatrix m1 = new ColorMatrix(2, 3, 4, 5, 6, 7, 8, 9); Assert.Equal(2, m1.R); Assert.Equal(3, m1.G); Assert.Equal(4, m1.B); Assert.Equal(5, m1.A); Assert.Equal(6, m1.RedShift); Assert.Equal(7, m1.GreenShift); Assert.Equal(8, m1.BlueShift); Assert.Equal(9, m1.AlphaShift); }
/// <summary> /// 在图片中添加文字水印 /// </summary> /// <param name="gSrcCanvas"></param> /// <param name="watermarkText"></param> /// <param name="width"></param> /// <param name="height"></param> private static void AddWatermarkText(Graphics gSrcCanvas, string watermarkText, int width, int height) { //计算图片对角线长度 double diagonal = Math.Sqrt(Math.Pow(width, 2) + Math.Pow(height, 2)); //计算对角线倾角 double angle = Math.Asin(height / Math.Sqrt(Math.Pow(width, 2) + Math.Pow(height, 2))) / Math.PI * 180; // 确定水印文字的字体大小 int[] sizes = new int[] { 280, 276, 272, 268, 264, 260, 256, 252, 248, 244, 240, 236, 232, 228, 224, 220, 216, 212, 208, 204, 200, 196, 192, 188, 184, 180, 176, 172, 168, 164, 160, 156, 152, 148, 144, 140, 136, 132, 128, 124, 120, 116, 112, 108, 104, 100, 96, 92, 88, 84, 80, 76, 72, 68, 64, 60, 56, 52, 48, 44, 40, 36, 32, 28, 24, 20, 16, 12, 8, 4 }; Font crFont = null; SizeF crSize = new SizeF(); for (int i = 0; i < sizes.Length; i++) { crFont = new Font("微软雅黑", sizes[i], FontStyle.Bold); crSize = gSrcCanvas.MeasureString(watermarkText, crFont); if ((int)crSize.Width < (int)diagonal * 0.9) { break; } } // 生成水印图片(将文字写到图片中) //Bitmap bmWaterMark = new Bitmap((int)crSize.Width + 3, (int)crSize.Height + 3, PixelFormat.Format32bppArgb); Bitmap bmWaterMark = new Bitmap(width, height, PixelFormat.Format32bppArgb); Graphics gWaterMark = Graphics.FromImage(bmWaterMark); gWaterMark.TranslateTransform(width / 2, height / 2); //文字倾斜角度根据实际图片对角线长度计算 gWaterMark.RotateTransform(-(int)angle); gWaterMark.TranslateTransform(-crSize.Width / 2, -crSize.Height / 2); PointF pt = new PointF(0, 0); // 画阴影文字 Brush transparentBrush0 = new SolidBrush(Color.FromArgb(255, Color.Black)); Brush transparentBrush1 = new SolidBrush(Color.FromArgb(255, Color.Black)); gWaterMark.DrawString(watermarkText, crFont, transparentBrush0, pt.X, pt.Y + 1); gWaterMark.DrawString(watermarkText, crFont, transparentBrush0, pt.X + 1, pt.Y); gWaterMark.DrawString(watermarkText, crFont, transparentBrush1, pt.X + 1, pt.Y + 1); gWaterMark.DrawString(watermarkText, crFont, transparentBrush1, pt.X, pt.Y + 2); gWaterMark.DrawString(watermarkText, crFont, transparentBrush1, pt.X + 2, pt.Y); transparentBrush0.Dispose(); transparentBrush1.Dispose(); // 画文字 gWaterMark.SmoothingMode = SmoothingMode.HighQuality; //Brush SolidBrush3 = new SolidBrush(Color.White); Brush solidBrush3 = new SolidBrush(Color.FromArgb(255, Color.White)); gWaterMark.DrawString(watermarkText, crFont, solidBrush3, pt.X, pt.Y, StringFormat.GenericDefault); solidBrush3.Dispose(); // 保存刚才的操作 gWaterMark.Save(); gWaterMark.Dispose(); bmWaterMark.Save(_wmImgSavePath, ImageFormat.Jpeg); //// 将水印图片加到原图中 //AddWatermarkImage(gSrcCanvas, new Bitmap(bmWaterMark), "WM_TOP_LEFT", width, height); using (var imageAttr = new ImageAttributes()) { ColorMap colorMap = new ColorMap(); colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); ColorMap[] remapTable = { colorMap }; imageAttr.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float[][] colorMatrixElements = { new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.3f, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); imageAttr.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); gSrcCanvas.DrawImage(bmWaterMark, new Rectangle(10, 10, bmWaterMark.Width, bmWaterMark.Height), 0, 0, bmWaterMark.Width, bmWaterMark.Height, GraphicsUnit.Pixel, imageAttr); gSrcCanvas.Dispose(); } bmWaterMark.Dispose(); }
// CONSIDER: why doesn't AddColor just take a SymColor? This seems inconsistent with the way the // other methods work. private bool EqualColorMatrix(ColorMatrix mat1, ColorMatrix mat2) { if (mat1 == null) return (mat2 == null); else if (mat2 == null) return (mat1 == null); else { for (int i = 0; i < 5; ++i) for (int j = 0; j < 5; ++j) if (mat1[i, j] != mat2[i, j]) return false; return true; } }
public Bitmap applyFilters(String name, Bitmap image) { Console.WriteLine("Filter start"); //Black and white if (name.Equals("bw")) { Console.WriteLine("bw"); //create a blank bitmap the same size as original Bitmap newBitmap = new Bitmap(image.Width, image.Height); //get a graphics object from the new image Graphics g = Graphics.FromImage(image); //create the grayscale ColorMatrix ColorMatrix colorMatrix = new ColorMatrix( new float[][] { new float[] { .3f, .3f, .3f, 0, 0 }, new float[] { .59f, .59f, .59f, 0, 0 }, new float[] { .11f, .11f, .11f, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }); //create some image attributes ImageAttributes attributes = new ImageAttributes(); //set the color matrix attribute attributes.SetColorMatrix(colorMatrix); //draw the original image on the new image //using the grayscale color matrix g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes); } //Sepia if (name.Equals("sp")) { Console.WriteLine("sp"); //Values for sepia filter color matrix float[][] sepiaValues = { new float[] { .393f, .349f, .272f, 0, 0 }, new float[] { .769f, .686f, .534f, 0, 0 }, new float[] { .189f, .168f, .131f, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }; //Make and populate color matrix ColorMatrix sepiaMatrix = new ColorMatrix(sepiaValues); ImageAttributes IA = new ImageAttributes(); //Setting image attributes IA.SetColorMatrix(sepiaMatrix); Bitmap sepiaEffect = image; //Draw image with sepia using (Graphics G = Graphics.FromImage(sepiaEffect)) { G.DrawImage(sepiaEffect, new Rectangle(0, 0, sepiaEffect.Width, sepiaEffect.Height), 0, 0, sepiaEffect.Width, sepiaEffect.Height, GraphicsUnit.Pixel, IA); } image = sepiaEffect; } return(image); }
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(); }
private void repaintPictureBoxFromList(PointF?mouseClickPoint = null) { // Pen handle for wall painting Pen wallPen; // ImageAttributes for transparent image drawing 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, 0.5f, 0 }, new float[] { 0, 0, 0, 0, 1 } }; ColorMatrix colorMatrix = new ColorMatrix(matrixItems); ImageAttributes imageAtt = new ImageAttributes(); imageAtt.SetColorMatrix( colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); Graphics g = Graphics.FromImage(blueprintPictureBox.Image); g.FillRectangle(Brushes.White, 0, 0, blueprintPictureBox.Image.Width, blueprintPictureBox.Image.Height); for (int i = 0; i < createdFurnitureListBox.Items.Count; ++i) { if (!(createdFurnitureListBox.Items[i] is FurnitureListBoxItem)) { continue; } FurnitureListBoxItem item = createdFurnitureListBox.Items[i] as FurnitureListBoxItem; if (item.type == "wall.png") { if (item == createdFurnitureListBox.SelectedItem) { wallPen = new Pen(Color.FromArgb(128, 0, 0, 0), 10); // semi transparent } else { wallPen = new Pen(Color.Black, 10); // opaque } wallPen.LineJoin = LineJoin.Round; //Matrix for rotation if (item.path != null) { Matrix rotateMatrix = null; if (item.path.PointCount > 1) { rotateMatrix = new Matrix(); rotateMatrix.RotateAt(item.rotation, item.path.PathPoints[0]); } if (item.path.PointCount > 0) { GraphicsPath graphicsPath = (GraphicsPath)item.path.Clone(); if (wallPath == item.path && mouseClickPoint != null) { graphicsPath.AddLine(graphicsPath.GetLastPoint(), (PointF)mouseClickPoint); } if (rotateMatrix != null) { graphicsPath.Transform(rotateMatrix); } g.DrawPath(wallPen, graphicsPath); } else if (item.path.PointCount == 0 && mouseClickPoint != null) { g.DrawLine(wallPen, pathStart, (PointF)mouseClickPoint); } } } else { if (item.rotation != 0) { g.TranslateTransform(item.displayPoint.X, item.displayPoint.Y); g.RotateTransform(item.rotation); g.TranslateTransform(-item.displayPoint.X, -item.displayPoint.Y); } PointF point = new PointF(item.displayPoint.X - item.displayImage.Width / 2, item.displayPoint.Y - item.displayImage.Height / 2); if (item == createdFurnitureListBox.SelectedItem) { g.DrawImage(item.displayImage, new Rectangle((int)point.X, (int)point.Y, item.displayImage.Width, item.displayImage.Height), 0.0f, 0.0f, item.displayImage.Width, item.displayImage.Height, GraphicsUnit.Pixel, imageAtt); } else { g.DrawImage(item.displayImage, point); } } g.ResetTransform(); } g.Dispose(); blueprintPictureBox.Refresh(); }
public void SetColorMatrix(ColorMatrix newColorMatrix) {}
/// <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(); } }
public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag mode, ColorAdjustType type) {}
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(); }
/// <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(); } }
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); } }
public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag flags) {}
/// <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.HttpPostedFile 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(); } }
public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag flags) {}
//TODO_RR static ImageAttributes imageAttr = new ImageAttributes(); public static void set_alpha(int alpha) { // Initialize the color matrix. ColorMatrix myColorMatrix = new ColorMatrix(); // Red myColorMatrix.Matrix00 = 1.00f; // Green myColorMatrix.Matrix11 = 1.00f; // Blue myColorMatrix.Matrix22 = 1.00f; // alpha myColorMatrix.Matrix33 = (float)(alpha) / 256.0f; ; // w myColorMatrix.Matrix44 = 1.00f; // set the color matrix. imageAttr.SetColorMatrix(myColorMatrix); }
public void IsInvertableTest() { ColorMatrix m1 = new ColorMatrix(1, 1, 1, 1, 0, 0, 0, 0); Assert.True(m1.IsInvertible); }