using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Imaging;
namespace SaveImageHigh
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Drawing.Image image = System.Drawing.Image.FromFile("D:\\111.jpg");
SaveImageForSpecifiedQuality(image, "D:\\222.jpg", 100, ImageFormat.Jpeg);
image.Dispose();
}
/// <summary>
/// 按指定的压缩质量及格式保存图片(微软的Image.Save方法保存到图片压缩质量为75)
/// </summary>
/// <param name="sourceImage">要保存的图片的Image对象</param>
/// <param name="savePath">图片要保存的绝对路径</param>
/// <param name="imageQualityValue">图片要保存的压缩质量,该参数的值为1至100的整数,数值越大,保存质量越好</param>
/// <returns>保存成功,返回true;反之,返回false</returns>
public bool SaveImageForSpecifiedQuality(System.Drawing.Image sourceImage, string savePath, int imageQualityValue,System.Drawing.Imaging.ImageFormat format)
{
//以下代码为保存图片时,设置压缩质量
EncoderParameters encoderParameters = new EncoderParameters();
EncoderParameter encoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, imageQualityValue);
encoderParameters.Param[0] = encoderParameter;
try
{
ImageCodecInfo[] ImageCodecInfoArray = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo jpegImageCodecInfo = null;
for (int i = 0; i < ImageCodecInfoArray.Length; i++)
{
if (ImageCodecInfoArray[i].FormatDescription.Equals(format.ToString().ToUpper()))
{
jpegImageCodecInfo = ImageCodecInfoArray[i];
break;
}
}
sourceImage.Save(savePath, jpegImageCodecInfo, encoderParameters);
return true;
}
catch
{
return false;
}
}
}
}