图片编辑类

简介:
using  System;
using  System.Drawing;
using  System.IO;

/// <summary>
/// ImgEdit 的摘要说明
/// </summary>

public   class  ImgEdit
{
    
public ImgEdit()
    
{
        
//
        
// TODO: 在此处添加构造函数逻辑
        
//
    }


    
/// <summary>
    
/// 图片水印
    
/// </summary>
    
/// <param name="ImgFile">原图文件地址</param>
    
/// <param name="WaterImg">水印图片地址</param>
    
/// <param name="sImgPath">水印图片保存地址</param>
    
/// <param name="Alpha">水印透明度设置</param>
    
/// <param name="iScale">水印图片在原图上的显示比例(水平)</param>
    
/// <param name="intDistance">水印图片在原图上的边距确定,以图片的右边和下边为准,当设定的边距超过一定大小后参数会自动失效</param>

    public bool ImgWater(string ImgFile, string WaterImg, string sImgPath, float Alpha, float iScale, int intDistance)
    
{
        
try
        
{
            
//装载图片
            FileStream fs = new FileStream(ImgFile, FileMode.Open);
            BinaryReader br 
= new BinaryReader(fs);
            
byte[] bytes = br.ReadBytes((int)fs.Length);
            br.Close();
            fs.Close();
            MemoryStream ms 
= new MemoryStream(bytes);

            System.Drawing.Image imgPhoto 
= System.Drawing.Image.FromStream(ms);
            
int imgPhotoWidth = imgPhoto.Width;
            
int imgPhotoHeight = imgPhoto.Height;

            System.Drawing.Image imgWatermark 
= new Bitmap(WaterImg);
            
int imgWatermarkWidth = imgWatermark.Width;
            
int imgWatermarkHeight = imgWatermark.Height;


            
//计算水印图片尺寸
            decimal aScale = Convert.ToDecimal(iScale);
            
decimal pScale = 0.05M;
            
decimal MinScale = aScale - pScale;
            
decimal MaxScale = aScale + pScale;

            
//设置比例
            int imgWatermarkWidthNew = Convert.ToInt32(imgPhotoWidth * aScale);
            
int imgWatermarkHeightNew = Convert.ToInt32((imgPhotoWidth * aScale / imgWatermarkWidth) * imgWatermarkHeight);


            
//将原图画出来
            Bitmap bmPhoto = new Bitmap(imgPhotoWidth, imgPhotoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(
7272);
            Graphics gbmPhoto 
= Graphics.FromImage(bmPhoto);

            gbmPhoto.InterpolationMode 
= System.Drawing.Drawing2D.InterpolationMode.High;
            gbmPhoto.SmoothingMode 
= System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            gbmPhoto.Clear(Color.White);
            gbmPhoto.DrawImage(imgPhoto, 
new Rectangle(00, imgPhotoWidth, imgPhotoHeight), 00, imgPhotoWidth, imgPhotoHeight, GraphicsUnit.Pixel);

            Bitmap bmWatermark 
= new Bitmap(bmPhoto);
            bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

            Graphics gWatermark 
= Graphics.FromImage(bmWatermark);

            
//指定高质量显示水印图片质量
            gWatermark.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            gWatermark.SmoothingMode 
= System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            System.Drawing.Imaging.ImageAttributes imageAttributes 
= new System.Drawing.Imaging.ImageAttributes();

            
//设置两种颜色,达到合成效果
            System.Drawing.Imaging.ColorMap colorMap = new System.Drawing.Imaging.ColorMap();
            colorMap.OldColor 
= Color.FromArgb(25502550);
            colorMap.NewColor 
= Color.FromArgb(0000);

            System.Drawing.Imaging.ColorMap[] remapTable 
= { colorMap };

            imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            
//用矩阵设置水印图片透明度
            float[][] colorMatrixElements = 
               
new float[] {1.0f,  0.0f,  0.0f,  0.0f0.0f},
               
new float[] {0.0f,  1.0f,  0.0f,  0.0f0.0f},
               
new float[] {0.0f,  0.0f,  1.0f,  0.0f0.0f},
               
new float[] {0.0f,  0.0f,  0.0f,  Alpha, 0.0f},
               
new float[] {0.0f,  0.0f,  0.0f,  0.0f1.0f}
            }
;

            System.Drawing.Imaging.ColorMatrix wmColorMatrix 
= new System.Drawing.Imaging.ColorMatrix(colorMatrixElements);
            imageAttributes.SetColorMatrix(wmColorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap);

            
//确定水印边距
            int xPos = imgPhotoWidth - imgWatermarkWidthNew;
            
int yPos = imgPhotoHeight - imgWatermarkHeightNew;
            
int xPosOfWm = 0;
            
int yPosOfWm = 0;

            
if (xPos > intDistance)
                xPosOfWm 
= xPos - intDistance;
            
else
                xPosOfWm 
= xPos;

            
if (yPos > intDistance)
                yPosOfWm 
= yPos - intDistance;
            
else
                yPosOfWm 
= yPos;

            gWatermark.DrawImage(imgWatermark, 
new Rectangle(xPosOfWm, yPosOfWm, imgWatermarkWidthNew, imgWatermarkHeightNew), 00, imgWatermarkWidth, imgWatermarkHeight, GraphicsUnit.Pixel, imageAttributes);

            imgPhoto 
= bmWatermark;


            imgPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            
//销毁对象
            gbmPhoto.Dispose();
            gWatermark.Dispose();

            imgPhoto.Dispose();
            imgWatermark.Dispose();

            
return true;
        }

        
catch (Exception ex)
        
{
            
return false;
        }

    }




    
/// <summary>
    
/// 文字水印
    
/// </summary>
    
/// <param name="ImgFile">原图文件地址</param>
    
/// <param name="TextFont">水印文字</param>
    
/// <param name="sImgPath">文字水印图片保存地址</param>
    
/// <param name="Alpha">文字透明度 其数值的范围在0到255</param>
    
/// <param name="widthFont">文字块在图片中所占宽度比例</param>
    
/// <param name="hScale">高度位置</param>

    public bool TextWater(string ImgFile, string TextFont, string sImgPath, int Alpha, float widthFont, float hScale)
    
{
        
try
        
{
            FileStream fs 
= new FileStream(ImgFile, FileMode.Open);
            BinaryReader br 
= new BinaryReader(fs);
            
byte[] bytes = br.ReadBytes((int)fs.Length);
            br.Close();
            fs.Close();
            MemoryStream ms 
= new MemoryStream(bytes);

            System.Drawing.Image imgPhoto 
= System.Drawing.Image.FromStream(ms);
            
int imgPhotoWidth = imgPhoto.Width;
            
int imgPhotoHeight = imgPhoto.Height;

            Bitmap bmPhoto 
= new Bitmap(imgPhotoWidth, imgPhotoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(
7272);
            Graphics gbmPhoto 
= Graphics.FromImage(bmPhoto);
            gbmPhoto.Clear(Color.FromName(
"white"));//gif背景色
            gbmPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            gbmPhoto.SmoothingMode 
= System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            gbmPhoto.DrawImage(imgPhoto, 
new Rectangle(00, imgPhotoWidth, imgPhotoHeight), 00, imgPhotoWidth, imgPhotoHeight, GraphicsUnit.Pixel);

            
//建立字体大小的数组,循环找出适合图片的水印字体
            int[] sizes = new int[] 100080070065060056054050045040038036034032030028026024022020018016014012010080726448322826242028161412108642 };
            System.Drawing.Font crFont 
= null;
            System.Drawing.SizeF crSize 
= new SizeF();
            
for (int i = 0; i < 43; i++)
            
{
                crFont 
= new Font("arial", sizes[i], FontStyle.Bold);
                crSize 
= gbmPhoto.MeasureString(TextFont, crFont);

                
if ((ushort)crSize.Width < (ushort)imgPhotoWidth * widthFont)
                    
break;
            }


            
//设置水印字体的位置
            int yPixlesFromBottom = (int)(imgPhotoHeight * hScale);
            
float yPosFromBottom = ((imgPhotoHeight - yPixlesFromBottom) - (crSize.Height / 2));
            
float xCenterOfImg = (imgPhotoWidth * 1 / 2);

            System.Drawing.StringFormat StrFormat 
= new System.Drawing.StringFormat();
            StrFormat.Alignment 
= System.Drawing.StringAlignment.Center;

            
//画两次制造透明效果
            System.Drawing.SolidBrush semiTransBrush2 = new System.Drawing.SolidBrush(Color.FromArgb(Alpha, 000));
            gbmPhoto.DrawString(TextFont, crFont, semiTransBrush2, 
new System.Drawing.PointF(xCenterOfImg + 1, yPosFromBottom + 1), StrFormat);

            System.Drawing.SolidBrush semiTransBrush 
= new System.Drawing.SolidBrush(Color.FromArgb(Alpha, 255255255));
            gbmPhoto.DrawString(TextFont, crFont, semiTransBrush, 
new System.Drawing.PointF(xCenterOfImg, yPosFromBottom), StrFormat);

            bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            gbmPhoto.Dispose();
            imgPhoto.Dispose();
            bmPhoto.Dispose();

            
return true;
        }

        
catch (Exception ex)
        
{
            
return false;
        }

    }



    
/// <summary>
    
/// 缩略图
    
/// </summary>
    
/// <param name="ImgFile">原图文件地址</param>
    
/// <param name="sImgPath">缩略图保存地址</param>
    
/// <param name="ResizeWidth">缩略图宽度</param>
    
/// <param name="ResizeHeight">缩略图高度</param>
    
/// <param name="BgColor">缩略图背景颜色,注意,背景颜色只能指定KnownColor中的值,如white,blue,red,green等</param>

    public bool ResizeImg(string ImgFile, string sImgPath, int ResizeWidth, int ResizeHeight, string BgColor)
    
{
        
try
        
{
            FileStream fs 
= new FileStream(ImgFile, FileMode.Open);
            BinaryReader br 
= new BinaryReader(fs);
            
byte[] bytes = br.ReadBytes((int)fs.Length);
            br.Close();
            fs.Close();
            MemoryStream ms 
= new MemoryStream(bytes);

            System.Drawing.Image imgPhoto 
= System.Drawing.Image.FromStream(ms);
            
int imgPhotoWidth = imgPhoto.Width;
            
int imgPhotoHeight = imgPhoto.Height;
            
int StartX = 0;
            
int StartY = 0;
            
int NewWidth = imgPhotoWidth;
            
int NewHeight = imgPhotoHeight;

            
//计算缩放图片尺寸
            if (NewWidth > ResizeWidth)
            
{
                NewWidth 
= ResizeWidth;
                NewHeight 
= Convert.ToInt32(imgPhotoHeight * Math.Round(Convert.ToDecimal(NewWidth) / Convert.ToDecimal(imgPhotoWidth), 10));
            }


            
if (NewHeight > ResizeHeight)
            
{
                NewHeight 
= ResizeHeight;
                NewWidth 
= Convert.ToInt32(imgPhotoWidth * Math.Round(Convert.ToDecimal(NewHeight) / Convert.ToDecimal(imgPhotoHeight), 10));
            }


            StartX 
= ResizeWidth - NewWidth;
            StartY 
= ResizeHeight - NewHeight;

            StartX 
= StartX > 0 ? StartX / 2 : 0;
            StartY 
= StartY > 0 ? StartY / 2 : 0;

            Bitmap bmPhoto 
= new Bitmap(ResizeWidth, ResizeHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(
7272);
            Graphics gbmPhoto 
= Graphics.FromImage(bmPhoto);
            gbmPhoto.Clear(Color.FromName(BgColor));
            gbmPhoto.InterpolationMode 
= System.Drawing.Drawing2D.InterpolationMode.High;
            gbmPhoto.SmoothingMode 
= System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            gbmPhoto.DrawImage(imgPhoto, 
new Rectangle(StartX, StartY, NewWidth, NewHeight), new Rectangle(00, imgPhotoWidth, imgPhotoHeight), GraphicsUnit.Pixel);
            bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            imgPhoto.Dispose();
            gbmPhoto.Dispose();
            bmPhoto.Dispose();

            
return true;
        }

        
catch (Exception err)
        
{
            
return false;
        }

    }



    
/// <summary>
    
/// 图片剪切
    
/// </summary>
    
/// <param name="ImgFile">原图文件地址</param>
    
/// <param name="sImgPath">缩略图保存地址</param>
    
/// <param name="PointX">剪切起始点 X坐标</param>
    
/// <param name="PointY">剪切起始点 Y坐标</param>
    
/// <param name="CutWidth">剪切宽度</param>
    
/// <param name="CutHeight">剪切高度</param>

    public bool CutImg(string ImgFile, string sImgPath, int PointX, int PointY, int CutWidth, int CutHeight)
    
{
        
try
        
{
            FileStream fs 
= new FileStream(ImgFile, FileMode.Open);
            BinaryReader br 
= new BinaryReader(fs);
            
byte[] bytes = br.ReadBytes((int)fs.Length);
            br.Close();
            fs.Close();
            MemoryStream ms 
= new MemoryStream(bytes);
            System.Drawing.Image imgPhoto 
= System.Drawing.Image.FromStream(ms);

            
//System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(ImgFile);
            
//此处只能用filestream,用 System.Drawing.Image则会报多过进程访问文件的错误,会锁定文件
            Bitmap bmPhoto = new Bitmap(CutWidth, CutHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(
7272);
            Graphics gbmPhoto 
= Graphics.FromImage(bmPhoto);
            gbmPhoto.InterpolationMode 
= System.Drawing.Drawing2D.InterpolationMode.High;
            gbmPhoto.SmoothingMode 
= System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            gbmPhoto.DrawImage(imgPhoto, 
new Rectangle(00, CutWidth, CutHeight), new Rectangle(PointX, PointY, CutHeight, CutHeight), GraphicsUnit.Pixel);
            bmPhoto.Save(sImgPath, System.Drawing.Imaging.ImageFormat.Jpeg);

            imgPhoto.Dispose();
            gbmPhoto.Dispose();
            bmPhoto.Dispose();

            
return true;
        }

        
catch (Exception err)
        
{
            
return false;
        }

    }

}

本文转自博客园cloudgamer的博客,原文链接:图片编辑类,如需转载请自行联系原博主。

相关文章
|
Shell 测试技术
Airtest如何自动连接重启后的设备并继续执行自动化脚本呢?
Airtest如何自动连接重启后的设备并继续执行自动化脚本呢?
351 0
|
Prometheus 监控 Cloud Native
hyperf| hyperf/metric 上手指南
这期又开始聊微服务的基础设施之一: 实时监控. 更准确的说法, 基于 prometheus 的实时监控. 关于技术选型这里就不多啰嗦啦, 很多时候「从众」或者「用脚投票」往往是最有效的
1062 0
|
9月前
|
存储 SQL Apache
为什么 Apache Doris 是比 Elasticsearch 更好的实时分析替代方案?
本文将从技术选型的视角,从开放性、系统架构、实时写入、实时存储、实时查询等多方面,深入分析 Apache Doris 与 Elasticsearch 的能力差异及性能表现
853 17
为什么 Apache Doris 是比 Elasticsearch 更好的实时分析替代方案?
|
9月前
|
人工智能 运维 数据可视化
凌晨急诊室诞生的疫苗系统:一个宝妈的AI破局之路
本文分享了一位妈妈在急诊室经历后,将技术与母爱结合的心路历程。从凌晨抱着高烧儿子就医,同时处理工作告警的崩溃时刻,到意识到妈妈和程序员都是“运维工程师”,作者逐步构建了宝宝疫苗管理系统。文章介绍了系统从静态命令行工具升级为动态智能预警系统的全过程,包括环境搭建、核心代码解析及家庭协同功能实现,并总结了碎片时间开发法与防坑指南。最终,作者通过技术赋予母爱温度,为其他妈妈提供了实用资源包,展现了代码背后的人文关怀。
267 5
|
设计模式 测试技术 容器
依赖注入与控制反转:理解与应用
【8月更文挑战第22天】
633 0
|
存储 Linux Shell
常用vim命令和vim基本使用及Linux用户的管理,用户和组相关文件
这篇文章介绍了Vim编辑器的基本使用、常用命令和模式,以及Linux系统中用户和组的管理方法,包括用户和组相关文件如/etc/passwd、/etc/shadow和/etc/group的说明。
常用vim命令和vim基本使用及Linux用户的管理,用户和组相关文件
|
Java 数据库连接 数据格式
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
IOC/DI配置管理DruidDataSource和properties、核心容器的创建、获取bean的方式、spring注解开发、注解开发管理第三方bean、Spring整合Mybatis和Junit
【Java笔记+踩坑】Spring基础2——IOC,DI注解开发、整合Mybatis,Junit
|
物联网 人机交互 语音技术
计算机中输入输出设备
【7月更文挑战第28天】
430 1
|
缓存 监控 中间件
构建高效的Go语言Web服务器:基于Fiber框架的性能优化实践
在追求极致性能的Web开发领域,Go语言(Golang)凭借其高效的并发处理能力、垃圾回收机制及简洁的语法赢得了广泛的青睐。本文不同于传统的性能优化教程,将深入剖析如何在Go语言环境下,利用Fiber这一高性能Web框架,通过精细化配置、并发策略调整及代码层面的微优化,构建出既快速又稳定的Web服务器。通过实际案例与性能测试数据对比,揭示一系列非直觉但极为有效的优化技巧,助力开发者在快节奏的互联网环境中抢占先机。
|
存储 缓存 前端开发
单页应用(SPA)的架构与优化:深度探索与实践
【6月更文挑战第11天】本文探讨了单页应用(SPA)的架构与优化,包括前后端分离、路由管理和状态管理基础,以及加载性能、路由和状态管理的优化策略。通过合理设计与优化,SPA能提供流畅体验,同时应对加载性能、路由导航和状态管理的挑战。文章旨在帮助读者理解并提升SPA应用的性能和用户体验。