C# GDI+ 图像调整大小函数

标签 c# image gdi+ resize

所以我的逻辑有缺陷,我需要一种更好、更正确的方法来在我的 C# 应用程序中调整图像大小

我需要一个类似于此设置的功能

public void ResizeImageForWeb(string OriginalFile, string NewFile, int MaxWidth, int MaxHeight, int Quality)
{
// Resize Code

}

基本上,我是一名网页设计师,在尝试编写桌面应用程序时迷失了方向。

最佳答案

这是我用来调整用户上传的图像大小以创建缩略图或只是强制执行大小限制的代码。它不涉及图片质量,但这是一个开始。

// uses System.Drawing namespace
public class ImageResizer
{
    public bool ResizeImage(string fullFileName, int maxHeight, int maxWidth)
    {
        return this.ResizeImage(fullFileName, maxHeight, maxWidth, fullFileName);
    }

    public bool ResizeImage(string fullFileName, int maxHeight, int maxWidth, string newFileName)
    {
        using (Image originalImage = Image.FromFile(fullFileName))
        {
            int height = originalImage.Height;
            int width = originalImage.Width;
            int newHeight = maxHeight;
            int newWidth = maxWidth;

            if (height > maxHeight || width > maxWidth)
            {
                if (height > maxHeight)
                {
                    newHeight = maxHeight;
                    float temp = ((float)width / (float)height) * (float)maxHeight;
                    newWidth = Convert.ToInt32(temp);

                    height = newHeight;
                    width = newWidth;
                }

                if (width > maxWidth)
                {
                    newWidth = maxWidth;
                    float temp = ((float)height / (float)width) * (float)maxWidth;
                    newHeight = Convert.ToInt32(temp);
                }

                Image.GetThumbnailImageAbort abort = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                using (Image resizedImage = originalImage.GetThumbnailImage(newWidth, newHeight, abort, System.IntPtr.Zero))
                {
                    resizedImage.Save(newFileName);
                }

                return true;
            }
            else if (fullFileName != newFileName)
            {
                // no resizing necessary, but need to create new file 
                originalImage.Save(newFileName);
            }
        }

        return false;
    }

    private bool ThumbnailCallback()
    {
        return false;
    }
}

关于C# GDI+ 图像调整大小函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2861789/

相关文章:

c# - 将 FASTREPORT 打印导出为 PDF

android - 将图像转换为文本形式以通过 SMS 发送

c++ - 使用 GDI 或 GDI+ 的高级图形

javascript - 按左右箭头更改图像?

php - PHP Table 下的背景图——方法

c++ - 有人有优化的函数来通过 alpha 预乘位图吗?

c++ - 在 GDI+ 中设置现有位图的像素格式

c# - 桌面桥toast打开应用程序

c# - 数据 GridView : DataGridViewImageColumn displays a red cross

c# - 将多个资源字典动态添加到我的 WPF 项目