brianium / watermarkjs

:rice_scene: Watermarking for the browser
http://brianium.github.io/watermarkjs/
Other
1.73k stars 230 forks source link

Watermarking on list of images eats up CPU #41

Open jduelfer opened 6 years ago

jduelfer commented 6 years ago

I am using your library to watermark a series of images for a slideshow in a website. I have noticed however that the image() function hogs the CPU on my computer. To help the problem, I am initially loading the page and then setting timeouts reasonably apart to separate the writing to the canvas (which I believe is the source of the issue?). When I am writing the watermarks the page gets pretty laggy because it's eating up all the CPU.

Do you have any suggestion for how to implement your library on a list of images?

brianium commented 6 years ago

Hmmm - I'm not aware of anything specific in the library that would be causing this without doing some profiling. In the past I've been able to watermark series of images without much of a problem. How many images are we talking about?

There could be a lot of factors at work here. The series I've run before have used an async or timeout approach - as used here (http://brianium.github.io/watermarkjs/pooling.html) (not a perfect example for many different images - but maybe illustrates).

The CanvasPool implementation right now leaves a little to be desired as it has potential to grow unbounded. I could see this causing some issues :) - A PR to address this would definitely be welcome.

Also watermark.destroy() will clear the canvas pool - so if you are doing this serially maybe there is an opportunity to call that at certain points?

jduelfer commented 6 years ago

I'm pretty much doing the same thing, but trying to slowly increment the time between each call to allow the Garbage Collector to clean up. This is what I'm doing, I don't believe there is anything different.

function watermarkAllImages() {
    for (var i = 0; i < loadedPicturesQueue.length; i++) {
        watermarkImage(loadedPicturesQueue[i], i);
    }
}

function watermarkImage(imageToWatermark, i) {
    setTimeout(function() {
        watermark([imageToWatermark.src, document.getElementById('watermarkImageTag')], options)
            .image(watermark.image.center(0.6))
            .then(function(img) {
                watermarkCounter++;
                var picId = imageToWatermark.id.split('-')[1];
                $('a#pictureContainer-' + picId).attr('href', img.src); // used for slideshow
            }
        );
    }, 1500 + i * 100); // slowly increment to not lockup browser
}

There can be up to 15-20 images, and that's when it really goes crazy. I did some profiling and it seems like the Garbage Collector might be causing a bit of the locking up.

I will definitely try to submit a pull request if I can get some time to solve this problem, because it's a really cool library.

brianium commented 6 years ago

awesome! I'm glad you have found it useful 👍