2011-10-25 68 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)) 
      { 
      ... 
      } 
     } 
     ...... 
    }