Utilize images inputted via an HTML DOM file uploader within p5.js

I'm facing a challenge with allowing users to upload their image file through a DOM file uploader (

<input type="file"></input>
). Once the image is uploaded, I'm unsure of how to transfer it to JavaScript and process it using p5.js. How can I convert an HTML file to a p5.js file or an array of pixels that I can manipulate in JavaScript?

Initially, I set restrictions on the element to only accept .png and .jpg files.

I attempted to use the .file[0] syntax and load the image by its path using the .value within the loadImage() function.

Unfortunately, neither method worked for me, and I'm feeling lost about what steps to take next.

<div id="uploadMenu">
  <h4>Please select your image file:</h4>
  <input accept=".png, .jpg, .jpeg" type="file" id="imageUpload">
  <button onclick="fileToGrid()">Done</button>
  <script>
  </script>
  <script>
  let thisWindow = document.getElementById("uploadMenu");
  let windowWidth = thisWindow.style.width;
  console.log(windowWidth);
  thisWindow.style.left = `${innerWidth/2 - 100}px`
  thisWindow.style.top = `${innerHeight/2 - 50}px`
  </script>
</div>
function fileToGrid() {
  let uploadFromHTML = document.getElementById("imageUpload");
  let uploadedImage = loadImage(uploadFromHTML.value);
  let imageW = uploadedImage.width;
  let imageH = uploadedImage.height;
  console.log(imageW, imageH); 
// My ultimate goal is to convert this image into an array of pixel values.
}

Answer №1

It's been a little while since I originally posted this, but I finally figured it out.

First, we need to locate the upload element in the DOM. In my example, the id was simply "upload".

const selectedFile = document.getElementById('upload');

Next, we retrieve the uploaded file.

const myImageFile = selectedFile.files[0];

We can then generate a URL for the image using the following code.

let urlOfImageFile = URL.createObjectURL(myImageFile);

If you're working with p5.js, you can use the following code snippet to create a p5.Image object.

let imageObject = loadImage(urlOfImageFile);

I suggest setting up a callback function when working with images, as they may not load instantaneously. The complete process looks like this:

const selectedFile = document.getElementById('upload');
const myImageFile = selectedFile.files[0];
let urlOfImageFile = URL.createObjectURL(myImageFile);
let imageObject = loadImage(urlOfImageFile, () => {image(imageObject, 0, 0)});

Alternatively, you can also use the same URL as the src attribute for an image element in the DOM.

Answer №2

Take a look at the createFileInput() function. You can find more information about it here.

Here's an example from the page:

let img;

function setup() {
  input = createFileInput(handleFile);
  input.position(0, 0);
}

function draw() {
  background(255);
  if (img) {
    image(img, 0, 0, width, height);
  }
}

function handleFile(file) {
  print(file);
  if (file.type === 'image') {
    img = createImg(file.data);
    img.hide();
  } else {
    img = null;
  }
}

This demonstration illustrates how to implement a file input in P5.js and extract an image from it.

You might be able to achieve similar results with an existing file input in the DOM.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps are involved in setting up a point distribution system in AngularJS?

My objective is to develop a point allocation system within AngularJS. I have successfully created a basic directive that introduces DOM elements, including a span displaying "0" points and buttons for incrementing and decrementing. The total number of poi ...

How can AngularJS handle uploading multipart form data along with a file?

Although I am new to angular.js, I have a solid understanding of the fundamentals. My goal is to upload both a file and some form data as multipart form data. I've learned that this is not a built-in feature of angular, but third-party libraries can ...

Is your Bootstrap input displaying the has-error class with a glyphicon, but the alignment is not vertically centered?

What is the reason for the misalignment of glyphicon-warning-sign form-control-feedback vertically in the code below after applying font-size: 20px; to the label? <div class="container"> <div class="content align-left contact"> ...

What is the best way to ensure that a div appears below, rather than alongside, another one

I need help positioning my divs on the webpage. Currently, my map div is appearing next to the list instead of below it. The height of the list can vary as it is generated dynamically. I want the map div to be on the right side with the list displayed on t ...

