0

画像サイズを元のサイズより小さくしたいのですが、次のコードを使用して画像を圧縮していますが、画像サイズが1MBから1.5MBに増加しました
。画像の元の高さ、幅を変更せずに大きなサイズの画像を圧縮するその他のソリューション。

    public static byte[] CompressImage(Image img) {

            int originalwidth = img.Width, originalheight = img.Height;

            Bitmap bmpimage = new Bitmap(originalwidth, originalheight);

            Graphics gf = Graphics.FromImage(bmpimage);
            gf.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            gf.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.AssumeLinear;
            gf.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;

            Rectangle rect = new Rectangle(0, 0, originalwidth, originalheight);
            gf.DrawImage(img, rect, 0, 0, originalwidth, originalheight, GraphicsUnit.Pixel);

            byte[] imagearray;

            using (MemoryStream ms = new MemoryStream())
            {
                bmpimage.Save(ms, ImageFormat.Jpeg);
                imagearray= ms.ToArray();
            }

            return imagearray;
        }
4

2 に答える 2

3

ファイルを JPEG として保存するときに品質レベルを設定できます。これはほとんどの場合、ファイル サイズと直接相関します。品質が低いほど、出力ファイルは小さくなります。

How to: Set JPEG Compression Levelも参照してください。例については、この SO answerを参照してください。

于 2012-09-11T12:32:28.820 に答える
0

@BrokenGlassで述べたように、 EncoderParameter内で圧縮レベルを指定できます。品質を変更してみた場合のスニペットは次のとおりです。

public static void SaveJpeg(string path, Image image, int quality)
{
    //ensure the quality is within the correct range
    if ((quality < 0) || (quality > 100))
    {
        //create the error message
        string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality.  A value of {0} was specified.", quality);
        //throw a helpful exception
        throw new ArgumentOutOfRangeException(error);
    }

    //create an encoder parameter for the image quality
    EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
    //get the jpeg codec
    ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

    //create a collection of all parameters that we will pass to the encoder
    EncoderParameters encoderParams = new EncoderParameters(1);
    //set the quality parameter for the codec
    encoderParams.Param[0] = qualityParam;
    //save the image using the codec and the parameters
    image.Save(path, jpegCodec, encoderParams);
}
于 2012-09-11T12:56:14.590 に答える