P5.js: Calling Resize on an Image Reduces Quality

Date: 2016-01-09 |

You can view my example solution on GitHub or at the bottom of this post.

**Problem: **In a P5.js sketch, repeatedly calling image.resize() when the window resizes causes my image quality to degrade/become blurry. Is there a way I can resize the image without reducing the quality?

**Solution: **The reason this happens is that calling resize changes the image that P5 has in memory. So say you resize the image to make it smaller. P5 now only stores the information required to display the image at that size. Subsequently increasing the size of that image would cause the image quality to degrade because the program now only has the information to display the image at the smaller size which leads to a blurry effect.

The solution to this problem is to use the image() function to size your images to the window. Instead of using the image() call that takes in three parameters, we’re going to use the one that takes five:

image(imgVar, xVal, yVal, imgWidth, imgHeight)

  • imgVar – The variable in which you loaded the image. In my examples, this is exImg
  • xVal – The x value on the canvas where you’d like your image rendered
  • yVal – The y value of the canvas where you’d like your image rendered
  • imgWidth – The desired width of your image
  • imgHeight – The desired height of your image

Coding the image’s width and height directly into the image() call ensures that the size of the image stored in memory isn’t changed, rather we’re changing the size of the image being rendered. Thus subsequent calls won’t be affected by previous calls and we can change the rendering size to our heart’s content.

**TL;DR **Use image() to set the image’s size, not resize()

(https://gist.github.com/SIRHAMY/1c0b7581e82e6eaf6e8a)

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.