2011-10-25 87 views
0

我需要對圖像做兩件事:調整它的大小,然後裁剪它。裁剪圖形對象?

我調整這樣的:

nonResizedImage = new Bitmap(imagePath); 
Bitmap scaled = new Bitmap(preCropWidth, preCropHeight); 
using (Graphics scaledGraphics = Graphics.FromImage(scaled)) 
{ // scale image to the sizeo f the image the user cropped on 
    scaledGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 
    scaledGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed; 
    scaledGraphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; 
    scaledGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; 
    scaledGraphics.Clear(ColorTranslator.FromHtml("#FFFFFF")); 
    scaledGraphics.DrawImage(nonResizedImage, 0, 0, preCropWidth, preCropHeight); 
} 

現在我需要裁剪圖像。我找到了這樣一個功能:

static byte[] Crop(string Img, int Width, int Height, int X, int Y) 
{ 
    try 
    { 
     using (SD.Image OriginalImage = SD.Image.FromFile(Img)) 
     { 
      using (SD.Bitmap bmp = new SD.Bitmap(Width, Height)) 
      { 
       bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution); 

       using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp)) 
       { 
        Graphic.SmoothingMode = SmoothingMode.AntiAlias; 
        Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; 
        Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; 
        Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, Height, SD.GraphicsUnit.Pixel); 
        MemoryStream ms = new MemoryStream(); 
        bmp.Save(ms, OriginalImage.RawFormat); 
        return ms.GetBuffer(); 
       } 
      } 
     } 
    } 

    catch (Exception Ex) 
    { 
     throw Ex; 
    } 
} 

但是這需要一個圖像作爲輸入。所以,我可以將我的調整大小代碼的輸出保存到磁盤上,然後再次讀取它以完成裁剪,但這看起來毫無用處。雖然我不太瞭解c#中的圖像處理。

我該如何裁剪scaledGraphics我沒有先保存到磁盤?

回答

1

新位圖的重載之一是寬度,高度,圖形對象。您應該能夠將圖形對象傳入,然後從中創建位圖。像這樣的東西

static byte[] Crop(Graphics g, int Width, int Height, int X, int Y) 
    { 
     try 
     { 
      using (Bitmap bmp = new Bitmap(Width, Height, g)) 
      { 
      ... 
      } 
     } 
     ...... 
    }