Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptp5.Image save() Method

p5.Image save() Method

The save() method of p5.Image in p5.js is used to save the image to a file by forcing the browser to download it. The file can be saved in two formats, ‘png’ and ‘jpg’. It can also be saved with a ‘gif’ extension if an animated GIF is used with the p5.Image.

Note: It is not recommended calling this function inside the draw() loop, as it will prompt a new save dialog every draw call.

Syntax:

save( filename, extension )


Parameters: This function accepts two parameters as mentioned above and described below. 

  • filename: It is a String that specifies the filename of the saved file.
  • extension: It is a String that specifies the extension of the saved file. It can be either of the value ‘png’ or ‘jpg’.

The examples below illustrate the save() method in p5.js:

Example 1:

javascript




function preload() {
    img = loadImage("sample-image.png");
}
 
function setup() {
    createCanvas(500, 300);
    textSize(20);
 
    // Apply filter to image
    img.filter(GRAY);
 
    text('Current Image', 20, 20);
    image(img, 20, 40, 200, 100);
}
 
function keyTyped() {
 
  // Pressing the "q" key to
  // save the image
  if (key === 'q') {
    img.save('saved-image', 'png');
  }
}


Output:

Example 2:

javascript




function preload() {
    img = loadImage("sample-gif.gif");
}
 
function setup() {
    createCanvas(500, 300);
    textSize(20);
 
    text('Current GIF', 20, 20);
    image(img, 20, 40, 200, 100);
 
    btnSave = createButton("Save GIF");
    btnSave.position(30, 160);
    btnSave.mousePressed(saveImg);
}
 
function saveImg() {
 
    // Save the GIF
    img.save("new-gif");
}


Output:

Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5.Image/save

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments