我在 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,但可以是任何格式。
这是从数据库加载并裁剪后的图像的图像...
此图像是裁剪的结果。如您所见,它并不好。
我看过一些关于该主题的其他帖子,但它们没有帮助。任何人都可以提出解决方案吗?
谢谢