Skip to content

Instantly share code, notes, and snippets.

@GoToLoop
Forked from gncgnc/resizeNN.js
Last active January 2, 2026 23:21
Show Gist options
  • Select an option

  • Save GoToLoop/2e12acf577506fd53267e1d186624d7c to your computer and use it in GitHub Desktop.

Select an option

Save GoToLoop/2e12acf577506fd53267e1d186624d7c to your computer and use it in GitHub Desktop.
Extends p5.Image to handle nearest neighbor resizing for scaling images w/o blurring.
/**
* Resize the image to a new width and height using nearest neigbor algorithm. To make the image scale
* proportionally, use 0 as the value for the wide or high parameter.
* For instance, to make the width of an image 150 pixels, and change
* the height using the same proportion, use resize(150, 0).
*
**** Note: Disproportionate resizing squashes the "pixels" from squares to rectangles.
*/
p5.Image.prototype.resizeNN = function(width, height) {
if (width === 0 && height === 0) {
width = this.canvas.width;
height = this.canvas.height;
} else if (width === 0) {
width = this.canvas.width * height / this.canvas.height;
} else if (height === 0) {
height = this.canvas.height * width / this.canvas.width;
}
width = Math.floor(width);
height = Math.floor(height);
var temp = createImage(width,height),
wScale = width / this.width ,
hScale = height / this.height
this.loadPixels()
temp.loadPixels()
for(var x=0; x<temp.width; x++) {
for(var y=0; y<temp.height; y++) {
// var ind = 4*(y*img.width + x)
var sourceP = this.get(1.0*x/wScale, 1.0*y/hScale)
temp.set(x,y,sourceP)
}
}
temp.updatePixels()
this.updatePixels()
this.canvas.width = this.width = width;
this.canvas.height = this.height = height;
console.log(temp)
this.drawingContext.drawImage(temp.canvas,
0, 0, width, height,
0, 0, width, height
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment