2012-07-07 92 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

相关问题