Skip to content

crop() #12

Description

@loftafi

Would a crop() helper function be welcome. Happy to make a pull request.

fn crop(
    img: Image,
    x: usize,
    y: usize,
    width: usize,
    height: usize,
) zstbi.Image {
    var new_img = try zstbi.Image.createEmpty(@intCast(width), @intCast(height), img.num_components, .{
        .bytes_per_component = img.bytes_per_component,
        .bytes_per_row = @intCast(width * img.bytes_per_component * img.num_components),
    });

    const n: usize = img.bytes_per_component * img.num_components;
    std.debug.assert(img.width * img.height * img.num_components * img.bytes_per_component == img.data.len);
    std.debug.assert(width * height * n == new_img.data.len);

    for (0..height) |row| {
        const src = (y + row) * img.width * n + x * n;
        const source = img.data[src .. src + new_img.bytes_per_row];
        const dst = row * new_img.bytes_per_row;
        const destination = new_img.data[dst .. dst + new_img.bytes_per_row];
        @memcpy(destination, source);
    }

    return new_img;
}

I have bounds checking code as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions