Files
KJD_WebService/AllBase/ImageCut.cs
T
2025-06-29 19:38:31 +08:00

500 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using ZXing;
namespace AllBase
{
public class ImageCut
{
/// <summary>
/// 正方型裁剪
/// 以图片中心为轴心,截取正方型,然后等比缩放
/// 用于头像处理
/// </summary>
/// <remarks>吴剑 2010-11-23</remarks>
/// <param name="path">原图HttpPostedFile对象</param>
/// <param name="fileSaveUrl">缩略图存放地址</param>
/// <param name="side">指定的边长(正方型)</param>
/// <param name="quality">质量(范围0-100)</param>
public static void CutForSquare(string path, string fileSaveUrl, int side, int quality, out int width,
out int height)
{
string exe = path.Split('.')[path.Split('.').Length - 1].ToLower();
Image initImage = null;
width = 0;
height = 0;
try
{
FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
initImage = Image.FromStream(fileStream);
fileStream.Close();
fileStream.Dispose();
}
catch (Exception e)
{
LogSave.Add(e.Message);
return;
}
width = initImage.Width;
height = initImage.Height;
//原图宽高均小于模版,不作处理,直接保存
if (initImage.Width <= side || initImage.Height <= side)
{
return;
//initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
}
//关键质量控制
//获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo ici = null, defCodecInfo = null;
foreach (ImageCodecInfo i in icis)
{
if (i.MimeType == "image/jpeg")
defCodecInfo = i;
if ((exe == "jpg" || exe == "jpeg") && i.MimeType == "image/jpeg")
{
ici = i;
}
if (exe == "bmp" && i.MimeType == "image/bmp")
{
ici = i;
}
if (exe == "png" && i.MimeType == "image/png")
{
ici = i;
}
if (exe == "gif" && i.MimeType == "image/gif")
{
ici = i;
}
}
if (ici == null)
ici = defCodecInfo;
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
//原始图片的宽、高
int initWidth = initImage.Width;
int initHeight = initImage.Height;
int sizeW = 50, sizeH = 50;
if (initWidth > initHeight)
sizeW = 70;
else
sizeH = 70;
width = initWidth - sizeW * 2;
height = initHeight - sizeH * 2;
//FileBase.Delete(path);
Image pickedImage = new Bitmap(width, height);
Graphics pickedG = Graphics.FromImage(pickedImage);
pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
//定位
Rectangle fromR = new Rectangle(sizeW - 20, sizeH, width, height);
Rectangle toR = new Rectangle(0, 0, width, height);
//画图
pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
//将截图对象赋给原图
Image initImagex = (System.Drawing.Image)pickedImage.Clone();
//释放截图资源
pickedG.Dispose();
pickedImage.Dispose();
initImage.Clone();
initImage.Dispose();
try
{
initImagex.Save(fileSaveUrl, ici, ep);
}
catch (Exception e)
{
LogSave.Add(e.Message);
}
//释放关键质量控制所用资源
ep.Dispose();
}
/// <summary>
/// 是否二维码
/// </summary>
/// <param name="strSavePath"></param>
/// <returns></returns>
public static bool GetErWeiMa(string strSavePath)
{
BarcodeReader reader = new BarcodeReader();
FileStream fileStream = new FileStream(strSavePath, FileMode.Open, FileAccess.Read);
try
{
Image initImage = Image.FromStream(fileStream);
fileStream.Close();
fileStream.Dispose();
if (initImage.Width < 10 || initImage.Height < 10)
return false;
Result result = reader.Decode((Bitmap)initImage);
if (result == null || string.IsNullOrEmpty(result.Text))
return false;
}
catch
{
return false;
}
FileBase.Delete(strSavePath);
return true;
//return result.Text;
}
/// <summary>
/// 是否二维码
/// </summary>
/// <param name="strSavePath"></param>
/// <returns></returns>
public static bool GetErWeiMa(byte[] file, out int width, out int height)
{
width = 0;
height = 0;
try
{
MemoryStream ms = new MemoryStream(file);
Image initImage = Image.FromStream(ms);
ms.Close();
width = initImage.Width;
height = initImage.Height;
if (initImage.Width < 10 || initImage.Height < 10)
{
initImage = null;
return false;
}
BarcodeReader reader = new BarcodeReader();
Result result = reader.Decode((Bitmap)initImage);
if (result == null || string.IsNullOrEmpty(result.Text))
{
reader = null;
result = null;
initImage = null;
return false;
}
reader = null;
result = null;
initImage = null;
}
catch
{
return false;
}
return true;
//return result.Text;
}
/// <summary>
/// 正方型裁剪
/// 以图片中心为轴心,截取正方型,然后等比缩放
/// 用于头像处理
/// </summary>
/// <remarks>吴剑 2010-11-23</remarks>
/// <param name="postedFile">原图HttpPostedFile对象</param>
/// <param name="fileSaveUrl">缩略图存放地址</param>
/// <param name="side">指定的边长(正方型)</param>
/// <param name="quality">质量(范围0-100)</param>
public static void CutForSquare(System.IO.Stream fromFile, string fileSaveUrl, int side, int quality)
{
//创建目录
string dir = Path.GetDirectoryName(fileSaveUrl);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
//原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);
//原图宽高均小于模版,不作处理,直接保存
if (initImage.Width <= side && initImage.Height <= side)
{
initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else
{
//原始图片的宽、高
int initWidth = initImage.Width;
int initHeight = initImage.Height;
//非正方型先裁剪为正方型
if (initWidth != initHeight)
{
//截图对象
System.Drawing.Image pickedImage = null;
System.Drawing.Graphics pickedG = null;
//宽大于高的横图
if (initWidth > initHeight)
{
//对象实例化
pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
pickedG = System.Drawing.Graphics.FromImage(pickedImage);
//设置质量
pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//定位
Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
Rectangle toR = new Rectangle(0, 0, initHeight, initHeight);
//画图
pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
//重置宽
initWidth = initHeight;
}
//高大于宽的竖图
else
{
//对象实例化
pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
pickedG = System.Drawing.Graphics.FromImage(pickedImage);
//设置质量
pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//定位
Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
Rectangle toR = new Rectangle(0, 0, initWidth, initWidth);
//画图
pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
//重置高
initHeight = initWidth;
}
//将截图对象赋给原图
initImage = (System.Drawing.Image)pickedImage.Clone();
//释放截图资源
pickedG.Dispose();
pickedImage.Dispose();
}
//缩略图对象
System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side);
System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage);
//设置质量
resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
//用指定背景色清空画布
resultG.Clear(Color.White);
//绘制缩略图
resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel);
//关键质量控制
//获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo ici = null;
foreach (ImageCodecInfo i in icis)
{
if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
{
ici = i;
}
}
EncoderParameters ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
//保存缩略图
resultImage.Save(fileSaveUrl, ici, ep);
//释放关键质量控制所用资源
ep.Dispose();
//释放缩略图资源
resultG.Dispose();
resultImage.Dispose();
//释放原始图片资源
initImage.Dispose();
}
}
/// <summary>
/// 判断文件类型是否为WEB格式图片
/// (注:JPG,GIF,BMP,PNG)
/// </summary>
/// <param name="contentType">HttpPostedFile.ContentType</param>
/// <returns></returns>
public static bool IsWebImage(string contentType)
{
if (contentType == "image/pjpeg" || contentType == "image/jpeg" || contentType == "image/gif" || contentType == "image/bmp" || contentType == "image/png")
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 压缩图片获得图片MD5 32位指纹
/// </summary>
/// <param name="imgToResize"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <returns></returns>
public static long ResizeImage(Image imgToResize, int width, int height)
{
try
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)width / (float)sourceWidth);
nPercentH = ((float)height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage(b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
imgToResize.Dispose();
long md5 = ToGray(ref b, width, height);
return md5;
}
catch (Exception e)
{
LogSave.Add("计算图片指纹失败:"+e.Message);
return 0;
}
}
/// <summary>
/// 图像灰度化,并计算指纹
/// </summary>
/// <param name="bmp"></param>
/// <returns></returns>
public static long ToGray(ref Bitmap bmp, int width, int height)
{
byte[] b = new byte[width * height];
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
Color color = bmp.GetPixel(i, j);
int gray = (int)(color.R * 0.3 + color.G * 0.59 + color.B * 0.11);
gray = gray / 16;
b[i * bmp.Width + j] = (byte)gray;
}
}
return BaseClass.GetLong(b);
}
/// <summary>
/// 处理图片(四边裁剪+水印)
/// </summary>
/// <param name="bytesOld"></param>
/// <param name="sWaterMark"></param>
/// <returns></returns>
public static void HandleImage(ref byte[] bytesOld,bool flag)
{
try
{
Image img = BytesToImage(ref bytesOld);
int iniWidth = img.Width;
int iniHeight = img.Height;
Random random = new Random();
int cutPixl = random.Next(1, 50); //左边切除的像素
int cutPixr = random.Next(1, 50); //右边切除的像素
int cutPixt = random.Next(1, 50); //顶部切除的像素
int cutPixb = random.Next(1, 50); //底部切除的像素
if (!flag)
{
cutPixl = 0; //左边切除的像素
cutPixr = 0; //右边切除的像素
cutPixt = 0; //顶部切除的像素
cutPixb = 0; //底部切除的像素
}
Bitmap bitmap = CutImage(ref bytesOld, cutPixl, cutPixr, iniWidth - cutPixl - cutPixt, iniHeight - cutPixr - cutPixb);
if(bitmap==null)
return;
MemoryStream ms = new MemoryStream();
ImageCodecInfo icc = GetEncoderInfo("image/jpeg");
EncoderParameters ep = new EncoderParameters(1)
{
Param = { [0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 75l) }
};
bitmap.Save(ms, icc, ep);
bytesOld = ms.ToArray();
}
catch
{
}
}
/// <summary>
/// 字节数组转换为图片
/// </summary>
/// <param name="buffer">字节数组</param>
/// <returns>图片</returns>
public static Image BytesToImage(ref byte[] buffer)
{
var ms = new MemoryStream(buffer, 0, buffer.Length);
return Image.FromStream(ms);
}
/// <summary>
/// 裁剪图片四边
/// </summary>
/// <param name="bytes">原始图片字节流</param>
/// <param name="iStartX">裁剪开始x坐标</param>
/// <param name="iStartY">裁剪开始y坐标</param>
/// <param name="iWidth">裁剪宽度</param>
/// <param name="iHeight">裁剪高度</param>
/// <returns></returns>
public static Bitmap CutImage(ref byte[] bytes, int iStartX, int iStartY, int iWidth, int iHeight)
{
try
{
Image image = BytesToImage(ref bytes);
Bitmap b = new Bitmap(image);
if (bytes == null) return null;
Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format24bppRgb);
Graphics g = Graphics.FromImage(bmpOut);
g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(iStartX, iStartY, iWidth, iHeight), GraphicsUnit.Pixel);
g.Dispose();
return bmpOut;
}
catch
{
return null;
}
}
public static ImageCodecInfo GetEncoderInfo(string mimeType)
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for (j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType == mimeType)
return encoders[j];
}
return null;
}
}
}