0

我在使用 WPF 调整图像大小时遇到​​了一些问题,因为图像在某些分辨率下变得模糊。我实际上是将这些写到文件中,所以SnapToDevicePixels无济于事(我什至不在 WPF 应用程序中,我只是在引用System.Windows)。

我知道这与 WPF 中像素的设备独立性有关,但我现在需要知道如何计算像素的偏移量以获得清晰的图像。

4

1 回答 1

0

有没有必要使用WPF?我们使用的这个基于 GDI 的代码产生了出色的调整大小的能力:

    public static Size ResizeImage(
       string fileName, 
       string targetFileName, 
       Size boundingSize, 
       string targetMimeType, 
       long quality)
    {
        ImageCodecInfo imageCodecInfo = 
            ImageCodecInfo
               .GetImageEncoders()
               .Single(i => i.MimeType == targetMimeType);
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = 
            new EncoderParameter(Encoder.Quality, quality);
        using (FileStream fs = File.OpenRead(fileName))
        {
            Image img ;
            try
            {
                img = Image.FromStream(fs, true, true);
            }
            catch (ArgumentException ex)
            {
                throw new FileFormatException("cannot decode image",ex);
            } 
            using (img)
            {
                double targetAspectRatio = 
                    ((double)boundingSize.Width) / boundingSize.Height;
                double srcAspectRatio = ((double)img.Width) / img.Height;
                int targetWidth = boundingSize.Width;
                int targetHeight = boundingSize.Height;
                if (srcAspectRatio > targetAspectRatio)
                {
                    double h = targetWidth / srcAspectRatio;
                    targetHeight = Convert.ToInt32(Math.Round(h));
                }
                else
                {
                    double w = targetHeight * srcAspectRatio;
                    targetWidth = Convert.ToInt32(Math.Round(w));
                }
                using (Image thumbNail = new Bitmap(targetWidth, targetHeight))
                using (Graphics g = Graphics.FromImage(thumbNail))
                {
                    g.CompositingQuality = CompositingQuality.HighQuality;
                    g.SmoothingMode = SmoothingMode.HighQuality;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Rectangle rect = 
                        new Rectangle(0, 0, targetWidth, targetHeight);
                    g.DrawImage(img, rect);
                    thumbNail.Save(
                        targetFileName, imageCodecInfo, encoderParams);
                }
                return new Size(targetWidth, targetHeight);
            }

        }
    }
于 2012-11-12T22:58:18.310 回答