2013-11-22 3 views
0

이미지를 가져 와서 가로 세로 비율을 유지하면서 캔바스에 맞게 크기를 조절하는 기능이 있습니다. 이 코드는이 답변의 코드의 minorly 수정 된 버전입니다 :이 예를 들어 c# Image resizing to different size while preserving aspect ratioGraphics.DrawImage 이미지의 크기가 변하지 않습니다.

, 내 캔버스 높이가 642입니다, 내 캔버스 폭은 823

이다 나는 아래의 기능, 라인을 실행하면

graphic.DrawImage(image, posX, posY, newWidth, newHeight); 

이미지 크기에는 아무런 영향이 없습니다. 에가는 :

Image.Height == 800, 
Image.Width == 1280. 

당신이 볼 수 있듯이 graphic.DrawImage

를 실행 한 후

Image.Height == 800, 
Image.Width == 1280. 
newHeight = 514, 
newWidth == 823 

, 이미지의 높이와 폭은 변경되지 않습니다.

누구나 일어날 수있는 명백한 오류가 있습니까? 고맙습니다! 이미지의

private Bitmap resizeImage(Bitmap workingImage, 
         int canvasWidth, int canvasHeight) 
    { 
     Image image = (Bitmap)workingImage.Clone(); 

     System.Drawing.Image thumbnail = 
      new Bitmap(canvasWidth, canvasHeight); 

     double ratioX = (double)canvasWidth/(double)workingImage.Width; 
     double ratioY = (double)canvasHeight/(double)workingImage.Height; 

     double ratio = ratioX < ratioY ? ratioX : ratioY; 

     int newHeight = Convert.ToInt32((double)workingImage.Height * ratio); 
     int newWidth = Convert.ToInt32((double)workingImage.Width * ratio); 

     int posX = Convert.ToInt32((canvasWidth - ((double)workingImage.Width * ratio))/2); 
     int posY = Convert.ToInt32((canvasHeight - ((double)workingImage.Height * ratio))/2); 

     using (Graphics graphic = Graphics.FromImage(thumbnail)) 
     { 
      graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
      graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; 
      graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; 
      graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; 

      graphic.Clear(SystemColors.Control); 
      graphic.DrawImage(image, posX, posY, newWidth, newHeight); //<--- HERE 
     } 

     System.Drawing.Imaging.ImageCodecInfo[] info = 
         System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); 
     System.Drawing.Imaging.EncoderParameters encoderParameters; 
     encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); 
     encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 
         100L); 

     return workingImage; 
    } 
+0

도움이 될 수 아래의 링크를 참조 전체 지역을 채우기 위해. 그리고 썸네일은 원본이 아닌 새로운 크기로 만들어야합니다 (canvasW 및 canvasH가 아님). – pasty

답변

5

크기는이

graphic.DrawImage(image, posX, posY, newWidth, newHeight); 

에만 지정된 인수로 이미지를 그립니다 여기

Image image = (Bitmap)workingImage.Clone(); 

정의되어 있지만, 이미지의 크기가 변경됩니다 것을 의미하지 않는다. 즉, 이미지 그리기는 단순히 크기를 변경하지 않고 이미지를 가져 와서 원하는대로 캔버스에 그립니다. 당신이 원하는, 그래서 당신이 시작 신선한 -

+0

물론! 그래픽이 축소판 그림으로 저장되며 이미지는 저장되지 않습니다. 이봐, 나 바보이거나 피곤해. 내가 그 것을 놓친 것을 믿을 수 없다 = D 도움을 주셔서 대단히 감사합니다! –

관련 문제