2013-09-25 67 views
0

我想將圖片尺寸減小到小於50 kb。如何使用c sharp減小圖像的尺寸

在這裏,我給我在我的應用程序中使用的代碼。

byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength]; 
HttpPostedFile uploadedImage = FileUpload1.PostedFile; 
uploadedImage.InputStream.Read(imageSize(int)FileUpload1.PostedFile.ContentLength); 
var fileLength1 = (FileUpload1.FileContent.Length.ToString()); 
byte[] ImageData = GenerateThumbnails(0.005, uploadedImage.InputStream); 

private byte[] GenerateThumbnails(double scaleFactor, Stream sourcePath) { 
    var image = System.Drawing.Image.FromStream(sourcePath); 
    var newWidth = (int)(image.Width * scaleFactor); 
    var newHeight = (int)(image.Height * scaleFactor); 
    var thumbnailImg = new Bitmap(newWidth, newHeight); 
    var thumbGraph = Graphics.FromImage(thumbnailImg); 
    thumbGraph.CompositingQuality = CompositingQuality.HighQuality; 
    thumbGraph.SmoothingMode = SmoothingMode.HighQuality; 
    thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; 
    var imageRectangle = new Rectangle(0, 0, newWidth, newHeight); 
    thumbGraph.DrawImage(image, imageRectangle); 
    MemoryStream ms = new MemoryStream(); 
    image.Save(ms, ImageFormat.Jpeg); 
    return ms.ToArray();  
} 

這裏功能GenerateThumbnails減少了圖片的實際大小,但它非常低。假設我上傳大小爲800kb的圖像,功能將從800kb減少40kb。影響我網站性能的圖像大小。

+0

http://stackoverflow.com/questions/1922040/resize-an-image-c-sharp – Sadique

回答

0

減小圖像的分辨率可能會導致產生低尺寸圖像,

變化比例因子值< 0.5,在現有的代碼。

var newWidth = (int)(image.Width * scaleFactor); 
var newHeight = (int)(image.Height * scaleFactor); 
+0

根據圖像的原始大小縮小scaleFactor比率,以進一步優化硬編碼。 –

+0

哪一個也不能給出正確的結果。 – Rajeev

2

你也可以使用Thumbnailimage方法......它看起來正是你想要的。 (我不測試的壓縮,但它definatly compreses圖像)

Image FinalImage = Image.FromFile(@"yourPath").GetThumbnailImage(X, Y,() => false, IntPtr.Zero); 

您也可以使用較低的InterpolationModeCompositingQuality,並SmoothingMode