简体   繁体   English

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

[英]How to Resize Image and save in folder?

I tried this: 我试过这个:

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;
    }
}

Running the above code, I get an image 4-5 KB in size with very poor image quality. 运行上面的代码,我得到一个4-5 KB的图像,图像质量很差。 The original image file is no more than 1.5 MB large. 原始图像文件不超过1.5 MB。 How can I improve the image quality of the results? 如何提高结果的图像质量?

I think you should use Image Resizer , its free and resizing an image is very easy using it. 我认为你应该使用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(); 

You can also install it using Nuget package manager. 您也可以使用Nuget包管理器安装它。

PM> Install-Package ImageResizer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM