Rob*_*Rob 7 c# asp.net asp.net-mvc image-processing
我有一个web应用程序,用户可以上传图像.我遇到的当前问题是正在上传的图像以原始格式保存到数据库中.当在网页上使用图像时,这会导致很多性能问题.我使用dotTrace来分析应用程序,我发现从数据库处理图像时会出现重大问题.
我的想法是在图像上传到服务器时调整图像大小.以下示例,我希望应用程序在用户上传新图像时执行此操作;
唯一存储的图像是上面提到的图像,web应用程序包含动态调整大小的技术.
我已经在SO上阅读了几个主题.而且他们中的大多数都指向了ImageMagick的方向.这个工具在我的公司已经很熟悉,并且在PHP项目中使用.但是这个工具有没有任何好的和稳定的C#包装器?我已经找到了下面的工具,但他们要么在Béta发布,Alpha发布,要么当前没有更新.
我也在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;
}
Run Code Online (Sandbox Code Playgroud)
总之,我有问题;
欢迎任何有关表演的其他好建议!
我们使用后一种方法 - 我无法评论性能,但它确实使处理依赖关系变得更简单。
但是,需要注意的一件事是,如果您的用户能够上传各种格式的图像,则上述代码可能太简单了。底层库 (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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5102 次 |
| 最近记录: |