2012-07-07 86 views
1

我嘗試這樣做:如何調整圖像大小並保存在文件夾中?

string str = System.IO.Path.GetFileName(txtImage.Text); 
string pth = System.IO.Directory.GetCurrentDirectory() + "\\Subject"; 
string fullpath = pth + "\\" + str; 

Image NewImage = clsImage.ResizeImage(fullpath, 130, 140, true); 
NewImage.Save(fullpath, ImageFormat.Jpeg); 

public static Image ResizeImage(string file, int width, int height, bool onlyResizeIfWider) 
{ 
    if (File.Exists(file) == false) 
     return null; 
    try 
    { 
     using (Image image = Image.FromFile(file)) 
     { 
      // Prevent using images internal thumbnail 
      image.RotateFlip(RotateFlipType.Rotate180FlipNone); 
      image.RotateFlip(RotateFlipType.Rotate180FlipNone); 
      if (onlyResizeIfWider == true) 
      { 
       if (image.Width <= width) 
       { 
        width = image.Width; 
       } 
      } 
      int newHeight = image.Height * width/image.Width; 
      if (newHeight > height) 
      { 
       // Resize with height instead 
       width = image.Width * height/image.Height; 
       newHeight = height; 
      } 
      Image NewImage = image.GetThumbnailImage(width, newHeight, null, IntPtr.Zero); 
      return NewImage; 
     } 
    } 
    catch (Exception) 
    { 
     return null; 
    } 
} 

運行上面的代碼中,我得到的圖像4-5 KB大小與圖像質量很差。 原始圖像文件不超過1.5 MB大。我怎樣才能提高結果的圖像質量?

+1

您使用'RotateFlip'很奇怪。我看到了評論,但這看起來像是對我的貨物崇拜編程。 – Oded 2012-07-07 12:59:54

+1

你正在使用哪個'Image'類?在什麼名字空間?保存時,使用帶有「EncoderParameters」的過載,其質量設置爲「高」。 – Oded 2012-07-07 13:01:40

+0

位圖類型@Oded – 2012-07-07 13:10:09

回答

4

我認爲你應該使用Image Resizer,它的自由和調整大小的圖像很容易使用它。

var settings = new ResizeSettings { 
MaxWidth = thumbnailSize, 
MaxHeight = thumbnailSize, 
Format = "jpg" 
}; 
settings.Add("quality", quality.ToString()); 
ImageBuilder.Current.Build(inStream, outStream, settings); 
resized = outStream.ToArray(); 

您也可以使用Nuget包管理器進行安裝。

PM> Install-Package ImageResizer 
+0

什麼我通過inStream和outStream? – 2012-07-07 13:40:25

+0

您應該傳遞圖像以在'inStream'中調整大小,並在'outStream'中調整圖像大小。你可以傳遞新的MemoryStream()作爲outStream。 – 2012-07-07 13:52:27

+0

你也可以傳遞給任何參數的文件名。 – 2012-07-07 14:16:56

相關問題