【发布时间】:2012-11-27 04:49:00
【问题描述】:
我在 MVC3 C# 应用程序中裁剪图像时遇到问题。我正在裁剪图像,但在视图中渲染时它的质量会下降。 要裁剪的图像是从数据库中加载的,并且是从 ByteArray 中创建的......
public static Image ByteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
当此图像在视图上呈现时,它看起来不错,但质量不符合预期。 然后我选择要裁剪的区域并使用以下方法进行裁剪...
public Image CropImage(System.Drawing.Image Image, int Height, int Width, int StartAtX, int StartAtY)
{
Image outimage;
MemoryStream mm = null;
try
{
//check the image height against our desired image height
if (Image.Height < Height)
{
Height = Image.Height;
}
if (Image.Width < Width)
{
Width = Image.Width;
}
//create a bitmap window for cropping
Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(Image.VerticalResolution,Image.HorizontalResolution);
//create a new graphics object from our image and set properties
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
//now do the crop
grPhoto.DrawImage(Image, new Rectangle(0, 0, Width, Height), StartAtX, StartAtY, Width, Height, GraphicsUnit.Pixel);
// Save out to memory and get an image from it to send back out the method.
mm = new MemoryStream();
bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
Image.Dispose();
bmPhoto.Dispose();
grPhoto.Dispose();
outimage = Image.FromStream(mm);
return outimage;
}
catch (Exception ex)
{
throw new Exception("Error cropping image, the error was: " + ex.Message);
}
}
这个裁剪后的图像然后被转换回 ByteArray 并且可以像这样保存到数据库中......
public static byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
稍后在视图上渲染此图像时,其质量比原始图像差很多。它看起来很像素化。 在这种情况下,原始图像是 .jpg,但可以是任何格式。
这是从数据库加载并裁剪后的图像...
这张图片是裁剪的结果。如您所见,它并不好。
我看过其他一些关于该主题的帖子,但它们没有帮助。任何人都可以提出解决方案吗?
谢谢
【问题讨论】:
-
.NET 用于保存 JPEG 的默认质量非常糟糕,您可以使用此重载来指定自己的质量级别:msdn.microsoft.com/en-us/library/ms142148.aspx
-
我找到了一个可行的解决方案。这是一个很棒的博客,总结了blog.tallan.com/2011/02/04/…
标签: c# asp.net .net asp.net-mvc image-processing