C#底层库--图片增加水印辅助类

系列文章

C#底层库–记录日志帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/124187709

C#底层库–数据库访问帮助类(MySQL版)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126886379

C#底层库–获取文件版本和MD5值
本文链接:https://blog.csdn.net/youcheng_ge/article/details/112513871

C#底层库–操作文件帮助类FileHelper(获取目录的所有文件)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887161

C#底层库–操作Excel帮助类(读取、导出表格)
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126887445

C#底层库–软件版本管理XML
本文链接:https://blog.csdn.net/youcheng_ge/article/details/110195766

C#底层库–随机数生成类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/126888812

C#底层库–正则表达式帮助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/109745286

C#底层库–CSV和DataTable相互转换
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128804367

C#底层库–Image图片操作类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805298

C#底层库–JSON序列化、反序列化扩展类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128805705

C#底层库–cookie操作辅助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128816347

C#底层库–Session操作辅助类
本文链接:https://blog.csdn.net/youcheng_ge/article/details/128817096

文章目录

  • 系列文章
  • 前言
  • 一、底层库介绍
  • 二、底层库源码
  • 三、调用方法
  • 三、项目案列


前言

本专栏为【底层库】,将介绍研发过程中 通用的函数。我们将这些固化的源码,进行重写、规范封装、单元测试、集成测试,从而形成通用化模块库,本专栏称为“底层库”。

作为研发人员的你,并不需要花大量时间,完全掌握“底层库”的含义,你只需要几行调用代码,就可以解决一些项目上碰到的难题。大家有任何问题,可以评论区反馈,私信我。

底层库已实现功能:数据库操作、加解密算法、日志记录、HTTP通信、Socket通信、API前后端交互、邮件发送、文件操作、配置参数存储、Excel导入导出、CSV和DataTable转换、压缩解压、自动编号、Session操作等,

一、底层库介绍

WaterMark图片增加水印辅助类。包含:图片水印、文字水印、得到图片的格式。

二、底层库源码

创建类WaterMark.cs,复制以下代码。

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;

namespace GYC_Util.Common
{
    public class WaterMark
    {
        /// 
        /// 图片水印
        /// 
        /// 图片字节数组
        /// 图片扩展名
        /// 水印文件相对路径
        /// 图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下
        /// 附加水印图片质量,0-100
        /// 水印的透明度 1--10 10为不透明
        public static byte[] AddImageSignPic(byte[] byteData, string fileExt, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            MemoryStream memoryStream = new MemoryStream(byteData);
            Image img = Image.FromStream(memoryStream);
            if (watermarkFilename.StartsWith("/") == false)
            {
                watermarkFilename = "/" + watermarkFilename;
            }
            watermarkFilename = Utils.GetMapPath(watermarkFilename);
            if (!File.Exists(watermarkFilename))
            {
                return byteData;
            }
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            Image watermark = new Bitmap(watermarkFilename);
            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
            {
                return byteData;
            }

            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;

            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    if (ici != null)
                    {
                        img.Save(ms, ici, encoderParams);
                    }
                    else
                    {
                        img.Save(ms, GetFormat(fileExt));
                    }
                    byte[] buffer = new byte[ms.Length];
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.Read(buffer, 0, buffer.Length);
                    return buffer;
                }
            }
            finally
            {
                g.Dispose();
                img.Dispose();
                watermark.Dispose();
                imageAttributes.Dispose();
            }
        }

        /// 
        /// 文字水印
        /// 
        /// 图片字节数组
        /// 图片扩展名
        /// 水印文字
        /// 图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中  9=右下
        /// 附加水印图片质量,0-100
        /// 字体
        /// 字体大小
        public static byte[] AddImageSignText(byte[] byteData, string fileExt, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
        {
            MemoryStream memoryStream = new MemoryStream(byteData);
            Image img = Image.FromStream(memoryStream);
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF crSize;
            crSize = g.MeasureString(watermarkText, drawFont);

            float xpos = 0;
            float ypos = 0;

            switch (watermarkStatus)
            {
                case 1:
                    xpos = (float)img.Width * (float).01;
                    ypos = (float)img.Height * (float).01;
                    break;
                case 2:
                    xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                    ypos = (float)img.Height * (float).01;
                    break;
                case 3:
                    xpos = ((float)img.Width * (float).99) - crSize.Width;
                    ypos = (float)img.Height * (float).01;
                    break;
                case 4:
                    xpos = (float)img.Width * (float).01;
                    ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                    break;
                case 5:
                    xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                    ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                    break;
                case 6:
                    xpos = ((float)img.Width * (float).99) - crSize.Width;
                    ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                    break;
                case 7:
                    xpos = (float)img.Width * (float).01;
                    ypos = ((float)img.Height * (float).99) - crSize.Height;
                    break;
                case 8:
                    xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                    ypos = ((float)img.Height * (float).99) - crSize.Height;
                    break;
                case 9:
                    xpos = ((float)img.Width * (float).99) - crSize.Width;
                    ypos = ((float)img.Height * (float).99) - crSize.Height;
                    break;
            }

            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

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

            qualityParam[0] = quality;

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

            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    if (ici != null)
                    {
                        img.Save(ms, ici, encoderParams);
                    }
                    else
                    {
                        img.Save(ms, GetFormat(fileExt));
                    }
                    byte[] buffer = new byte[ms.Length];
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.Read(buffer, 0, buffer.Length);
                    return buffer;
                }
            }
            finally
            {
                g.Dispose();
                img.Dispose();
            }
        }

        /// 
        /// 得到图片的格式
        /// 
        private static ImageFormat GetFormat(string ext)
        {
            switch (ext.ToLower())
            {
                case "bmp":
                    return ImageFormat.Bmp;
                case "png":
                    return ImageFormat.Png;
                case "gif":
                    return ImageFormat.Gif;
                default:
                    return ImageFormat.Jpeg;
            }
        }
    }
}


三、调用方法

我放在网页的文件上传按钮中,通过文件流上传文件方法。

//如果是图片,检查是否需要打水印
if (IsWaterMark(fileExt) && isWater)
{
    switch (SysConfig.Intance.watermarktype)
    {
        case 1:
            byteData = WaterMark.AddImageSignText(byteData, fileExt, SysConfig.Intance.watermarktext, SysConfig.Intance.watermarkposition,
                SysConfig.Intance.watermarkimgquality, SysConfig.Intance.watermarkfont, SysConfig.Intance.watermarkfontsize);
            break;
        case 2:
            byteData = WaterMark.AddImageSignPic(byteData, fileExt, SysConfig.Intance.watermarkpic, SysConfig.Intance.watermarkposition,
                SysConfig.Intance.watermarkimgquality, SysConfig.Intance.watermarktransparency);
            break;
    }
}

三、项目案列

你可能感兴趣的:(C#,底层库(工具,通用类),c#,开发语言)