GetContentRect.cs
//
// This code is part of GrapeCity Documents for Imaging samples.
// Copyright (c) GrapeCity, Inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using GrapeCity.Documents.Drawing;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Imaging;

namespace GcImagingWeb.Samples
{
    // This sample demonstrates the use of GcBitmap.GetContentRect() method
    // that allows to trim single colored margins off an image.
    public class GetContentRect
    {
        public GcBitmap GenerateImage(int pixelWidth = 1024, int pixelHeight = 1024, bool opaque = true, float dpiX = 96, float dpiY = 96)
        {
            // The original goldfish image has white background with margins around the actual fish:
            var origImagePath = Path.Combine("Resources", "Stock", "goldfish.jpg");

            // Create the resulting bitmap:
            var targetBmp = new GcBitmap(pixelWidth, pixelHeight, true, dpiX, dpiY);
            using (var origBmp = new GcBitmap())
            {
                // Load the goldfish image:
                using (var stm = new FileStream(origImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.RandomAccess))
                    origBmp.Load(stm);
                // Create graphics on the resulting bitmap, filling it with blue color:
                using (var g = targetBmp.CreateGraphics(Color.FromArgb(unchecked((int)0xff004d99))))
                {
                    // Render the goldfish on white background:
                    targetBmp.BitBlt(origBmp, 0, 0);
                    // The GetContentRect() method returns the area of the image without
                    // margins of the specified color (white in this case):
                    var rc = origBmp.GetContentRect(Color.White);
                    // Draw a red border on the content rectangle:
                    g.DrawRectangle(rc, Color.Red);
                }
            }
            return targetBmp;
        }
    }
}