2014-05-15 55 views
0

我將圖片加載到excel頁面,一旦完成此excel大約48,284 KB這是很大,影響下載速度,並不是我們想要實現的效率。減小位圖圖像的物理大小?

我試圖儘可能減少這個Excel文件的大小,並認爲減小圖像大小會做的伎倆,因爲沒有圖像的Excel文件大約1000 kb。

這是我迄今沒有影響的嘗試:

public Image ReduceImageSize(Image img) 
{ 
    float iwidth = 150; 
    float iheight = 150; 
    var brush = new SolidBrush(Color.Black); 

    var Resizedimage = new Bitmap(img); 

    float scale = Math.Min(iwidth/Resizedimage.Width, iheight/Resizedimage.Height); 

    var graph = Graphics.FromImage(Resizedimage); 

    graph.InterpolationMode = InterpolationMode.Low; 
    graph.CompositingQuality = CompositingQuality.Default; 
    graph.SmoothingMode = SmoothingMode.None; 

    var scaleWidth = (int)(Resizedimage.Width * scale); 
    var scaleHeight = (int)(Resizedimage.Height * scale); 

    graph.FillRectangle(brush, new RectangleF(0, 0, iwidth, iheight)); 
    graph.DrawImage(Resizedimage, new Rectangle(((int)iwidth - scaleWidth)/2, ((int)iheight - scaleHeight)/2, scaleWidth, scaleHeight)); 

    return Resizedimage; 
} 

此時我正在尋找任何方式,以減少大小,如果它涉及失去一些質量或縮小圖像尺寸。

請幫忙。

回答

1

您將Resizeimage製作爲與img相同的尺寸。

使用下面的代碼來解決結果圖像尺寸:

var Resizedimage = new Bitmap(iwidth,iheight); 

一個例子調整圖像大小保持寬高比:

  Image img = Image.FromFile(@"c:\temp\1.jpg"); 
     Bitmap resizedImg = new Bitmap(150, 150); 

     double ratioX = (double)resizedImg.Width/(double)img.Width; 
     double ratioY = (double)resizedImg.Height/(double)img.Height; 
     double ratio = ratioX < ratioY ? ratioX : ratioY; 

     int newHeight = Convert.ToInt32(img.Height * ratio); 
     int newWidth = Convert.ToInt32(img.Width * ratio); 

     using (Graphics g = Graphics.FromImage(resizedImg)) 
     { 
      g.DrawImage(img, 0, 0, newWidth, newHeight); 
     } 
     resizedImg.Save(@"c:\temp\2.jpg"); 
+0

他們出來只是黑色的? – Pomster

+0

對不起,我還不夠清楚。我的代碼將解決您的尺寸問題。所有關於縮放的代碼都必須重新編寫。查看我的編輯以獲取示例解決方案。 – wonko79