How to resize an Image C#

前端 未结 17 2655
暗喜
暗喜 2020-11-21 22:28

As Size, Width and Height are Get() properties of System.Drawing.Image;
How can I resize an Image object

17条回答
  •  半阙折子戏
    2020-11-21 23:20

    This code is same as posted from one of above answers.. but will convert transparent pixel to white instead of black ... Thanks:)

        public Image resizeImage(int newWidth, int newHeight, string stPhotoPath)
        {
            Image imgPhoto = Image.FromFile(stPhotoPath);
    
            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
    
            //Consider vertical pics
            if (sourceWidth < sourceHeight)
            {
                int buff = newWidth;
    
                newWidth = newHeight;
                newHeight = buff;
            }
    
            int sourceX = 0, sourceY = 0, destX = 0, destY = 0;
            float nPercent = 0, nPercentW = 0, nPercentH = 0;
    
            nPercentW = ((float)newWidth / (float)sourceWidth);
            nPercentH = ((float)newHeight / (float)sourceHeight);
            if (nPercentH < nPercentW)
            {
                nPercent = nPercentH;
                destX = System.Convert.ToInt16((newWidth -
                          (sourceWidth * nPercent)) / 2);
            }
            else
            {
                nPercent = nPercentW;
                destY = System.Convert.ToInt16((newHeight -
                          (sourceHeight * nPercent)) / 2);
            }
    
            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);
    
    
            Bitmap bmPhoto = new Bitmap(newWidth, newHeight,
                          PixelFormat.Format24bppRgb);
    
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                         imgPhoto.VerticalResolution);
    
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(Color.White);
            grPhoto.InterpolationMode =
                System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
    
            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);
    
            grPhoto.Dispose();
            imgPhoto.Dispose();
    
            return bmPhoto;
        }
    

提交回复
热议问题