User-980333546 posted
Hi, I'm using code below to resize image but after resizing, we are losing image quality(resolution).
Can someone suggest the best way to resize image without losing its resolution/quality?
public string GetFixedSizeImage(string oldFile)
{
int sourceX = 0, sourceY = 0, destX = 0, destY = 0;
float nPercent = 0, nPercentW = 0, nPercentH = 0;
int height =1650, width=2350;
string fixedImageFilePath =@"OutputImagePath....";
try
{
System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(oldFile);
int sourceWidth = sourceImage.Width;
int sourceHeight = sourceImage.Height;
nPercentW = ((float)width / (float)sourceWidth);
nPercentH = ((float)height / (float)sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = System.Convert.ToInt16((width - (sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = System.Convert.ToInt16((height - (sourceHeight * nPercent)) / 2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
using (Bitmap bmPhoto = new Bitmap(width, height))
{
bmPhoto.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);
using (Graphics grPhoto = Graphics.FromImage(bmPhoto))
{
grPhoto.Clear(System.Drawing.Color.White);
grPhoto.CompositingQuality = CompositingQuality.HighQuality;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.SmoothingMode = SmoothingMode.HighQuality;
grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
grPhoto.DrawImage(sourceImage, new System.Drawing.Rectangle(destX, destY, destWidth, destHeight)
, new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel);
}
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[1];
EncoderParameters eParams = new EncoderParameters(1);
eParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
bmPhoto.Save(fixedImageFilePath, codec, eParams);
eParams.Dispose();
}
}
catch (Exception ex)
{
throw;
}
return fixedImageFilePath;
}