嘿,我有这个图片:
我正在使用此方法调整图片大小:
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如下所示。 e.g:
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
答案 0 :(得分:3)
我正在使用以下方法处理数千张图像,它永远不会失去显着的质量或导致虚线图像。
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;
}
我冒昧地使用此代码将您发布的图像缩放到128px(就像您发布的缩略图一样)。
结果:
答案 1 :(得分:0)
这个方法对我很有效。
只需使用您想要的宽度和高度创建一个新的尺寸,然后使用您想要缩放的图像创建一个新的位图。
public Bitmap GetResizeImage(Bitmap bm, int newWidth, int newHeight)
{
var newSize = new Size(newWidth, newHeight);
return new Bitmap(bm, newSize);
}