图片加水印帮助类

/// <summary>
/// 图片加水印帮助类
/// </summary>
public class WaterMarkHelper
{
/// <summary>
/// 图片水印
/// </summary>
/// <param name="imgPath">服务器图片相对路径</param>
/// <param name="filename">保存文件名</param>
/// <param name="watermarkFilename">水印文件相对路径</param>
/// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中,5=居中,6=右中,7=左下,8=中下, 9=右下</param>
/// <param name="quality">附加水印图片质量,0-100</param>
/// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param>
public static string AddImageWaterMark(string imgPath, string filename, string watermarkFilename, int watermarkStatus = 0, int quality = 100, int watermarkTransparency = 10)
{
if (!File.Exists(imgPath))
return "原图文件不存在";
if (!File.Exists(watermarkFilename))
return "水印文件不存在";
//如果保存文件不存在的就替换原图
if (string.IsNullOrEmpty(filename))
filename = imgPath;
try
{
byte[] _ImageBytes = File.ReadAllBytes(imgPath);
Image img = Image.FromStream(new MemoryStream(_ImageBytes));
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();
return "水印添加成功";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 文字水印
/// </summary>
/// <param name="imgPath">服务器图片相对路径</param>
/// <param name="filename">保存文件名</param>
/// <param name="watermarkText">水印文字</param>
/// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param>
/// <param name="quality">附加水印图片质量,0-100</param>
/// <param name="fontsize">字体大小</param>
/// <param name="fontname">字体</param>
public static string AddTextWaterMark(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, int fontsize, string fontname = "微软雅黑")
{
if (!File.Exists(imgPath))
return "原图文件不存在";
if (string.IsNullOrEmpty(watermarkText))
return "水印文字不存在";
//如果保存文件不存在的就替换原图
if (string.IsNullOrEmpty(filename))
filename = imgPath;
try
{
byte[] _ImageBytes = File.ReadAllBytes(imgPath);
Image img = Image.FromStream(new MemoryStream(_ImageBytes));
Graphics g = Graphics.FromImage(img);
Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
SizeF 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(Encoder.Quality, qualityParam);
encoderParams.Param[0] = encoderParam;

if (ici != null)
img.Save(filename, ici, encoderParams);
else
img.Save(filename);

g.Dispose();
img.Dispose();
return "水印文字添加成功";
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>
/// 在图片上添加平铺倾斜文字水印
/// </summary>
/// <param name="imgPath">源图片文件</param>
/// <param name="waterWords">需要添加到图片上的文字</param>
/// <returns></returns>
public static string AddTextWaterMark(string imgPath, string waterWords, int fontsize, int quality, string fontname = "微软雅黑")
{
if (!File.Exists(imgPath))
return "原图文件不存在";
if (string.IsNullOrEmpty(waterWords))
return "水印文字不存在";
try
{
Image img = Image.FromFile(imgPath);

// 获取图片的宽和高
int width = img.Width;
int height = img.Height;

Graphics g = Graphics.FromImage(img);

// 字体 字号 字体样式
Font drawFont = new Font(fontname, fontsize, FontStyle.Italic, GraphicsUnit.Pixel);

SizeF fontSize = g.MeasureString(waterWords, drawFont);

float xpos = 0;
float ypos = 0;

// 倾斜 -30°
g.RotateTransform(-30);

// 循环打印文字水印
for (int i = -width / 2; i < width * 1.5; i += 400)
{
xpos = i;
for (int j = -height / 2; j < height * 1.5; j += 240)
{
ypos = j;
g.DrawString(waterWords, drawFont, new SolidBrush(Color.FromArgb(50, 100, 100, 100)), 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];

// 图片质量:0 - 100
if (quality < 0 || quality > 100)
quality = 80;

qualityParam[0] = quality;

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

Image newImage = new Bitmap((int)img.Width, (int)img.Height);
//新建一个画板
Graphics newG = Graphics.FromImage(newImage);

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

//置背景色
newG.Clear(Color.White);
//画图
newG.DrawImage(img, new Rectangle(0, 0, newImage.Width, newImage.Height), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel);
img.Dispose();
g.Dispose();
newImage.Save(imgPath, ImageFormat.Jpeg);
return imgPath;
}
catch (Exception ex)
{
return ex.Message;
}
}
}

原文地址:https://www.cnblogs.com/liuzhangxi2018/p/9698230.html

时间: 2024-10-05 13:52:49

图片加水印帮助类的相关文章

thinkphp 3.2.3整合ueditor 1.4,给上传的图片加水印

今天分享一下thinkphp 3.2.3整合ueditor 1.4,给上传的图片加水印.博主是新手,在这里卡住了很久(>_<) thinkphp 3.2.3整合ueditor 1.4 下载地址:https://github.com/Nintendov/Ueditor-thinkphp 下载下来,看着配置就可以了. 下面就是给上传图片加水印: (在做这步前,请确保ueditor已经正常工作) 我的工程目录如下: fonts里面的fz.fft为水印字体 images里面的logo.png为水印图片

php 给图片加水印

昨天下午同事问我一个php的问题,就是给图片加水印,php我也一知半解,网上资料找了一通,自己就写了一个加水印的php类. 具体代码如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

Thumbnails为图片加水印

在JAVA中使用Thumbnails为图片加水印 将D盘下面的cat.jpg作为水印加在2.jpg上面,输出新的图片2_cat.jpg到D盘下面 1.java类 import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.geometry.Pos

java 图片加水印,设置透明度。说明很详细

package com.yidao.common; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.Out

文件上传,图片加水印

文件上传: 所用控件:FileUpload 使用时的思路: 1.判断用户是否选中了文件 FileUpload.FileName获取选中的文件名,判断长度,如果长度大于零就代表已经选择了文件 JS端:通过ID获取控件,然后控件的value获取选中的文件名 2.将文件保存到服务器上 FileUpload.SaveAs("绝对路径"); 3.获得绝对路径 先编写相对路径:比如"UpLoads/abc.txt" 再把路径映射成绝对路径:Server.MapPath(&quo

利用PHP为图片加水印

1.为图片加风格字体 <?php header('Content-type:image/jpeg');//告诉服务器用JPEG图像格式输出 $img=imagecreatefromjpeg('images/girl.jpg');//建立背景图像 $color=imagecolorallocate($img,100,100,100);//分配给字体的颜色 $width=imagesx($img);//输出背景图像的总宽度 $height=imagesy($img);//输出背景图像的总长度 $po

iOS图片加水印效果的实现并保存至相冊

图片加水印效果的实现并保存至相冊 实现效果如图: project下载:githubproject下载链接 代码: - (void)viewDidLoad { [super viewDidLoad]; UIImage *image = [UIImage imageNamed:@"pushu.jpg"]; UIImage *waterImage = [self waterMarkImage:image withText:@"朴树水印測试"]; UIImageWriteT

PHP给图片加水印具体实现

给图片加水印实现方法如下: 1 class Mark 2 { 3 public function __construct() 4 { 5 6 } 7 8 /** 9 * 加水印 10 * @param file $srcImg 要加水印的图片 11 * @param file $waterImg 水印图片 12 * @param integer $position 水印图片放置位置 1:左上,2:右上,3:居中,4:左下,5:右下 13 * @param integer $alpha 水印图片透

java 图片加水印,设置透明度。说明非常具体

package com.yidao.common; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.Out