The scrollbar track has a habit of popping up unexpectedly

Is there a way to prevent the white area from showing up in my divs where the scroll bar thumb appears? The issue seems to occur randomly on Chrome and Safari. This is the div in question .column-content{ height:60vh; padding: 10px 3px 0 3px; overf ...

What is the best way to apply CSS styles to a child div element in Next.js?

I'm currently working on enhancing the menu bar for a website project. Utilizing nextjs for my application I am aiming to customize the look of the anchor tag, however, encountering some issues with it not rendering correctly. Here is a snippet of ...

Fulfill the promise in AngularJS and assign it to a different factory

Presenting my factory below: .factory('UserData', ['User', '$q', function(User, $q) { var deferred = $q.defer(); return { user: null, get: function() { var _this = this; _this. ...

What could be causing my anchored link to redirect incorrectly?

My navigation bar correctly directs me to the 'work' section, but when I click on ABOUT in the navigation bar, it drops down about 300px above the 'about' h2. I suspect that this issue may be related to positioning and display settings. ...

The stop-color property is not functioning as expected in CSS/SVG

Here is the code I am currently working with: <?xml version="1.0" standalone="yes"?> <svg xmlns="http://www.w3.org/2000/svg" width="360" height="240"> <style>stop{stop-opacity:1}circle{fill:url(#r)}</style> <defs> <radialG ...

NodeJS: Speed up your workflow by compressing video files

In my quest to enhance the performance of my application, I am seeking ways to compress images and videos to their smallest possible size without sacrificing quality. This process is known as lossless compression. While the imagemin package has proven eff ...

How can I display several custom markers that are constantly updating on a Google map with MySQL and PHP?

Currently, I am using the following code to generate markers on a Google map by retrieving data from a database. However, the issue I am facing is that it only generates one marker instead of all the markers stored in the database. & ...

Preserve StepContent information within Material-ui Stepper during updates to the active step

I have a Stepper component with multiple steps, each containing several TextFields. The issue is that material-ui unmounts the step contents when you switch steps, causing all the data in the TextFields to be lost. My question is: Is there a way to prese ...

Deactivating Cluetip tool tips and adjusting the height limit in JQuery

How can I momentarily turn off the hints? I have seen references to being able to do so on the website and in this forum, but I am having trouble locating the command to disable them. I just need to temporarily deactivate them and then enable them again. ...

Is there a way to solely adjust the color of a -box-shadow using jquery?

Looking for a way to incorporate tinycolor, a color manipulation framework, into setting a box-shadow color. Instead of directly setting the box-shadow with jQuery, you can use tinycolor on an existing color variable. $("CLASS").css("box-shadow", "VALUE") ...

The Geocoder.geocode() method returns XML instead of JSON when invalid credentials are provided

Currently in the process of developing a program that converts addresses from a database to their corresponding lat/long coordinates using the HERE Geocoding API. In order for multiple users to utilize this program, they must manually input their app_id an ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

JavaScript - Separate Artist and Title

In the code snippet below, I am using a Parser script to extract metadata from a live streaming radio station: const Parser = require('../src'); const radioStation = new Parser('http://stream.com/live_32.aac'); radioStation.on(' ...

Utilize the Multer file upload feature by integrating it into its own dedicated controller function

In my Express application, I decided to keep my routes.js file organized by creating a separate UploadController. Here's what it looks like: // UploadController.js const multer = require('multer') const storage = multer.diskStorage({ dest ...

Clicking the Less/More button using jQuery

In my current setup, I have a code snippet that loads and displays two comments initially. There is also a button labeled More comments which, when clicked, fetches and shows the remaining comments using AJAX. Upon clicking the More comments button, it tr ...

How to retrieve a subobject using AngularJS

From my perspective : <span data-ng-init="fillEditForm['titi']='toto'" ></span> In my Angular controller : console.log($scope.fillEditForm); console.log($scope.fillEditForm['titi']); The outcome : Object { ti ...