开发者

Reducing image in bytes while storing in database mvc2 c# 4.0

开发者 https://www.devze.com 2023-02-19 04:32 出处:网络
I am uploading a user image in mvc2 web application. User can upload an image of any size e.g. 10MB or more. The uploaded images are getting stored in database AS IMAGE datatype. But before getting st

I am uploading a user image in mvc2 web application. User can upload an image of any size e.g. 10MB or more. The uploaded images are getting stored in database AS IMAGE datatype. But before getting stored in the database I want to reduce its size to 4MB. How do I do this?

I have reduced the size the bytes of the image with the following code:

   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();
                    }

But while displaying the image, images are not showing up even though the reduced size is getting stored in the DB. I think while reducing the size, image is getting corrupt or else.

Kindly Suggest?

Thanks


You never write down the stream into the byte array you are creating:

var imgBytes = new Byte[stream.Length];

Then what?

Use ToArray() to get the actual byte array instead:

var imgBytes = stream.ToArray();


You can either rescale the image or save it as JPEG with a higher compression level.

If the image is larger than the expected displaying size I would start with rescaling the image. Then apply higher compression if necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消