0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jpegファイルのセーブ

Last updated at Posted at 2025-05-17

JpegIO

jpeg ファイルを品質(quality)を指定してセーブする時に使用します

新しいビットマップを作成してセーブしているのは、
GDI+なんたらのエラーを回避するためです

プラットフォーム x64 でビルドした場合、品質が正しく設定されないことがあります。x86 での使用を推奨します

JpegIO.cs
using System.Drawing.Imaging;

namespace System.Drawing
{
    public static class JpegIO
    {
        static ImageCodecInfo? GetEncoderInfo(string mineType)
        {
            ImageCodecInfo[] encs = ImageCodecInfo.GetImageEncoders();

            foreach (ImageCodecInfo enc in encs)
            {
                if (enc.MimeType == mineType)
                {
                    return enc;
                }
            }

            return null;
        }

        public const int quality_default = 85;

        public static CustomError? Save(string path, Bitmap bitmap, int quality = quality_default)
        {
            var imagecodecinfo = GetEncoderInfo("image/jpeg");

            if (imagecodecinfo == null)
            {
                return new CustomError("ImageCodecInfo の取得に失敗しました");
            }

            Bitmap? _bitmap = null;

            try
            {
                var encoderparameters = new EncoderParameters(1);

                encoderparameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality);

                _bitmap = new Bitmap(bitmap);

                _bitmap.Save(path, imagecodecinfo, encoderparameters);

                return null;
            }
            catch (Exception ex)
            {
                return new CustomException(ex);
            }
            finally
            {
                if (_bitmap != null)
                {
                    _bitmap.Dispose();
                }
            }
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?