![](/img/trans.png)
[英]How to reduce image file, resize without losing quality using MultipleFileUpload in ASP.NET C#
[英]Resize image in C# without losing quality
static Image ScaleImage(Image image, int Width, int Height)
{
int originalWidth = image.Width;
int originalHeight = image.Height;
double ratioX = (double)Width / (double)originalWidth;
double ratioY = (double)Height / (double)originalHeight;
double ratio = Math.Min(ratioX, ratioY);
int newHeight = (int)(originalHeight * ratio);
int newWidth = (int)(originalWidth * ratio);
Image scaledImage = new Bitmap(newWidth, newHeight);
Graphics graphic = Graphics.FromImage(scaledImage);
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.Clear(Color.Transparent);
graphic.DrawImage(image, 0, 0, newWidth, newHeight);
return scaledImage;
}
Image full = new Bitmap("img.png");
Image scaledImage = ScaleImage(full, full.Width / 2, full.Height / 2);
Clipboard.SetImage(scaledImage);
問題在於,使用此代碼調整大小后,圖像有點模糊。
我想將原始圖像的一個版本復制到剪貼板,但是要縮放(縮小2/3倍),如果我將圖像粘貼到某個地方並手動調整大小(以更高的分辨率),則我希望獲得與原始圖像相同的質量。
我怎樣才能做到這一點?
試試這個代碼,它幾乎就像您的代碼,但是我在自己的圖片查看器中使用它,卻看不到任何“模糊”。
它不會調整每一側的大小,而是將圖片與MaxImageSizeToResize一側放置在正方形中並保存比例。 可能是由於未按比例調整大小而導致模糊或丟失了某些屬性。
嘗試說-結果是否相同。
public static System.Drawing.Bitmap Resize(string pathToOriginalFile, int MaxImageSizeToResize)
{
using (var image = System.Drawing.Image.FromFile(pathToOriginalFile))
{
return LocalGet(image);
}
System.Drawing.Bitmap LocalGet(System.Drawing.Image image)
{
int rW = 0;
int rH = 0;
double c = 0;
c = ((double)image.Height / (double)MaxImageSizeToResize);
rW = (int)(image.Width / c);
rH = MaxImageSizeToResize;
var destRect = new System.Drawing.Rectangle(0, 0, rW, rH);
var destImage = new System.Drawing.Bitmap(rW, rH);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = System.Drawing.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 System.Drawing.Imaging.ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.