我正在 mvc2 网络应用程序中上传用户图像。用户可以上传任何尺寸的图像,例如10MB 或更多。上传的图像正在以 IMAGE
数据类型存储在数据库中。但在存储到数据库之前,我想将其大小减少到 4MB。我该怎么做?
我使用以下代码减小了图像的字节大小:
if (file.ContentLength > 0)
{
//Create byte Array with file len
var imgByte = new Byte[file.ContentLength];
//force the control to load data in array
file.InputStream.Read(imgByte, 0, file.ContentLength);
System.IO.MemoryStream newImageStream =
new System.IO.MemoryStream(imgByte, 0, imgByte.Length);
Image image = Image.FromStream(newImageStream, true);
Bitmap resized = new Bitmap(image, new Size(800,600));
System.IO.MemoryStream stream = new System.IO.MemoryStream();
resized.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
var imgBytes = new Byte[stream.Length];
customParentalHealthUser.ImageBytes = imgBytes;
stream.Close();
stream.Dispose();
resized.Dispose();
}
但是在显示图像时,即使缩小的尺寸存储在数据库中,图像也不会显示。我认为在减小尺寸的同时,图像会损坏或者其他。
请推荐?
谢谢
最佳答案
您永远不会将流写到您正在创建的字节数组中:
var imgBytes = new Byte[stream.Length];
然后呢?
改为使用 ToArray() 获取实际的字节数组:
var imgBytes = stream.ToArray();
关于c# - 在数据库 mvc2 c# 4.0 中存储时以字节为单位减少图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5415464/