SqlSer数据库设置保存图片字段类型为Image类型
对应保存
方法参数为图片路径,压缩后路径,压缩最大宽度,压缩最大高度
引用类型using System.Data; using System.Drawing; using System.IO;
\完整类
/// <summary>
/// 按比例缩放,图片不会变形,会优先满足原图和最大长宽比例最高的一项
/// </summary>
/// <param name="oldPath">图片路径</param>
/// <param name="newPath">压缩后路径</param>
/// <param name="maxWidth">压缩最大宽度</param>
/// <param name="maxHeight">压缩最大高度</param>
public static void CompressPrecent(string oldPath, string newPath, int maxWidth, int maxHeight)
{
System.Drawing.Image _sourceImg = System.Drawing.Image.FromFile(oldPath);
double _newW = maxWidth;
double _newH = maxWidth;
double percentWidth = (double)_sourceImg.Width > maxWidth ? maxWidth : _sourceImg.Width;
if (_sourceImg.Height * (double)percentWidth / _sourceImg.Width > maxHeight)
{
_newH = maxHeight;
_newW = maxHeight / (double)_sourceImg.Height * _sourceImg.Width;
}
else
{
_newW = percentWidth;
_newH = (percentWidth / _sourceImg.Width) * _sourceImg.Height;
}
System.Drawing.Image bitmap = new Bitmap((int)_newW, (int)_newH);
Graphics g = Graphics.FromImage(bitmap);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.Clear(System.Drawing.Color.Transparent);
g.DrawImage(_sourceImg, new System.Drawing.Rectangle(0, 0, (int)_newW, (int)_newH),
new System.Drawing.Rectangle(0, 0, _sourceImg.Width, _sourceImg.Height), GraphicsUnit.Pixel);
_sourceImg.Dispose();
g.Dispose();
bitmap.Save(newPath, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
}
今天就分享到这里,敬请关注后面
初来乍到,请多多指教,大神勿喷。若有错误之处,欢迎指导