c# - 调整大小后图像周围的 GhoSTLy 轮廓

标签 c# .net image resize scale

我正在一个销售手工制作的珠宝的网站上工作,我正在完成图像编辑器,但它的行为不太正确。

基本上,用户上传的图像将被保存为源,然后它会被调整大小以适应用户的屏幕并保存为临时文件。然后,用户将转到允许他们裁剪图像并将其保存为最终版本的屏幕。

除了最终版本有 3 个错误外,所有这些都工作正常。首先是图像底部的一些黑色水平线。其次是沿着边缘的各种轮廓。我以为这是因为我降低了质量,但即使是 100%,它仍然会出现……最后,我注意到裁剪后的图像总是比我指定的低几个像素……

无论如何,我希望有使用 C# 编辑图像经验的人可以看看代码,看看我在哪里可能偏离了正确的道路。

哦,顺便说一句,这是在 ASP.NET MVC 应用程序中。

代码如下:

public class ImageProvider {
    private readonly ProductProvider ProductProvider = null;

    private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
    private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
        c => (c.MimeType == "image/jpeg"));

    private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");
    private readonly short[][] Dimensions = new short[3][] {
        new short[2] { 640, 480 },
        new short[2] { 240, 0 },
        new short[2] { 80, 60 }
    }

    public ImageProvider(ProductProvider ProductProvider) {
        this.ProductProvider = ProductProvider;

        HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
    }

    public void Crop(string FileName, Image Image, Crop Crop) {
        using (Bitmap Source = new Bitmap(Image)) {
            using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Target)) {
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;

                    Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                }

                Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
            }
        }
    }

    public void CropAndResize(Product Product, Crop Crop) {
        using (Image Source = Image.FromFile(String.Format("{0}/{1}.source", Path, Product.ProductId))) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                float Percent = ((float)Source.Width / (float)Temp.Width);

                short Width = (short)(Temp.Width * Percent);
                short Height = (short)(Temp.Height * Percent);

                Crop.Height = (short)(Crop.Height * Percent);
                Crop.Left = (short)(Crop.Left * Percent);
                Crop.Top = (short)(Crop.Top * Percent);
                Crop.Width = (short)(Crop.Width * Percent);

                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Source, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(this.Dimensions[0], String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[1], String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                    this.Resize(this.Dimensions[2], String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), Cropped, HighQualityEncoder);
                }
            }
        }

        this.Purge(Product);
    }

    public void QueueFor( Product Product, HttpPostedFileBase PostedFile) {
        using (Image Image = Image.FromStream(PostedFile.InputStream)) {
            this.Resize(new short[2] {
                1152,
                0
            }, String.Format("{0}/{1}.temp", Path, Product.ProductId), Image, HighQualityEncoder);
        }

        PostedFile.SaveAs(String.Format("{0}/{1}.source", Path, Product.ProductId));
    }

    private void Purge(Product Product) {
        string Source = String.Format("{0}/{1}.source", Path, Product.ProductId);
        string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

        if (File.Exists(Source)) {
            File.Delete(Source);
        }
        if (File.Exists(Temp)) {
            File.Delete(Temp);
        }

        foreach (Img Img in Product.Imgs) {
            string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

            if (File.Exists(Cropped)) {
                File.Delete(Cropped);
            }
        }
    }

    public void Resize( short[] Dimensions, string FileName, Image Image, EncoderParameters EncoderParameters) {
        if (Dimensions[1] == 0) {
            Dimensions[1] = (short)(Image.Height / ((float)Image.Width / (float)Dimensions[0]));
        }

        using (Bitmap Bitmap = new Bitmap(Dimensions[0], Dimensions[1])) {
            using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Graphics.SmoothingMode = SmoothingMode.HighQuality;
                Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                Graphics.CompositingQuality = CompositingQuality.HighQuality;

                Graphics.DrawImage(Image, 0, 0, Dimensions[0], Dimensions[1]);
            };

            Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
        }
    }
}

这是其中一张图片:

http://i.stack.imgur.com/GJX97.jpg

更新

因此,我在发布后坐下来通读 MSDN 大约 2 个小时,验证了我的代码。据我所知,我在执行操作时使用了尽可能高的质量设置。

无论哪种方式,我最终都稍微清理并简化了代码。我考虑了对源文件的需求并决定删除它,因为它需要我做额外的工作来确定基于临时文件的裁剪尺寸。所以,它不见了。

此外,在流线型的某个地方,黑线消失了,所以我只能假设长宽比问题应该已经按照@StefanE 所述得到了纠正。

此外,正如@VinayC 所说,重新调整器生成的高度值为 479(我仍然不知道如何生成,但无论如何......),但当我切换时,这似乎已得到纠正一直使用 System.Drawing.Size 和 System.Drawing.Rectangle 类,而不是使用我自己的类,它们基本上做同样的事情。

所以,这是更新后的代码。剩下的 两个错误 错误仍然存​​在,所以我在图像周围一直有一个“重影”轮廓(见第二个附件),我可以缩小到调整大小,因为它出现在第一个重新- 未发生裁剪的大小。 第二个错误是裁剪后的版本在 y 轴上的位置始终低于我作为裁剪器传入的版本。我估计它比我告诉它的低 5%-8%,所以不确定那个(位置不应该改变......除非我从 jQuery 传递一个错误的数字,要检查在那...)。

(我的第二个错误最终导致我一开始就发送了错误的值,裁剪 div 正在根据主内容 div 而不是图像容器 div 获取其相对位置。现在全部修复。)

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;

namespace Website.Models.Providers {
    public class ImageProvider {
        private readonly ProductProvider ProductProvider = null;

