java实现图片滑动验证码
下载资源地址:https://download.csdn.net/download/shiqiangwen/11164170
首先感谢
https://blog.csdn.net/jiabeis/article/details/86477706、https://download.csdn.net/download/lycapzy/10831028 这两位作者,我是在这个基础之上做的修改。
在文章开始和末尾,附源代码下载地址。
最终的效果如下:
注:DataMap是自己封装的,extends自HashMap。凡是用到DataMap的可以替换成HashMap(没试过,感觉应该可以)。
主要代码如下
1.VerifyImageUtil.java 滑动验证码核心工具类
/**
* @description 图形验证码生成工具类
* @author SQW
* @date 2019年4月30日
*/
public class VerifyImageUtil {
private static int ORI_WIDTH = 280; //源文件宽度
private static int ORI_HEIGHT = 171; //源文件高度
private static int WIDTH; //模板图宽度
private static int HEIGHT; //模板图高度
/**
* @description 根据模板切图
* @author SQW
* @date 2019年4月30日
*/
public static Map<String, byte[]> pictureTemplatesCut(File templateFile, File targetFile, String templateType, String targetType,int X,int Y) throws Exception {
Map<String, byte[]> pictureMap = new HashMap<>();
// 文件类型
String templateFiletype = templateType;
String oriFiletype = targetType;
if (StringUtils.isEmpty(templateFiletype) || StringUtils.isEmpty(oriFiletype)) {
throw new RuntimeException("file type is empty");
}
// 源文件流
File Orifile = targetFile;
InputStream oriis = new FileInputStream(Orifile);
// 模板图
BufferedImage imageTemplate = ImageIO.read(templateFile);
WIDTH = imageTemplate.getWidth();
HEIGHT = imageTemplate.getHeight();
//generateCutoutCoordinates();
// 最终图像
BufferedImage newImage = new BufferedImage(WIDTH, HEIGHT, imageTemplate.getType());
Graphics2D graphics = newImage.createGraphics();
graphics.setBackground(Color.white);
//graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.3f));
int bold = 5;
// 获取感兴趣的目标区域
BufferedImage targetImageNoDeal = getTargetArea(X, Y, WIDTH, HEIGHT, oriis, oriFiletype);
// 根据模板图片抠图
newImage = DealCutPictureByTemplate(targetImageNoDeal, imageTemplate, newImage);
// 设置“抗锯齿”的属性
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setStroke(new BasicStroke(bold, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
graphics.drawImage(newImage, 0, 0, null);
graphics.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();//新建流。
ImageIO.write(newImage, "png", os);//利用ImageIO类提供的write方法,将bi以png图片的数据模式写入流。
byte[] newImages = os.toByteArray();
pictureMap.put("newImage", newImages);
// 源图生成遮罩
BufferedImage oriImage = ImageIO.read(Orifile);
byte[] oriCopyImages = DealOriPictureByTemplate(oriImage, imageTemplate, X, Y);
pictureMap.put("oriCopyImage", oriCopyImages);
return pictureMap;
}
/**
* 抠图后原图生成
*
* @param oriImage
* @param templateImage
* @param x
* @param y
* @return
* @throws Exception
*/
private static byte[] DealOriPictureByTemplate(BufferedImage oriImage, BufferedImage templateImage, int x,
int y) throws Exception {
// 源文件备份图像矩阵 支持alpha通道的rgb图像
BufferedImage ori_copy_