c# - 如何调整图像大小并保存在文件夹中?

标签 c# image-resizing

我试过这个:

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。如何提高结果的图像质量?

最佳答案

我认为你应该使用 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

关于c# - 如何调整图像大小并保存在文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375187/

相关文章:

c - 如何缩小图像尺寸?

java - 操作图像而不删除其 EXIF 数据

html - 在表中动态调整图像大小

jquery - 双向自动图像拉伸(stretch)/挤压/裁剪

c# - 解密卡号

c# - 线程的编码 UI 测试问题/定期执行重复操作

c# - 多行的 SQL ExecuteNonQuery

iphone - 调整 uiimage 的大小并添加空格

c# - Microsoft SQL Server 2014 数据库错误

c# - 验证另一个应用程序是否始终在运行