■ Image 클래스에서 이미지 크기를 조정하는 방법을 보여준다.
▶ Image 클래스 : 이미지 크기 조정하기 예제 (C#)
1 2 3 4 5 |
Image sourceImage = Image.FromFile("c:\\source.jpg"); Image targetImage = ResizeImage(sourceImage, this.pictureBox.Size, Color.Blue); |
※ pictureBox는 System.Windows.Forms.PictureBox 타입이다.
▶ Image 클래스 : 이미지 크기 조정하기 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; #region 이미지 크기 조정하기 - ResizeImage(sourceImage, targetSize, backgroundColor, isImageCenterAligned) /// <summary> /// 이미지 크기 조정하기 /// </summary> /// <param name="sourceImage">소스 이미지</param> /// <param name="targetSize">타겟 크기</param> /// <param name="backgroundColor">배경 색상</param> /// <param name="isImageCenterAligned">이미지 가운데 정렬 여부</param> /// <returns>이미지</returns> public static Image ResizeImage(Image sourceImage, Size targetSize, Color backgroundColor, bool isImageCenterAligned = true) { if(sourceImage == null || targetSize == Size.Empty) { return null; } int sourceWidth = sourceImage.Size.Width; int sourceHeight = sourceImage.Size.Height; int targetWidth = targetSize.Width; int targetHeight = targetSize.Height; Image targetImage = new Bitmap(targetWidth, targetHeight); Graphics targetGraphics = Graphics.FromImage(targetImage); targetGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic; targetGraphics.SmoothingMode = SmoothingMode.HighQuality; targetGraphics.PixelOffsetMode = PixelOffsetMode.HighQuality; targetGraphics.CompositingQuality = CompositingQuality.HighQuality; double ratioX = (double)targetWidth / (double)sourceWidth; double ratioY = (double)targetHeight / (double)sourceHeight; double ratio = ratioX < ratioY ? ratioX : ratioY; int newHeight = Convert.ToInt32(sourceHeight * ratio); int newWidth = Convert.ToInt32(sourceWidth * ratio); int positionX = Convert.ToInt32((targetWidth - (sourceImage.Width * ratio)) / 2); int positionY = Convert.ToInt32((targetHeight - (sourceImage.Height * ratio)) / 2); if(!isImageCenterAligned) { positionX = 0; positionY = 0; } targetGraphics.Clear(backgroundColor); targetGraphics.DrawImage(sourceImage, positionX, positionY, newWidth, newHeight); ImageCodecInfo[] imageCodecInfoArray = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); Stream stream = new MemoryStream(); targetImage.Save(stream, imageCodecInfoArray[1], encoderParameters); return Image.FromStream(stream); } |