Auto Trim Image with HTML5 canvas

10:32 PM 12/21/2018 - 3:39 PM 12/27/2018

I got this while was experimenting with pattern matching using HTML5 <canvas>. So instead of trimming words (from redundant left and right spaces), this one trims image from borders.

As a stand-alone application this might be quite handy, to auto crop images from excessive top, right, bottom and left borders quickly and thus make images more efficient for web purposes.

Note though that this only crops pixels which have exactly the same color and transparency of pixel at the top-left corner, or at the bottom-right corner. If you need some tolerance, well... feel free to dive into the source and adjust it by yourself:)
I've updated the test below to include "tolerance". Any pixels on sides which differs from top-left or bottom-right edges, and the difference value is still below tolerance, shall get cropped.

Test

Sorry, your browser doesn't support HTML5 canvas technology.

Sources

Sorry but I'm a bit tired of showing the sources here, but with your browser you can still easily locate them by right-click on "Test" element above and select "View Page Source" or "Inspect Element" on the popped-up context menu.

Hint: search for <form id="test"> element and also find some javascript lines inside <script src="page.js">

Good luck!

Comments