[英]How to resize image without losing quality
嘿,我有這張圖片:
我正在使用這種方法來調整我的圖像大小:
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 像素(如您發布的縮略圖)。
結果:
這種方法對我很有用。
只需使用您想要的寬度和高度創建一個新的大小,並使用您想要縮放的圖像創建一個新的位圖。
public Bitmap GetResizeImage(Bitmap bm, int newWidth, int newHeight)
{
var newSize = new Size(newWidth, newHeight);
return new Bitmap(bm, newSize);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.