您现在的位置是:首页 > C# > C#实现图片无损压缩

C#实现图片无损压缩

王递杰 2023年9月4日 C#

class Program
{
	static void Main(string[] args)
	{
		string imagePath = @"d:\dy.jpg"; //要压缩的图片路径
		string savePath = @"d:\dy_ys.jpg";//压缩后保存的路径
		using (FileStream fs = new FileStream(imagePath, FileMode.Open))
		{
			byte[] byteData = new byte[fs.Length];
			fs.Read(byteData, 0, byteData.Length);
			//压缩质量60
			CompressImage(byteData, savePath, 60);
		}
	}


	/// <summary>
	/// 压缩图片
	/// </summary>
	/// <param name="buffer">图片byte数据</param>
	/// <param name="outPath">保存位置</param>
	/// <param name="flag">图片压缩质量:0-100</param>
	/// <returns></returns>
	public static void CompressImage(byte[] buffer, string outPath, int flag)
	{
		MemoryStream ms = new MemoryStream(buffer);//使用byte
		Image iSource = Image.FromStream(ms);//如果使用路径 就用下面一个
		//Image iSource = Image.FromFile(path);
		ImageFormat tFormat = iSource.RawFormat;
		EncoderParameters ep = new EncoderParameters();
		long[] qy = new long[1];
		qy[0] = flag;
		EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
		ep.Param[0] = eParam;
		try
		{
			ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders();
			ImageCodecInfo jpegICIinfo = null;
			for (int x = 0; x < arrayICI.Length; x++)
			{
				if (arrayICI[x].FormatDescription.Equals("JPEG"))
				{
					jpegICIinfo = arrayICI[x];
					break;
				}
			}
			if (jpegICIinfo != null)
				iSource.Save(outPath, jpegICIinfo, ep);
			else
				iSource.Save(outPath, tFormat);
		}
		catch (Exception ex)
		{
			Console.WriteLine("压缩异常:" + ex.ToString());
		}
		finally
		{
			iSource.Dispose();
		}
	}
}


评论

暂无评论