C#保存图像质量差

时间:2012-10-08 12:58:02

标签: c# image save

我在保存图片时遇到问题。有了这段代码,我就把两张照片放在一起了。但是当我保存它们时,质量比原始图片的质量差。

            Image Image1 = Image.FromFile(openFileDialogOpenPicture1.FileName);
            Image Image2 = Image.FromFile(openFileDialogOpenPicture2.FileName);

            int imageHeight = 0;
            if (Image1.Height > Image2.Height)
                imageHeight = Image1.Height;
            else
                imageHeight = Image2.Height;

            Bitmap finalImage = new System.Drawing.Bitmap(Image1.Width + Image2.Width, imageHeight);
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
            {
                //set background color
                g.Clear(System.Drawing.Color.Black);

                //go through images and draw it on the final image
                int offset = 0;
                g.DrawImage(pictureBoxBackground1.Image, new System.Drawing.Rectangle(offset, 0, Image1.Width, Image1.Height));
                offset += Image1.Width;
                g.DrawImage(pictureBoxBackground2.Image, new System.Drawing.Rectangle(offset, 0, Image2.Width, Image2.Height));

                var eps = new EncoderParameters(1);
                eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                var ici = GetEncoderInfo("image/jpeg");
                finalImage.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\TestImage.jpg", ici, eps);
            }

我也试图保存未压缩的图片,但这只会使文件文件更大而质量更好。 提前谢谢!

1 个答案:

答案 0 :(得分:0)

我使用过这个GetEncoder方法:

private ImageCodecInfo GetEncoder(ImageFormat format)
{
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

    foreach (ImageCodecInfo codec in codecs)
    {
        if (codec.FormatID == format.Guid)
        {
            return codec;
        }
    }
    return null;
}

使用GetEncoder(ImageFormat.Jpeg)调用它;并删除了对pict​​ureBoxBackground1& 2的引用(否则它不会构建),最终结果是高质量,据我所知。