fileExtension = httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf(
(HttpStatusCode.OK, result);
工具方法:
public class ImageToolsB
/// <summary>
/// 无损压缩图片
/// </summary>
/// <param name="sFile">原图片地址</param>
/// <param name="dFile">压缩后保存图片地址</param>
/// <param name="flag">压缩质量(数字越小压缩率越高)1-100</param>
/// <param name="size">压缩后图片的最大大小</param>
/// <param name="sfsc">是否是第一次调用</param>
/// <returns></returns>
public static bool CompressImage(string sFile, string dFile, int flag = 90, int size = 500, bool sfsc = true)
//如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true
FileInfo firstFileInfo = new FileInfo(sFile);
if (sfsc == true && firstFileInfo.Length < size * 1024)
firstFileInfo.CopyTo(dFile);
return true;
Image iSource = Image.FromFile(sFile);
ImageFormat tFormat = iSource.RawFormat;
int dHeight = iSource.Height / 2;
int dWidth = iSource.Width / 2;
int sW = 0, sH = 0;
//按比例缩放
Size tem_size = new Size(iSource.Width, iSource.Height);
if (tem_size.Width > dHeight || tem_size.Width > dWidth)
if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth))
sW = dWidth;
sH = (dWidth * tem_size.Height) / tem_size.Width;
sH = dHeight;
sW = (tem_size.Width * dHeight) / tem_size.Height;
sW = tem_size.Width;
sH = tem_size.Height;
Bitmap ob = new Bitmap(dWidth, dHeight);
Graphics g = Graphics.FromImage(ob);
g.Clear(Color.WhiteSmoke);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel);
g.Dispose();
//以下代码为保存图片时,设置压缩质量
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = flag;//设置压缩的比例1-100
EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
ep.Param[0] = eParam;
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
if (arrayICI[x].FormatDescription.Equals("JPEG"))
jpegICIinfo = arrayICI[x];
break;
if (jpegICIinfo != null)
ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径
FileInfo fi = new FileInfo(dFile);
if (fi.Length > 1024 * size)
flag = flag - 10;
CompressImage(sFile, dFile, flag, size, false);
ob.Save(dFile, tFormat);
iSource.Dispose();
return true;
catch (Exception ex)
return false;
finally
iSource.Dispose();
ob.Dispose();
#region ImageCompress
/// <summary>
/// 图片压缩 ImageCompress.CompressionImage(fileSelect,@"d:\",50);
/// </summary>
/// <param name="imagePath">图片文件路径</param>
/// <param name="targetFolder">保存文件夹</param>
/// <param name="quality">压缩质量</param>
/// <param name="fileSuffix">压缩后的文件名后缀(防止直接覆盖原文件)</param>
public static void CompressionImage(string imagePath, string targetFolder, long quality = 100, string fileSuffix = "compress")
if (!File.Exists(imagePath))
throw new FileNotFoundException();
if (!Directory.Exists(targetFolder))
Directory.CreateDirectory(targetFolder);
var fileInfo = new FileInfo(imagePath);
var fileName = fileInfo.Name.Replace(fileInfo.Extension, "");
var fileFullName = Path.Combine($"{targetFolder}", $"{fileName}_{fileSuffix}{fileInfo.Extension}");
var imageByte = CompressionImage(imagePath, quality);
var ms = new MemoryStream(imageByte);
var image = Image.FromStream(ms);
image.Save(fileFullName);
ms.Close();
ms.Dispose();
image.Dispose();
/// <summary>
/// 压缩图片
/// </summary>
/// <param name="imagePath">压缩前图片全路径</param>
/// <param name="compressfilefullName">压缩后图片全路径</param>
/// <param name="quality">压缩质量</param>
public static void CompressionImage(string imagePath, string compressfilefullName, long quality = 100)
if (!File.Exists(imagePath))
throw new FileNotFoundException();
var imageByte = CompressionImage(imagePath, quality);
var ms = new MemoryStream(imageByte);
var image = Image.FromStream(ms);
image.Save(compressfilefullName);
ms.Close();
ms.Dispose();
image.Dispose();
private static byte[] CompressionImage(string imagePath, long quality)
using (var fileStream = new FileStream(imagePath, FileMode.Open))
using (var img = Image.FromStream(fileStream))
using (var bitmap = new Bitmap(img))
//var codecInfo = GetEncoder(img.RawFormat);
//转成jpg
var codecInfo = GetEncoder(ImageFormat.Jpeg);
var myEncoder = System.Drawing.Imaging.Encoder.Quality;
var myEncoderParameters = new EncoderParameters(1);
var myEncoderParameter = new EncoderParameter(myEncoder, quality);
myEncoderParameters.Param[0] = myEncoderParameter;
using (var ms = new MemoryStream())
bitmap.Save(ms, codecInfo, myEncoderParameters);
myEncoderParameters.Dispose();
myEncoderParameter.Dispose();
return ms.ToArray();
private static ImageCodecInfo GetEncoder(ImageFormat format)
var codecs = ImageCodecInfo.GetImageDecoders();
return codecs.FirstOrDefault(codec => codec.FormatID == format.Guid);
#endregion
在压缩png时,发现图片文件没有变小,反面变大了,
在网上找方法:C# Bitmap/png转成jpg格式,压缩图片
//转成jpg
var codecInfo = GetEncoder(ImageFormat.Jpeg);
string fileExtension = request.fileFullName.Substring(request.fileFullName.LastIndexOf('.') + 1).ToLower();
var fileName = request.fileFullName.Substring(request.fileFullName.LastIndexOf(@"\") + 1);
参考:https://www.cnblogs.com/testsec/p/6095729.html C# Bitmap/png转成jpg格式,压缩图片
https://blog.csdn.net/nodeman/article/details/80661995 c# 无损高质量压缩图片代码
https://www.cnblogs.com/wdw984/p/13112621.html C#进行图片压缩(对jpg压缩效果最好)
此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。