2017-05-09 13 views
1

我有一個大的圖像(至少200 MB和高達2 GB)與剪切路徑。我想應用剪切路徑來刪除背景。我目前發現的唯一解決方案(ConvertClippingPathToMask)使用了一個位圖,它將整個圖像加載到內存中並引發OutOfMemoryException。如何使用Graphicsmill中的管道刪除具有clippingPath的圖像的背景?

/// <summary> 
    /// Converts clipping path to alpha channel mask 
    /// </summary> 
    private static void ConvertClippingPathToMask() 
    { 
     using (var reader = new JpegReader("../../../../_Input/Apple.jpg")) 
     using (var bitmap = reader.Frames[0].GetBitmap()) // I can get rid of this line by using reader instead of bitmap in the next line, but then the OOM will throw in the next line. 
     using (var maskBitmap = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format8bppGrayscale, new GrayscaleColor(0))) 
     using (var graphics = maskBitmap.GetAdvancedGraphics()) 
     { 
      var graphicsPath = reader.ClippingPaths[0].CreateGraphicsPath(reader.Width, reader.Height); 

      graphics.FillPath(new SolidBrush(new GrayscaleColor(255)), Path.Create(graphicsPath)); 

      bitmap.Channels.SetAlpha(maskBitmap); 

      bitmap.Save("../../../../_Output/ConvertClippingPathToMask.png"); 
     } 
    } 

通過這種方法,總是需要位圖來獲取圖形對象,然後應用剪切路徑。

實際上,我甚至不需要內存中的maskBitmap,因爲我可以使用單獨的讀取器來設置setAlpha,但是:如何創建不帶位圖的maskBitmap來創建圖形對象?

回答

0

正確的方法是使用管道API:

using (var reader = new JpegReader("ImageWithPath.jpg")) 
using (var gc = new GraphicsContainer(reader)) 
using (var ig = new ImageGenerator(gc, PixelFormat.Format8bppGrayscale, RgbColor.Black)) 
using (var setAlpha = new Aurigma.GraphicsMill.Transforms.SetAlpha()) 
{ 
    using (var gr = gc.GetGraphics()) 
    { 
     var path = reader.ClippingPaths[0].CreateGraphicsPath(reader.Width, reader.Height); 
     gr.FillPath(new SolidBrush(RgbColor.White), Aurigma.GraphicsMill.AdvancedDrawing.Path.Create(path)); 
    } 

    setAlpha.AlphaSource = ig; 

    Pipeline.Run(reader + setAlpha + "output.png"); 
} 
+0

這不適用於所有路徑(儘管對於大多數路徑)。在這裏看到我的答案或Fedors在forums.aurigma.com/yaf_postst15163_Crop-image-from-Path.aspx上回答。無論如何,我接受你的答案,因爲你花時間去創造它。 – Sebastian

0

爲了完整起見:
這從Aurigma.Forums解決方案由費奧多爾涵蓋某些情況下,這Eugenes解決方案不。

using (var reader = ImageReader.Create("../../../PathForTest.tif")) 
using (var maskGen = new ImageGenerator(reader.Width, reader.Height, PixelFormat.Format8bppGrayscale, RgbColor.Black)) 
using (var drawer = new Drawer()) 
using (var bitmap = new Bitmap()) 
{ 
    var graphicsPath = Aurigma.GraphicsMill.AdvancedDrawing.Path.Create(reader.ClippingPaths[0], reader.Width, reader.Height); 

    drawer.Draw += (sender, e) => 
    { 
     e.Graphics.FillPath(new SolidBrush(new GrayscaleColor(255)), graphicsPath); 
    }; 

    using (var setAlpha = new SetAlpha(maskGen + drawer)) 
    { 
     (reader + setAlpha + bitmap).Run(); 
     bitmap.Save("../../../result.tif"); 
    } 
}