        private readonly EncoderParameters DefaultQualityEncoder = new EncoderParameters();
        private readonly EncoderParameters HighQualityEncoder = new EncoderParameters();
        private readonly ImageCodecInfo JpegCodecInfo = ImageCodecInfo.GetImageEncoders().Single(
            c =>
                (c.MimeType == "image/jpeg"));
        private readonly Size[] Sizes = new Size[3] {
            new Size(640, 0),
            new Size(240, 0),
            new Size(80, 0)
        };

        private readonly string Path = HttpContext.Current.Server.MapPath("~/Resources/Images/Products");

        public ImageProvider(
            ProductProvider ProductProvider) {
            this.ProductProvider = ProductProvider;

            this.DefaultQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
            this.HighQualityEncoder.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
        }

        public void Crop(
            string FileName,
            Image Image,
            Crop Crop) {
            using (Bitmap Source = new Bitmap(Image)) {
                using (Bitmap Target = new Bitmap(Crop.Width, Crop.Height)) {
                    using (Graphics Graphics = Graphics.FromImage(Target)) {
                        Graphics.CompositingMode = CompositingMode.SourceCopy;
                        Graphics.CompositingQuality = CompositingQuality.HighQuality;
                        Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                        Graphics.SmoothingMode = SmoothingMode.HighQuality;

                        Graphics.DrawImage(Source, new Rectangle(0, 0, Target.Width, Target.Height), new Rectangle(Crop.Left, Crop.Top, Crop.Width, Crop.Height), GraphicsUnit.Pixel);
                    };

                    Target.Save(FileName, JpegCodecInfo, HighQualityEncoder);
                };
            };
        }

        public void CropAndResize(
            Product Product,
            Crop Crop) {
            using (Image Temp = Image.FromFile(String.Format("{0}/{1}.temp", Path, Product.ProductId))) {
                Img Img = new Img();

                this.ProductProvider.AddImageAndSave(Product, Img);

                this.Crop(String.Format("{0}/{1}.cropped", Path, Img.ImageId), Temp, Crop);

                using (Image Cropped = Image.FromFile(String.Format("{0}/{1}.cropped", Path, Img.ImageId))) {
                    this.Resize(String.Format("{0}/{1}-L.jpg", Path, Img.ImageId), this.Sizes[0], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-T.jpg", Path, Img.ImageId), this.Sizes[1], Cropped, HighQualityEncoder);
                    this.Resize(String.Format("{0}/{1}-S.jpg", Path, Img.ImageId), this.Sizes[2], Cropped, HighQualityEncoder);
                };
            };

            this.Purge(Product);
        }

        public void QueueFor(
            Product Product,
            Size Size,
            HttpPostedFileBase PostedFile) {
            using (Image Image = Image.FromStream(PostedFile.InputStream)) {
                this.Resize(String.Format("{0}/{1}.temp", Path, Product.ProductId), Size, Image, HighQualityEncoder);
            };
        }

        private void Purge(
            Product Product) {
            string Temp = String.Format("{0}/{1}.temp", Path, Product.ProductId);

            if (File.Exists(Temp)) {
                File.Delete(Temp);
            };

            foreach (Img Img in Product.Imgs) {
                string Cropped = String.Format("{0}/{1}.cropped", Path, Img.ImageId);

                if (File.Exists(Cropped)) {
                    File.Delete(Cropped);
                };
            };
        }

        public void Resize(
            string FileName,
            Size Size,
            Image Image,
            EncoderParameters EncoderParameters) {
            if (Size.Height == 0) {
                Size.Height = (int)(Image.Height / ((float)Image.Width / (float)Size.Width));
            };

            using (Bitmap Bitmap = new Bitmap(Size.Width, Size.Height)) {
                using (Graphics Graphics = Graphics.FromImage(Bitmap)) {
                    Graphics.CompositingMode = CompositingMode.SourceCopy;
                    Graphics.CompositingQuality = CompositingQuality.HighQuality;
                    Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    Graphics.SmoothingMode = SmoothingMode.HighQuality;

                    Graphics.DrawImage(Image, new Rectangle(0, 0, Size.Width, Size.Height));
                };

                Bitmap.Save(FileName, JpegCodecInfo, EncoderParameters);
            };
        }
    }
}

此图像显示了红色箭头所指的“重影”轮廓。

alt text

最佳答案

关于底部的黑线是因为你没有处理纵横比。

double aspectRatio = imageWidth/imageHeight;
double boxRatio = maxWidth/maxHeight;
double scaleFactor = 0;
if (boxRatio > aspectRatio)
 //Use height, since that is the most restrictive dimension of box.
 scaleFactor = maxHeight / imageHeight;
else
 scaleFactor = maxWidth / imageWidth;

double newWidth = imageWidth * scaleFactor;
double newHeight = imageHeight * scaleFactor;

来源:http://nathanaeljones.com/163/20-image-resizing-pitfalls/

关于c# - 调整大小后图像周围的 GhoSTLy 轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4496496/

相关文章:

java - 如何在java中从网络加载图像

c# - Storyboard应用于许多元素

c# - 在 silverlight 4 中将两个不同的转换绑定(bind)在一起

c# - 日期时间 DayOfWeek 比较

Asp.net 图像随机给出 401 未经授权的错误

android - 使用图库中的所有图像在 Android Studio 中进行人脸识别

c# - 如何使用 LDAP 实现基于资源/操作的授权?

c# - 系统.InvalidOperationException : Value Dispose() cannot be called while doing CreateHandle()

c# - 你将如何为这个 xml 文件编写一个可序列化的类?

c# - 从窗体打开 WPF 窗口后,WinForms 应用程序更改其缩放比例