Public
Script
Readme

Playing with Pixels in JavaScript

Programmatically generate PNG images, pixel by pixel!

This val uses PNGLib and Val Town's Express API to create and host PNG images. It can be particularly useful if you want to dynamically generate an image โ€“ for any website or API that accepts png urls.

Usage

  1. Copy and paste the code below or fork one of the examples
  2. Click the ๐Ÿ”’ lock to make your val public
  3. Visualize your image in via its Express endpoint: Open the [โ‹ฎ] menu > Endpoints > Copy express endpoint
// Code from @andreterron.hostpng_example let my_image = @andreterron.png({ width: 256, height: 256, }, (p) => { const w = p.width, h = p.height; // Create colors (red, green, blue, alpha) const white = p.color(255, 255, 255, 255); // PNG starts filled with the first color const black = p.color(0, 0, 0, 255); for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { // Get the buffer index for this position let index = p.index(x, y); // Set the color for the specific pixel p.buffer[index] = (x * y) / (w * h) * 24 % 2 >= 1 ? black : white; } } });

Code from @andreterron.hostpng_example, and it generates this image:

this example

Other Examples

Gradient

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { png64 } from "https://esm.town/v/andreterron/png64";
import { Buffer } from "node:buffer";
export function png(
{ width, height, depth = 256 }: {
width: number;
height: number;
depth?: number;
},
callback: (png: {
width: number;
height: number;
color: (r: number, g: number, b: number, alpha: number) => string;
buffer: string[];
index: (x: number, y: number) => number;
getBase64: () => string;
getDump: () => string;
palette: Record<string, string>;
}) => void | Promise<void>,
) {
return async function(req: Request) {
var img = await png64(
{ width, height, depth },
callback,
);
var imgbase64 = new Buffer(img, "base64");
return new Response(imgbase64, {
headers: {
"Content-Type": "image/png",
},
status: 200,
});
};
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
September 4, 2024