C#控制生成图片的大小

时间:2023-03-08 15:50:44
        private void button1_Click(object sender, EventArgs e)
{
using (Bitmap bitmap = new Bitmap("d:\\a.jpg"))
{
string f = string.Format("d:\\{0}.jpg", Guid.NewGuid());
KiSaveAsJPEG(bitmap, f, (int)this.numericUpDown1.Value);
}
} /**/
/// <summary>
/// 保存JPG时用
/// </summary>
/// <param name="mimeType"></param>
/// <returns>得到指定mimeType的ImageCodecInfo</returns>
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType) return ici;
}
return null;
} /**/
/// <summary>
/// 保存为JPEG格式,支持压缩质量选项
/// </summary>
/// <param name="bmp"></param>
/// <param name="FileName"></param>
/// <param name="Qty"></param>
/// <returns></returns>
public static bool KiSaveAsJPEG(Bitmap bmp, string FileName, int Qty)
{
try
{
EncoderParameter p;
EncoderParameters ps;
ps = new EncoderParameters();
p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Qty);
ps.Param[] = p;
bmp.Save(FileName, GetCodecInfo("image/jpeg"), ps);
return true;
}
catch
{
return false;
} }

Qty代表质量等级:90代表90%.