/// <summary>
/// 把位图保存为jpeg格式,并可以这是保存质量
/// </summary>
/// <param name="b">位图</param>
/// <param name="name">文件名</param>
/// <param name="quality">保存质量</param>
/// <remarks>质量范围0-100,类型为long</remarks>
private void JpegSave( Bitmap b, string name, long quality )
{
ImageCodecInfo myImageCodecInfo;
Encoder myEncoder;
EncoderParameter myEncoderParameter;
EncoderParameters myEncoderParameters;
myImageCodecInfo = FrmMain.GetEncoderInfo( "image/jpeg" );
myEncoder = Encoder.Quality;
myEncoderParameters = new EncoderParameters( 1 );
myEncoderParameter = new EncoderParameter( myEncoder, quality );
myEncoderParameters.Param[0] = myEncoderParameter;
b.Save( name, myImageCodecInfo, myEncoderParameters );
}
/// <summary>
/// 获取位图保存文件格式信息
/// </summary>
private static ImageCodecInfo GetEncoderInfo( String mimeType )
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for( j = 0; j < encoders.Length; ++j )
{
f( encoders[ j ].MimeType == mimeType )
return encoders[ j ];
}
return null;
}
/// 把位图保存为jpeg格式,并可以这是保存质量
/// </summary>
/// <param name="b">位图</param>
/// <param name="name">文件名</param>
/// <param name="quality">保存质量</param>
/// <remarks>质量范围0-100,类型为long</remarks>
private void JpegSave( Bitmap b, string name, long quality )
{
ImageCodecInfo myImageCodecInfo;
Encoder myEncoder;
EncoderParameter myEncoderParameter;
EncoderParameters myEncoderParameters;
myImageCodecInfo = FrmMain.GetEncoderInfo( "image/jpeg" );
myEncoder = Encoder.Quality;
myEncoderParameters = new EncoderParameters( 1 );
myEncoderParameter = new EncoderParameter( myEncoder, quality );
myEncoderParameters.Param[0] = myEncoderParameter;
b.Save( name, myImageCodecInfo, myEncoderParameters );
}
/// <summary>
/// 获取位图保存文件格式信息
/// </summary>
private static ImageCodecInfo GetEncoderInfo( String mimeType )
{
int j;
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
for( j = 0; j < encoders.Length; ++j )
{
f( encoders[ j ].MimeType == mimeType )
return encoders[ j ];
}
return null;
}
文章来源:http://spaces.msn.com/sharkoo/Blog/cns!D8E832CE4545AF!156.entry
补充:
在以上代码的基础上使用以下代码可以控制位图的色深。当系统为16位色或更低时,使用不指定色深的保存方法保存的JPEG图片,可能会出现马赛克的情况。GDI中也会有此中情况出现,使用时要特别注意。
myEncoderParameters = new EncoderParameters(2);
myEncoder = Encoder.ColorDepth;
myEncoderParameter = new EncoderParameter(myEncoder, (long)ColorDepth.Depth32Bit);
myEncoderParameters.Param[1] = myEncoderParameter;
myEncoder = Encoder.ColorDepth;
myEncoderParameter = new EncoderParameter(myEncoder, (long)ColorDepth.Depth32Bit);
myEncoderParameters.Param[1] = myEncoderParameter;