嘿,我有这张图片:
我正在使用这种方法调整图像大小:
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
然而,当我完成后,这将是我的结果:
如您所见,图片有点模糊且质量很差。所以改变了我的方法并使用这个方法来调整我的图片:
public static Image ResizeImage(Image OriginalImage, Size ThumbSize)
{
Int32 thWidth = ThumbSize.Width;
Int32 thHeight = ThumbSize.Height;
Image i = OriginalImage;
Int32 w = i.Width;
Int32 h = i.Height;
Int32 th = thWidth;
Int32 tw = thWidth;
if (h > w)
{
Double ratio = (Double)w / (Double)h;
th = thHeight < h ? thHeight : h;
tw = thWidth < w ? (Int32)(ratio * thWidth) : w;
}
else
{
Double ratio = (Double)h / (Double)w;
th = thHeight < h ? (Int32)(ratio * thHeight) : h;
tw = thWidth < w ? thWidth : w;
}
Bitmap target = new Bitmap(tw, th);
Graphics g = Graphics.FromImage(target);
g.SmoothingMode = SmoothingMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.High;
Rectangle rect = new Rectangle(0, 0, tw, th);
g.DrawImage(i, rect, 0, 0, w, h, GraphicsUnit.Pixel);
return (Image)target;
}
但问题仍然存在。我想知道如何在不损失质量的情况下将此图像调整为更小的尺寸。
我必须添加调整大小后我将创建一个字节数组并将其保存在数据库中(是的我知道不好的事情,但在这个项目中它必须保存在数据库中)。同样在检索时,我从 webapi 获取图像,这样字节数组将被转换为 base64 字符串。我在图像标签上显示 b64,如下所示。例如:
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
最佳答案
我对数千张图像使用了以下方法,它从未失去显着的质量或产生虚线图像。
public static Image ScaleImage(Image image, int height)
{
double ratio = (double)height/ image.Height;
int newWidth = (int)(image.Width * ratio);
int newHeight = (int)(image.Height * ratio);
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, newWidth, newHeight);
}
image.Dispose();
return newImage;
}
我冒昧地将您使用此代码发布的图片缩放到 128 像素(就像您发布的缩略图一样)。
结果:
关于c# - 如何在不降低质量的情况下调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46149206/