Search code examples
javascriptprocessingp5.jsimagefilter

p5.js: Add filter to uploaded image


I want to add gray filter to the uploaded image.But using img.filter(GRAY,0.3) do not work. I know img is an p5 element here,is there any way to select the image source only and add filter to the uploaded image?

var img,canvas;

function setup(){
    var uploadBtn = createFileInput(imageUpload);
    canvas=createCanvas(500,400);
}
function imageUpload(file){
    img = loadImage(file.data,function(){
        image(img,0,0,width,height);
        img.filter(GRAY,0.5);
    })
    
}
<script src="https://github.com/processing/p5.js/releases/download/0.5.7/p5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.7/addons/p5.dom.min.js"></script>


Solution

  • This is because you apply the filter after displaying the image.When imageUpload() function is called, and image(img,0,0,width,height); is executed, the img image is displayed on the page, however that's static, it does not update like it would if it was in draw() and hence applying the image filter after displaying the image does not change anything (The image doesn't update because it's static). If you wrote the exact same code in draw() it would work because that gets called repeatedly. To fix this simply apply the grey filter before displaying the image :

    var img,canvas;
    
    function setup(){
        var uploadBtn = createFileInput(imageUpload);
        canvas=createCanvas(500,400);
    }
    function imageUpload(file){
        img = loadImage(file.data,function(){
            img.filter(GRAY,0.5);
            image(img,0,0,width,height);            
        })        
    }
    <script src="https://github.com/processing/p5.js/releases/download/0.5.7/p5.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.7/addons/p5.dom.min.js"></script>