Skip to content

RgbImage

ReferenceType edited this page Mar 12, 2025 · 2 revisions

RgbImage Class

The RgbImage class represents an RGB, BGR, RGBA or BGRA image with support for both managed and unmanaged memory. It provides methods for memory management, cropping, and aspect ratio adjustment.

Table of Contents


Overview

The RgbImage class is designed to handle RGB format images with efficient memory allocation. It supports both managed and unmanaged memory modes.

Features:

  • Supports RGB, BGR, RGBA or BGRA formats.
  • Handles both managed (byte[]) and unmanaged (IntPtr) memory.
  • Provides methods for cropping and aspect ratio adjustment without any copy.
  • Implements IDisposable for proper memory management.
  • Unmanaged memory is freed on disposal only if the memory is allocated by this class(owns).

Constructors

Constructor Description
RgbImage(ImageFormat format, int width, int height) Allocates unmanaged memory for the image, size depending on format.
RgbImage(ImageFormat format, int width, int height, int stride, byte[] data) Creates an image from an existing byte array without allocating new memory.
RgbImage(ImageFormat format, int width, int height, byte[] data) Assumes default stride((w3) or (w4)) and uses an existing byte array.
RgbImage(ImageFormat format, int width, int height, int stride, IntPtr imageBytes) References an existing unmanaged memory block.

Properties

Property Type Description
Format ImageFormat The image format (RGB, BGR, RGBA or BGRA).
Width int The image width in pixels.
Height int The image height in pixels.
Stride int The number of bytes per row.
IsManaged bool Indicates if memory is managed (true) or unmanaged (false).
NativeBytes IntPtr Pointer to unmanaged image data (if applicable).
ManagedBytes byte[] Managed image data (if applicable).
dataOffset int Offset within the data buffer.
dataLength int Length of the image data in bytes.

Methods

Method Return Type Description
Crop(int top, int bottom, int left, int right) RgbImage Creates a cropped shallow copy of the image.
ChangeAspectRatio(int targetWidth, int targetHeight) RgbImage Adjusts the aspect ratio of the image by cropping.
GetBytes() byte[] Returns the image data as a byte array.
CopyTo(MemoryStream stream) void Copies image data to a memory stream.
Dispose() void Releases unmanaged memory.

Usage Examples

Creating a New Image

RgbImage img = new RgbImage(ImageFormat.Rgb, 1920, 1080);

Creating an Image from Managed Memory

byte[] data = new byte[800 * 600 * 3]; // RGB format
RgbImage img = new RgbImage(ImageFormat.Rgb, 800, 600, data);

Cropping an Image

RgbImage cropped = img.Crop(10, 10, 20, 20);

Adjusting Aspect Ratio

RgbImage adjusted = img.ChangeAspectRatio(16, 9);

Releasing Resources

img.Dispose();

This documentation provides a structured overview of the RgbImage class and its functionalities.