【问题标题】:what is the best way to keep image's data when modifying?修改时保留图像数据的最佳方法是什么?
【发布时间】:2017-02-07 03:07:45
【问题描述】:

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

为了测试该方法,我不尝试调整图像大小,而是在 resize 方法中输出 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

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

图片:

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

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

【问题讨论】:

标签: c# image


【解决方案1】:

这里的问题是您使用 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2011-01-04
    • 1970-01-01
    相关资源
    最近更新 更多