需求介绍
项目需要实现在线无纸化合同签署,调用触屏手写签名生成电子合同,在生成合同过程中需要调用OCR 技术对签署文字进行识别,在此过程中,生成的电子签图片背景必须是透明的(为了附着在合同上),但是OCR技术对透明图片上文字无法识别,因此在调用OCR前需要对图片进行处理,增加背景颜色,提高识别率。
解决方式
- 查阅资料发现许多同学使用 java Graphics2D 直接修改透明图片,但是直接修改的结果是添加了背景颜色,但是不是我们需要的背景颜色,参考地址:
- 本文的解决方式是预先生成一个白色底片,将透明图片附在生成的白色图片上,达到添加背景的目的,具体代码如下:
/**
* 前端传递的参数为base64编码的字符串
* @param picStr
* @return
*/
public void str2Image(String picStr) {
byte[] decode = Base64Utils.decode(picStr);
InputStream in = new ByteArrayInputStream(decode);
BufferedImage srcImage;
try {
srcImage = ImageIO.read(in);
changeImageBackground(srcImage);
} catch (IOException e) {
log.error("ocr 将str转化io异常:", e);
throw new ServiceException("图片添加背景色异常");
}
}
public void changeImageBackground(BufferedImage srcImage) {
BufferedImage outImage = null;
try {
int oldHeight = srcImage.getHeight();
int oldWidth = srcImage.getWidth();
int destWidth = oldWidth * 2;
int destHeight = oldHeight * 2;
outImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = (Graphics2D) outImage.getGraphics();
// 设置背景颜色
graphics2D.setBackground(Color.WHITE);
graphics2D.clearRect(0, 0, destWidth, destHeight);
// 设置图片居中显示
graphics2D.drawImage(srcImage, (destWidth - oldWidth) / 2, (destHeight - oldHeight) / 2, null);
graphics2D.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(outImage, ConstantUtil.FileType.PNG, os);
byte[] bytes = os.toByteArray();
String string = Base64Utils.encodeToString(bytes);
// log.info(string);
// 调用ocr服务
// sendOcr(string);
} catch (IOException e) {
log.error("对ocr图片操作异常", e);
throw new ServiceException("对ocr图片操作异常");
}
}
Java处理透明图片背景
为了解决OCR技术无法识别透明背景图片的问题,本篇介绍了一种使用Java处理图片背景的方法。通过生成白色底片并将透明图片附在上面,提高了OCR识别率。
724

被折叠的 条评论
为什么被折叠?



