Exemple #1
0
        public static void MarkWater(string filepath, string waterfile, string watermarkPosition)
        {
            byte[]       barrImgData      = System.IO.File.ReadAllBytes(filepath);
            byte[]       barrWaterImgData = System.IO.File.ReadAllBytes(waterfile);
            MemoryStream msImg            = new MemoryStream(barrImgData);
            MemoryStream msWaterImg       = new MemoryStream(barrWaterImgData);
            Image        img     = null;
            Image        markImg = null;

            try
            {
                img     = Image.FromStream(msImg);
                markImg = Image.FromStream(msWaterImg);
                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, 1.0f, 0 },                       //注意:此处为0.0f为完全透明,1.0f为完全不透明
                    new float[] { 0, 0, 0,    0, 1 }
                };
                ColorMatrix     colorMatrix     = new ColorMatrix(ptsArray);
                ImageAttributes imageAttributes = new ImageAttributes();
                imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.SkipGrays, ColorAdjustType.Bitmap);
                Bitmap newBitmap = new Bitmap(img.Width, img.Height, PixelFormat.Format48bppRgb);
                newBitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                Graphics g = Graphics.FromImage(newBitmap);
                g.SmoothingMode      = SmoothingMode.AntiAlias;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);

                Rectangle watermarkRectangle = PicHandle.GetWatermarkRectangle(img.Width, img.Height, markImg.Width, markImg.Height, watermarkPosition);
                g.DrawImage(markImg, watermarkRectangle, 0, 0, markImg.Width, markImg.Height, GraphicsUnit.Pixel, imageAttributes);
                g.Dispose();
                ImageFormat igf = img.RawFormat;
                if (img != null)
                {
                    img.Dispose();
                }
                newBitmap.Save(filepath, igf);
                newBitmap.Dispose();
            }
            catch (Exception exp)
            {
                XMS.Core.Container.LogService.Error("水印出错:" + exp.ToString());
            }
            finally
            {
                if (img != null)
                {
                    img.Dispose();
                }
                if (markImg != null)
                {
                    markImg.Dispose();
                }
            }
        }