Bitmapを品質指定で保存する
C#のBitmapは品質をパーセント指定でSaveできません。下記のコードを利用すると品質指定で保存可能です。
0が最低品質で、100が最高品質です。下記のコードは利用側で、品質を80%としました。
MyClass mc0 = new MyClass();
mc0.SaveEx( bmp, "test.jpg", 80 );
MyClas mc1 = new MyClass();
string msg = "";
mc1.SaveEx( bmp, "test.jpg", 80, out msg );こちらがクラスメソッド側です。
using System;
using System.Drawing;
using System.Drawing.Imaging;
public class MyClass
{
public bool SaveEx( Bitmap bmp, string filepath, int quality_0_to_100 )
{
string excp_message = "";
return SaveEx(
bmp,
filepath,
quality_0_to_100,
ref excp_message
);
}
public bool SaveEx( Bitmap bmp, string filepath, int quality_0_to_100, ref string excp_message )
{
int quality = quality_0_to_100;
excp_message = "";
if ( bmp == null )
{
excp_message = "Bitmap is null.";
return false;
}
if ( filepath == null )
{
excp_message = "File path is null.";
return false;
}
if ( filepath == "" )
{
excp_message = "File path is empty.";
return false;
}
if ( quality < 0 )
{
excp_message = "Quality must be 0 to 100.";
return false;
}
if ( quality > 100 )
{
excp_message = "Quality must be 0 to 100.";
return false;
}
ImageCodecInfo jpeg_codec = null;
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
for ( int n = 0; n < codecs.Length; n++ )
{
if ( codecs[ n ].FormatID == ImageFormat.Jpeg.Guid )
{
jpeg_codec = codecs[ n ];
}
}
if ( jpeg_codec == null )
{
excp_message = "JPEG encoder was not found.";
return false;
}
try
{
using ( EncoderParameters enc_params = new EncoderParameters( 1 ) )
{
Encoder quality_encoder = Encoder.Quality;
long quality_value = (long)quality;
using ( EncoderParameter quality_param = new EncoderParameter( quality_encoder, quality_value ) )
{
enc_params.Param[ 0 ] = quality_param;
bmp.Save( filepath, jpeg_codec, enc_params );
}
}
}
catch ( Exception excp )
{
excp_message = excp.Message;
return false;
}
return true;
}
}