2011-03-24 18 views
1

我上傳的MVC2 Web應用程序用戶的圖像。用戶可以上傳任意大小的圖像,例如10MB或更多。上傳的圖像存儲在數據庫AS IMAGE數據類型中。但在獲得存儲在數據庫之前,我想將其大小減小到4MB。我該怎麼做呢?減少映像中的字節,而在數據庫中存儲MVC2 C#4.0

我已減小尺寸用下面的代碼圖像的字節數:

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

不過,雖然顯示圖像,圖像沒有顯示出來,即使減小尺寸變得存儲在DB中。我認爲在縮小尺寸的同時,圖像變得腐敗或者其他。

請推薦?

感謝

回答

3

你從來不寫往下流成字節數組要創建:

var imgBytes = new Byte[stream.Length]; 

然後呢?

使用ToArray的(),以獲得實際的字節數組來代替:

var imgBytes = stream.ToArray(); 
1

您可以重新調整圖像或將其以更高的壓縮級別保存爲JPEG。

如果圖像是比預期的顯示尺寸,我將開始與重新調整圖像越大。如有必要,請應用較高的壓縮率

+0

能否請您提供FOT的代碼?這裏是我的代碼:如果(請求!= NULL){ HttpPostedFileBase文件= Request.Files [ 「uploadimage」]; 如果(文件!= NULL) 如果(file.ContentLength> 0){ 變種 = imgByte新字節[file.ContentLength]; file.InputStream.Read(imgByte,0,file.ContentLength); customParentalHealthUser.ImageBytes = imgByte; } } – Tarun 2011-03-24 06:27:30

+1

@Tarun,已經有關於[100個實施例](http://stackoverflow.com/search?q=%5Bc%23%5D+resize+image)的如何調整在c#圖像。 – 2011-03-24 06:32:42

+0

但我需要減少圖像的字節大小,因爲我將圖像作爲字節數組存儲在數據庫中? – Tarun 2011-03-24 06:40:39

相關問題