2016-09-26 28 views
1

在我的項目中,我必須調整圖像大小,然後將其保存到文件夾中。但是,我遇到了一些問題,其中一些圖像會比原始文件大小大。爲什麼我的BMP圖像在縮小寬度和高度後比原始圖像大?

大小調整方法:

public Image reduce(Image sourceImage, string size) 
    { 
     double percent = Convert.ToDouble(size)/100; 
     int width = (int)(sourceImage.Width * percent); 
     int height = (int)(sourceImage.Height *percent); 
     var resized = new Bitmap(original, width, height); 
     return resized; 
    } 

使用:

//the code to get the image is omitted (in my testing, bmp format is fixed, however, other image formats are required) 
//to test the size of original image 
oImage.Save(Path.Combine(oImagepath), System.Drawing.Imaging.ImageFormat.Bmp); 

Image nImage = resizeClass.reduce(oImage,"95"); 
nImage.Save(Path.Combine(nImagepath), System.Drawing.Imaging.ImageFormat.Bmp); 

結果:

  • 圖像的第一保存:1920×1080,尺寸:6076 KB

  • 圖像的第二保存:1824 * 1026,尺寸:

    • original
    • 7311KB < =它應該比6076KB

圖像少

  • resized
  • 更新

    原始圖像的位深是24調整爲32。是這裏的問題?

    +0

    你絕對相信你將其保存爲BMP? – Euphoric

    +0

    @欣快,是的!你可以檢查上面的圖片網址!它是XXXX.bmp圖像 –

    +1

    也許原始圖像是16 bpp和輸出是24 bpp? – i486

    回答

    1

    根據您所提供的代碼,我已經做了一個ExtensionMethod您可能需要使用:

    public static class ImageExtensions { 
    
        public static System.Drawing.Image Reduce(this System.Drawing.Image sourceImage, double size) { 
         var percent = size/100; 
         var width = (int)(sourceImage.Width * percent); 
         var height = (int)(sourceImage.Height * percent);   
         Bitmap targetBmp; 
         using (var newBmp = new Bitmap(sourceImage, width, height)) 
         targetBmp = newBmp.Clone(new Rectangle(0, 0, width, height), sourceImage.PixelFormat); 
         return targetBmp; 
        } 
    
        } 
    

    使用

    var nImage = new Bitmap(@"PathToImage").Reduce(50); //Percentage here 
    nImage.Save(@"PathToNewImage", ImageFormat.Jpeg); //Change Compression as you need 
    

    請注意,這是目前全自動確定的研究,其中新的圖像有它的x = 0和y = 0。另外我已經用雙重字符串取代了字符串百分比。

    正如其他人在評論中提到的,你必須使用相同或更低的PixelFormat作爲SourceImage。此外,設置正確的/最佳的保存法圖像擴展降低了文件大小

    希望這有助於

    +0

    爲什麼它不是destX和destY的零值? –

    +0

    你有點兒不對,第一種方法提取圖像比例。已更新回答 – lokusking

    +0

    一個問題.....它削減我的圖像,以適應其大小..... –

    1

    顏色深度增加你的文件大小。

    有可能是一個更好的辦法,但你可以轉換你產生32位位圖的24位單

    Bitmap clone = new Bitmap(resized.Width, resized.Height, 
        System.Drawing.Imaging.PixelFormat.Format24bppRgb); 
    
    using (Graphics gr = Graphics.FromImage(clone)) { 
        gr.DrawImage(resized, new Rectangle(0, 0, clone.Width, clone.Height)); 
    } 
    
    +0

    我必須檢查原始圖像深度,然後再增加它因爲原始圖像可能是32位深度。 (如果是32位,我無法將圖像轉換爲24位) –

    +0

    無法使用* image.PixelFormat *請參閱此處,它應該完全提供該信息 https://msdn.microsoft.com/zh-cn/ -us /庫/ system.drawing.imaging.pixelformat.aspx –

    相關問題