2017-12-19 5 views
0

안녕하세요,이 이미지는 모두 here 크기 조정 코드이며 현재 코드에 맞게 조정하려고합니다. C# WPF 가로 세로 또는 세로 비율

private void resizeImage(string path, string originalFilename, 
        /* note changed names */ 
        int canvasWidth, int canvasHeight, 
        /* new */ 
        int originalWidth, int originalHeight) 
{ 
    Image image = Image.FromFile(path + originalFilename); 

    System.Drawing.Image thumbnail = 
     new Bitmap(canvasWidth, canvasHeight); // changed parm names 
    System.Drawing.Graphics graphic = 
       System.Drawing.Graphics.FromImage(thumbnail); 

    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; 
    graphic.SmoothingMode = SmoothingMode.HighQuality; 
    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; 
    graphic.CompositingQuality = CompositingQuality.HighQuality; 

    /* ------------------ new code --------------- */ 

    // Figure out the ratio 
    double ratioX = (double) canvasWidth/(double) originalWidth; 
    double ratioY = (double) canvasHeight/(double) originalHeight; 
    // use whichever multiplier is smaller 
    double ratio = ratioX < ratioY ? ratioX : ratioY; 

    // now we can get the new height and width 
    int newHeight = Convert.ToInt32(originalHeight * ratio); 
    int newWidth = Convert.ToInt32(originalWidth * ratio); 

    // Now calculate the X,Y position of the upper-left corner 
    // (one of these will always be zero) 
    int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio))/2); 
    int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio))/2); 

    graphic.Clear(Color.White); // white padding 
    graphic.DrawImage(image, posX, posY, newWidth, newHeight); 

    /* ------------- end new code ---------------- */ 

    System.Drawing.Imaging.ImageCodecInfo[] info = 
        ImageCodecInfo.GetImageEncoders(); 
    EncoderParameters encoderParameters; 
    encoderParameters = new EncoderParameters(1); 
    encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 
        100L);    
    thumbnail.Save(path + newWidth + "." + originalFilename, info[1], 
        encoderParameters); 
} 

그리고 내 현재 코드 :

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
{ 
    string path = value as string; 

    if (path != null) { 
     //create new stream and create bitmap frame 
     var bitmapImage = new BitmapImage(); 

     bitmapImage.BeginInit(); 
     bitmapImage.StreamSource = new FileStream(path, FileMode.Open, FileAccess.Read); 
     //load the image now so we can immediately dispose of the stream 
     bitmapImage.CacheOption = BitmapCacheOption.OnLoad; 
     bitmapImage.EndInit(); 

     //clean up the stream to avoid file access exceptions when attempting to delete images 
     bitmapImage.StreamSource.Dispose(); 

     return bitmapImage; 
    } else { 
     return DependencyProperty.UnsetValue; 
    } 
} 

문제의 존재가 resizeImage 코드가 이미지를 사용하여 내 현재 코드가 BitmapImage를 사용한다는 것입니다.

저는 하나의 형식 또는 다른 형식으로 변환하는 방법을 찾으려고했지만 제대로 수행하지 못했습니다.

resizeImage이 내가 실행할 수 없기 때문에 필요로하는 것이 확실하지 않지만 이미지를 가로 또는 세로로 검색하려고합니다. 수직면의 크기가 크거나 작 으면 크기가 조정되어 지정된 영역에 맞 춥니 다. 마찬가지로 가로도 세로와 같은 방식입니다.

+0

비트 맵의 ​​종횡비가 * 세로 *이면 (예 : 너비가 너비보다 큼) 어떻게 든 * 가로 *로 변환하고 회전시키지 않으려합니다. 그게 어떻게 된거 야? 부품을 잘라내거나 왜곡하여 (예 : 한 방향으로 만 조정)? BitmapImage는 Image 요소에 의해 확실히 표시됩니다. Image 요소는 이미 Source를 균일하게 변형 할 수 있기 때문에 BitmapImage를 전혀 조작 할 필요가 없습니다. – Clemens

+0

[WPF에서 BitMapImage의 크기 변경 및 요소에 어떤 종류의 객체를 넣을 수 있습니까?] (https://stackoverflow.com/questions/17072775/changing-the-dimensions-of-a) -bitmapimage-in-wpf-what-kind-of-objects-i- – PaulF

+1

이 코드를 모두 고치고 이미지의 'Stretch' 속성을 사용할 수 있습니다. –

답변

0

는 크기를 변환하는 방법에는 여러 가지가 있습니다,하지만 난 System.Drawing.Bitmap에에서 BitmapSource는 를 변환하는 방법에 대한 웹에 많이 없다 이후 직접 귀하의 질문에 대답하고 싶었다. (다른 방법으로가는 것에 대한 많은 기사가 있습니다).

어떤 WPF BitmapSource는 변환합니다이 기능

- BitmapSource는이다 BitmapImage를 포함하여 - System.Drawing.Bitmap에 :

System.Windows.Media.Imaging.BitmapSource bitmapSource; 
    using (System.IO.Stream stm = System.IO.File.Open("c:\\foo_in.png", System.IO.FileMode.Open, System.IO.FileAccess.Read)) 
    { 
     // Since we're not specifying a System.Windows.Media.Imaging.BitmapCacheOption, the pixel format 
     // will be System.Windows.Media.PixelFormats.Pbgra32. 
     bitmapSource = System.Windows.Media.Imaging.BitmapFrame.Create(
      stm, 
      System.Windows.Media.Imaging.BitmapCreateOptions.None, 
      System.Windows.Media.Imaging.BitmapCacheOption.OnLoad); 
    } 
    System.Drawing.Bitmap bmp = ConvertBitmapSourceToDrawingBitmap(bitmapSource); 
    bmp.Save("c:\\foo_out.png", System.Drawing.Imaging.ImageFormat.Png); 
:

private System.Drawing.Bitmap ConvertBitmapSourceToDrawingBitmap(BitmapSource image) 
{ 
    int width = Convert.ToInt32(image.Width); 
    int height = Convert.ToInt32(image.Height); 
    int stride = Convert.ToInt32(width * ((image.Format.BitsPerPixel + 7)/8) + 0.5); 

    byte[] bits = new byte[height * stride]; 
    image.CopyPixels(bits, stride, 0); 

    System.Drawing.Bitmap bitmap = null; 
    unsafe 
    { 
     fixed (byte* pBits = bits) 
     { 
      IntPtr ptr = new IntPtr(pBits); 
      bitmap = new System.Drawing.Bitmap(width, height, stride, System.Drawing.Imaging.PixelFormat.Format32bppPArgb, ptr); 
     } 
    } 

    return bitmap; 
} 

그것을 테스트하려면, 나는이 코드를 사용

관련 문제