所以我的逻辑有缺陷,我需要一种更好、更正确的方法来在我的 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/