c# - 在数据库 mvc2 c# 4.0 中存储时以字节为单位减少图像

标签 c# .net asp.net-mvc asp.net-mvc-2

我正在 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/

相关文章:

c# - 部分 View 刷新和脚本不起作用

c# - 不挂其他控件的WinForms验证

asp.net-mvc - 在ASP.NET MVC中封装用户控件

c# - 客户端验证 "required",使用 ASP.NET MVC UI Api 中的 kendo DropDownList 的条件逻辑

c# - 显示日期时间字符串或空字符串的函数

c# - 用于处理不同实现的 if else 的设计模式

c# - 写入套接字 : Unable to write data to transport connection 时出现异常

c# - 按日期排列的最新论坛帖子

c# - XmlSerializer 和工厂创建的元素

c# - .Net 控制台应用程序中的用户 secret 问题