修改时保留图像数据的最佳方法是什么?

时间:2016-09-26 03:23:42

标签: c# image

在我的项目中,我必须调整图像大小,然后将其保存到文件夹中。我发布了很多问题,以找出哪种方法可以调整图像大小而不会影响图像,但我仍然没有找到最好的方法..

为了测试方法,我不会尝试调整图像大小,而是在调整大小方法中输出100%大小的图像。

调整大小的方法:

    public Image reduce(Image sourceImage, string size)
    {
        //for testing, i want to use the size of the source image
        //double percent = Convert.ToDouble(size) / 100;
        int width = (int)(sourceImage.Width); //sourceImage.Width * percent 
        int height = (int)(sourceImage.Height); //sourceImage.Height *percent 
        var destRect = new Rectangle(0, 0, width, height);
        var destImage = new Bitmap(width, height);

        destImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
        using (var graphics = Graphics.FromImage(destImage))
        {
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            using (var wrapMode = new ImageAttributes())
            {
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                graphics.DrawImage(sourceImage, destRect, 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel, wrapMode);
            }
        }

        return destImage;
    }

使用:

//the code to get the image is omitted (in my testing, jpg format is fixed, however, other image formats are required)
//to test the size of original image
oImage.Save(Path.Combine(oImagepath), System.Drawing.Imaging.ImageFormat.Jpeg);

Image nImage = resizeClass.reduce(oImage,"100");
nImage .Save(Path.Combine(nImagepath), System.Drawing.Imaging.ImageFormat.Jpeg);

结果:

  
      
  • 首次保存图片:fileSize: 10721KB

  •   
  • 第二次保存图片:fileSize: 4033KB < =应该是10721KB

  •   

问题是如果用户通过设置90% - 100%传递10MB图像,用户如何接受接收4 MB图像?这太荒谬了,所以我必须改写这个程序:(

图片:

原文:https://1drv.ms/i/s!AsdOBLg50clihVaoEQdj1wQidhdX

调整大小:https://1drv.ms/i/s!AsdOBLg50clihVV96AVKouVkI25o

1 个答案:

答案 0 :(得分:2)

这里的问题是您使用JPEG压缩保存图像。虽然JPEG确实有lossless compression,但它是一种完全不同的算法,大多数编码器都不支持它。尝试使用无损图像格式,例如PNG。

来自Lossless compression wikipedia

  

无损压缩是一类数据压缩算法,可以从压缩数据中完美地重建原始数据

     

相比之下,有损压缩只允许重建原始数据的近似值,但这通常可以提高压缩率(从而减少文件大小)。

因此,如果你不介意在保存时丢失一些像素数据,你仍然可以使用JPEG,但是你需要指定一个更高的质量值,以便在保存后保留图像中存储的更多信息。

正如slawekwin在评论中提到的,请查看setting compression levels上的以下文章。 尝试使用此代码将质量设置为100%,从而获得更高质量的图像(但请注意,这仍然不是无损的):

EncoderParameters ep = new EncoderParameters(); 
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100);
相关问题