Created
December 28, 2023 16:20
-
-
Save eisterman/03e9307d2fa16f702576c0e54e950acd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const c = @cImport({ | |
@cInclude("stdlib.h"); | |
@cInclude("stdio.h"); | |
@cInclude("png.h"); | |
}); | |
const WIDTH = 800; | |
const HEIGHT = 600; | |
pub fn main() !void { | |
// Allocator | |
var gpa = std.heap.GeneralPurposeAllocator(.{}){}; | |
const allocator = gpa.allocator(); | |
defer { | |
const deinit_status = gpa.deinit(); | |
if (deinit_status == .leak) @panic("LEAK"); | |
} | |
// File and PNG Lib | |
const fp = c.fopen("random.png", "wb") orelse return error.FileError; | |
defer _ = c.fclose(fp); | |
var png_ptr = c.png_create_write_struct(c.PNG_LIBPNG_VER_STRING, null, null, null) orelse return error.PngException; | |
defer c.png_destroy_write_struct(@ptrCast(&png_ptr), null); | |
var info_ptr = c.png_create_info_struct(png_ptr) orelse return error.PngException; | |
defer c.png_free_data(png_ptr, info_ptr, c.PNG_FREE_ALL, -1); | |
if (c.setjmp(@constCast(&c.png_jmpbuf(png_ptr))) > 0) return error.PngException; | |
c.png_init_io(png_ptr, fp); | |
// Write header (8 bit colour depth) | |
c.png_set_IHDR(png_ptr, info_ptr, WIDTH, HEIGHT, 8, c.PNG_COLOR_TYPE_RGB, c.PNG_INTERLACE_NONE, c.PNG_COMPRESSION_TYPE_BASE, c.PNG_FILTER_TYPE_BASE); | |
c.png_write_info(png_ptr, info_ptr); | |
// Allocate memory for one row (3 bytes per pixel - RGB) | |
var row = try allocator.alloc(c.png_byte, 3 * WIDTH); | |
defer allocator.free(row); | |
// Random Numbers | |
// var prng = std.rand.DefaultPrng.init(10); | |
// const rand = prng.random(); | |
// _ = rand; | |
// Write image data | |
for (0..HEIGHT) |y| { | |
for (0..WIDTH) |x| { | |
const n: f64 = @as(f64, @floatFromInt((x * y) % 300)) / 300; | |
const color: u8 = @intFromFloat(@round(255 * n)); | |
row[x * 3] = color; // Red | |
row[x * 3 + 1] = color; // Green | |
row[x * 3 + 2] = color; // Blue | |
} | |
c.png_write_row(png_ptr, row.ptr); | |
} | |
// End write | |
c.png_write_end(png_ptr, null); | |
std.debug.print("Image created!\n", .{}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment