Im developing a java application that captures client signatures from Wacom USB tablet, creates a 320x200 pixels white background image with signature and stores into database, to print it on PDF later.
Before saving them, I would like to crop that images over signature. I mean, one client can sign on the left zone in the tablet and another one on the right zone. So all signatures would have different positions in the signature image and useless white space. For example, different signature images and I would like something like this
So my question is, is this possible? Is there any option to crop these images dynamically over signature before save it? Knowing all signatures have different size can't crop always from same positions. Or would be better, for example, to print a rectangle in the tablet forcing clients to sign inside it? (Don't know is this would be possible, I suppose yes).
Thanks.
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class Cropper {
public static void main(String[] args) throws IOException {
BufferedImage src = ImageIO.read(new URL("https://www.citrix.com/blogs/wp-content/uploads/2015/02/Signature-Richard1.jpg"));
int x0=src.getWidth();
int y0=src.getHeight();
int x1=0;
int y1=0;
//just a guess: the pixels color at 0,0 is wht you want to crop
int unusedcolor=src.getRGB(0,0);
//iterate over all pixels
for (int y = 0; y < src.getHeight(); y++) {
for (int x = 0; x < src.getWidth(); x++) {
int clr = src.getRGB(x, y);
if (clr!=unusedcolor)
{
//pixel is used, shift the new borders accordingly
x0=Math.min(x0, x);
y0=Math.min(y0, y);
x1=Math.max(x1, x);
y1=Math.max(y1, y);
}
}
}
if (x1>x0 && y1>y0)
{
BufferedImage dest = src.getSubimage(x0, y0, x1-x0,y1-y0);
ImageIO.write(dest, "png", new File("out.png"));
Runtime.getRuntime().exec("cmd /c start out.png");
}
}
}