我有一个网络应用程序,用户可以在其中上传图像。我遇到的当前问题是正在上传的图像正在以原始格式保存到数据库中。当在网页上使用图像时,这会导致很多性能问题。我使用 dotTrace 来分析应用程序,当从数据库处理图像时我发现了重大问题。
我的想法是在将图像上传到服务器时调整图像的大小。以我希望应用程序在用户上传新图像时执行的以下示例为例;
- 用户上传图片
- 正在将图片调整为 7.500 x 7.500 像素,72 dpi
- 图片正在保存到数据库中
- 原始文件被处置
唯一存储的图像是上面提到的图像,网络应用程序包含动态调整图像大小的技术。
我已经在这里阅读了几个关于 SO 的主题。他们中的大多数都为我指明了 ImageMagick 的方向。这个工具在我公司已经很熟悉了,并在 PHP 项目中使用。但是这个工具有任何好的和稳定的发布的 C# 包装器吗?我已经找到了以下工具,但它们处于 Béta 版、Alpha 版或当前未更新。
我还找到了this关于 SO 的主题。本主题提供了以下代码示例;
private static Image CreateReducedImage(Image imgOrig, Size newSize)
{
var newBm = new Bitmap(newSize.Width, newSize.Height);
using (var newGrapics = Graphics.FromImage(newBm))
{
newGrapics.CompositingQuality = CompositingQuality.HighSpeed;
newGrapics.SmoothingMode = SmoothingMode.HighSpeed;
newGrapics.InterpolationMode = InterpolationMode.HighQualityBicubic;
newGrapics.DrawImage(imgOrig, new Rectangle(0, 0, newSize.Width, newSize.Height));
}
return newBm;
}
简而言之我的问题;
- 使用上面的例子在性能方面有什么优势吗?
- 我可以使用 ImageMagick 的良好且可靠的 C# 包装器来执行此操作吗?
欢迎提供与性能相关的任何其他好的提示!
最佳答案
我们使用后一种方法 - 我无法对性能发表评论,但它确实使处理依赖关系更简单。
但是,需要注意的一件事是,如果您的用户能够上传各种格式的图像,那么上述代码可能过于简单。底层库 (GDI+) 存在许多颜色格式问题,但它也取决于操作系统版本。这是我们使用的代码的核心:
// GDI+ has problems with lots of image formats, and it also chokes on unknown ones (like CMYK).
// Therefore, we're going to take a whitelist approach.
// see http://bmpinroad.blogspot.com/2006/04/file-formats-pixel-formats.html
// also see http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/c626a478-e5ef-4a5e-9a73-599b3b7a6ecc
PixelFormat format = originalImage.PixelFormat;
if (format == PixelFormat.Format16bppArgb1555 ||
format == PixelFormat.Format64bppArgb)
{
// try to preserve transparency
format = PixelFormat.Format32bppArgb;
}
else if (format == PixelFormat.Format64bppPArgb)
{
// try to preserve pre-multiplied transparency
format = PixelFormat.Format32bppPArgb;
}
else if (format != PixelFormat.Format24bppRgb && format != PixelFormat.Format32bppRgb)
{
format = PixelFormat.Format24bppRgb;
}
// GIF saving is probably still an issue. If we ever need to tackle it, see the following:
// http://support.microsoft.com/kb/319061
// http://www.bobpowell.net/giftransparency.htm
// http://support.microsoft.com/kb/318343
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, format))
{
using (Graphics Canvas = Graphics.FromImage(newImage))
{
using (ImageAttributes attr = new ImageAttributes())
{
attr.SetWrapMode(WrapMode.TileFlipXY);
Canvas.SmoothingMode = SmoothingMode.AntiAlias;
Canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
Canvas.PixelOffsetMode = PixelOffsetMode.HighQuality;
Canvas.DrawImage(originalImage, new Rectangle(new Point(0, 0), newSize), srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, GraphicsUnit.Pixel, attr);
newImage.Save(outputImageStream, originalImage.RawFormat);
}
}
}
关于C# mvc 图片上传调整大小服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4737220/