tijian_tieying/web/Common/ImgUtil.cs
2025-02-20 12:14:39 +08:00

83 lines
3.0 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.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZWL.Common
{
public class ImgUtil
{
#region base64转换为图片并返回图片路径
public static string ConvertImg(string strBase)
{
var base64 = strBase.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
byte[] bytes = Convert.FromBase64String(base64);
MemoryStream memStream = new MemoryStream(bytes);
Image mImage = Image.FromStream(memStream);
//Bitmap bp = new Bitmap(mImage);
Bitmap bp = PercentImage(mImage);
MemoryStream ms = new MemoryStream();
string strPhotoPath = ConfigurationManager.AppSettings["Photo"].ToString();
if (!Directory.Exists(strPhotoPath))
{
DirectoryInfo directoryInfo = new DirectoryInfo(strPhotoPath);
directoryInfo.Create();
}
strPhotoPath += "\\" + Guid.NewGuid().ToString() + ".jpg";
bp.Save(strPhotoPath, System.Drawing.Imaging.ImageFormat.Jpeg);
return strPhotoPath;
}
/// <summary>
/// 压缩图片宽度最大为1200
/// 2023-11-29 xulu
/// </summary>
/// <param name="srcImage"></param>
/// <returns></returns>
public static Bitmap PercentImage(System.Drawing.Image srcImage)
{
int newW = srcImage.Width < 1200 ? srcImage.Width : 1200;
int newH = int.Parse(Math.Round(srcImage.Height * (double)newW / srcImage.Width).ToString());
try
{
Bitmap b = new Bitmap(newW, newH);
Graphics g = Graphics.FromImage(b);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
g.DrawImage(srcImage, new System.Drawing.Rectangle(0, 0, newW, newH), new System.Drawing.Rectangle(0, 0, srcImage.Width, srcImage.Height), GraphicsUnit.Pixel);
g.Dispose();
return b;
}
catch (Exception)
{
return null;
}
}
#endregion
#region base64
public static string DocumentToBase64Str(string fileName)
{
try
{
FileStream filestream = new FileStream(fileName, FileMode.Open);
byte[] bt = new byte[filestream.Length];
//调用read读取方法
filestream.Read(bt, 0, bt.Length);
string base64Str = Convert.ToBase64String(bt);
filestream.Close();
return base64Str;
}
catch (Exception ex)
{
return "";
}
}
#endregion
}
}