使用Springboot3.x結合美學與功能的設計實現藝術風格驗證碼
這個專題深入淺出地探討了各類驗證碼的生成和在Springboot3.x中的實踐,從基礎的滑動、點選、算術運算驗證碼到創新的藝術風格、水印、二維碼驗證碼,適合所有Java開發者閱讀。在這個專題中,不僅可以學習到技術實踐,更能領略到驗證碼的美學魅力。讓我們一起探索驗證碼的無盡可能性。
什么是藝術風格驗證碼
驗證碼,全名叫做 Completely Automated Public Turing Test to tell Computers and Humans Apart(全自動區分計算機和人類的圖靈測試)。其主要目標是阻止機器自動進行某些操作,例如注冊用戶、提交表單等。
而藝術風格驗證碼,可以看作是驗證碼的一種創新形式,它將數字藝術融入到這項安全措施中。藝術風格驗證碼的外觀吸引人,增強了用戶體驗,同時也提高了驗證碼的安全等級。因為這種驗證碼在視覺上的差異性和復雜性使得對驗證碼的自動識別變得更加困難,提高了安全性。
所謂藝術風格,包括但不限于各種視覺藝術形式,例如流行藝術、抽象藝術、最小主義藝術等。驗證碼的顏色、形狀、過濾效果等都可以根據特定的藝術風格來設計。例如,我們可能將驗證碼中的數字或字母渲染成流行藝術風格,或者給驗證碼背景添加抽象藝術元素。
藝術風格驗證碼的運行機制
藝術風格驗證碼的運行機制同普通驗證碼非常相似,但是它引入了額外的步驟來添加藝術效果。以下是其一般的工作流程:
- 生成一組隨機的字母或數字作為驗證碼的原始文本。
- 為每個字符生成一個基本的圖形表示,通常是在圖片中為每個字符分配一個特定的位置并進行繪制。
- 對生成的圖片應用一系列藝術效果。這些效果可以包含顏色變換、模糊處理、波紋效果、旋轉變形等。
- 將完成藝術效果處理的驗證碼圖片展示給用戶,并存儲原始的驗證碼文本以供用戶提交后進行比對驗證。
下面通過一個基本的例子演示在Java環境下如何通過代碼實現這個流程:
public void generateArtisticVerificationCode() {
String verificationCode = RandomStringUtils.randomAlphanumeric(5); // 生成原始驗證碼文本
BufferedImage image = new BufferedImage(100, 40, BufferedImage.TYPE_INT_ARGB); // 創建圖片對象
Graphics graphics = image.getGraphics(); // 獲取畫布
graphics.setFont(new Font("TimesRoman", Font.BOLD, 20)); // 設定字體
graphics.setColor(Color.BLACK); // 設定顏色
for (int i = 0; i < verificationCode.length(); i++) {
graphics.drawString(verificationCode.charAt(i) + "", 10 + i * 16, 28); // 在畫布上繪制每個字符
}
applyArtisticEffects(image); // 應用藝術效果
// 將圖片展示給用戶,同時保留原始驗證碼文本以供后續驗證
}
// 示例藝術效果應用函數
public void applyArtisticEffects(BufferedImage image) {
// 這個函數會對圖片應用各種藝術效果,包括但不限于顏色變換、模糊處理、波紋效果等
// 具體實現取決于你希望生成驗證碼的藝術風格
}
在生成藝術風格驗證碼的過程中,我們首先生成了原始的驗證碼文本,并為每一個字符在圖片上繪制了基本的圖形表示。然后我們對圖片應用了藝術效果處理。最后我們將處理過的驗證碼圖片展示給用戶,并保留原始的驗證碼文本,這樣用戶在提交時我們就可以對提交的驗證碼和原始的進行比對。
技術實現:在Springboot3.x中如何生成藝術風格驗證碼
在Springboot3.x中生成藝術風格驗證碼,我們主要分為以下幾步:
- 創建驗證碼Controller
- 實現一個驗證碼服務
- 實現一個藝術效果應用服務
以下是詳細的實現步驟和示例代碼:
創建驗證碼Controller
首先,我們需要創建一個Controller用于處理驗證碼相關的請求。這個Controller將和我們的驗證碼服務進行交互,接收用戶請求并返回生成的驗證碼。
@RestController
public class VerificationCodeController {
@Autowired
private VerificationCodeService verificationCodeService;
@RequestMapping("/verificationCode")
public void getVerificationCode(HttpServletResponse response, HttpSession session) {
BufferedImage image = verificationCodeService.createVerificationImage();
session.setAttribute("VERIFICATION_CODE", verificationCodeService.getVerificationCode());
ImageIO.write(image, "jpeg", response.getOutputStream());
}
}
在上述代碼中,我們創建了一個名為VerificationCodeController的Controller。我們注入了VerificationCodeService用于生成驗證碼。我們定義了一個路由/verificationCode,用于接收HTTP請求并返回生成的驗證碼圖片。
實現驗證碼服務
驗證碼服務的責任是生成原始的驗證碼文本和驗證碼圖片。
@Service
public class VerificationCodeService {
@Autowired
private ArtisticEffectService artisticEffectService;
private String verificationCode;
public BufferedImage createVerificationImage() {
verificationCode = RandomStringUtils.randomAlphanumeric(5);
BufferedImage image = new BufferedImage(100, 40, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = image.getGraphics();
graphics.setFont(new Font("TimesRoman", Font.BOLD, 20));
graphics.setColor(Color.BLACK);
for (int i = 0; i < verificationCode.length(); i++) {
graphics.drawString(verificationCode.charAt(i) + "", 10 + i * 16, 28);
}
artisticEffectService.applyArtisticEffects(image);
return image;
}
public String getVerificationCode() {
return verificationCode;
}
}
實現藝術效果應用服務
藝術效果應用服務用于對驗證碼圖片應用藝術效果。
@Service
public class import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import org.springframework.stereotype.Service;
@Service
public class ArtisticEffectService {
public void applyArtisticEffects(BufferedImage image) {
Graphics2D graphics = (Graphics2D) image.getGraphics();
// 添加線性漸變效果
GradientPaint paint = new GradientPaint(0, 0, Color.BLUE, image.getWidth(), 0, Color.RED);
graphics.setPaint(paint);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.5f));
graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
// 添加模糊效果
float ninth = 1.0f/9.0f;
float[] blurKernel = {
ninth, ninth, ninth,
ninth, ninth, ninth,
ninth, ninth, ninth
};
ConvolveOp op = new ConvolveOp(new Kernel(3, 3, blurKernel));
BufferedImage blurredImage = op.filter(image, null);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.drawImage(blurredImage, 0, 0, null);
}
}
在上述代碼中,我們首先使用GradientPaint創建了一個從左邊的藍色向右邊的紅色逐漸變化的線性漸變效果,然后使用AlphaComposite將這個漸變效果和原來的圖像合成在一起。
接著,我們創建了一個模糊核(blur kernel)并使用ConvolveOp將模糊效果應用到現有的圖像上。
實戰應用:藝術風格驗證碼的應用示例
在接下來的示例中,我們將實現一個功能更為完善的Spring Boot應用程序,該程序包含一個Web頁面,用戶可以從該頁面請求新的藝術風格驗證碼,并提交輸入以進行驗證。
以下是我們的應用程序的主要組件:
- 驗證碼生成服務
- Web控制器
- Vue.js前端應用
驗證碼生成服務
我們先前已經實現了一個驗證碼服務和藝術效果服務,現在我們可以將其集成到我們的Spring Boot應用中。
@Service
public class VerificationCodeService {
private String verificationCode;
@Autowired
private ArtisticEffectService artisticEffectService;
public String createVerificationCode() {
verificationCode = RandomStringUtils.randomAlphanumeric(5);
return verificationCode;
}
public BufferedImage createVerificationImage() {
String code = createVerificationCode();
BufferedImage image = new BufferedImage(100, 40, BufferedImage.TYPE_INT_ARGB);
Graphics graphics = image.getGraphics();
graphics.setFont(new Font("Arial", Font.BOLD, 24));
graphics.setColor(Color.BLACK);
for (int i = 0; i < verificationCode.length(); i++) {
graphics.drawString(code.charAt(i) + "", 10 + i * 16, 32);
}
artisticEffectService.applyArtisticEffects(image);
return image;
}
public boolean verifyCode(String userInput) {
return userInput.equals(verificationCode);
}
}
在這里,我們將為這個方法實現傾斜角度變化和圖片抖動這兩種常見的藝術樣式。
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.Random;
import org.springframework.stereotype.Service;
@Service
public class ArtisticEffectService {
// 旋轉給定的圖像
public BufferedImage rotateImage(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
BufferedImage rotatedImage = new BufferedImage(width, height, image.getType());
Graphics2D graphics2D = rotatedImage.createGraphics();
double theta = Math.toRadians(new Random().nextInt(40) - 20); // 在-20到20度之間隨機旋轉
graphics2D.rotate(theta, width / 2, height / 2);
graphics2D.drawImage(image, 0, 0, null);
graphics2D.dispose();
return rotatedImage;
}
// 對給定的字符串應用底噪音和干擾線
public BufferedImage applyArtisticEffects(BufferedImage image) {
int width = image.getWidth();
int height = image.getHeight();
Random random = new Random();
// 底部噪聲
for (int i = 0; i < 30; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int rgb = getRandomRgb();
image.setRGB(x, y, rgb);
}
// 干擾線
Graphics2D graphics2D = image.createGraphics();
for (int i = 0; i < 5; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(width);
int yl = random.nextInt(height);
graphics2D.setColor(new Color(getRandomRgb()));
graphics2D.drawLine(x, y, x + xl, y + yl);
}
graphics2D.dispose();
return rotateImage(image);
}
// 生成隨機的RGB顏色
private int getRandomRgb() {
Random random = new Random();
int red = random.nextInt(256);
int green = random.nextInt(256);
int blue = random.nextInt(256);
return (red << 16) | (green << 8) | blue;
}
}
在上述代碼中,我們首先為驗證碼圖片添加底部噪聲和干擾線,然后隨機地旋轉圖片角度。這將確保每一次生成的驗證碼圖片都是獨一無二的,并能有效地防止機器人自動識別。
Web控制器
接下來,我們需要創建一個Web控制器來處理用戶的HTTP請求。我們將創建兩個路由,一個用于生成和獲取驗證碼,另一個用于驗證用戶輸入的驗證碼。
@RestController
@RequestMapping("/api")
public class VerificationCodeController {
@Autowired
private VerificationCodeService verificationCodeService;
@GetMapping("/verificationCode")
public ResponseEntity<byte[]> getVerificationCode() throws IOException {
BufferedImage image = verificationCodeService.createVerificationImage();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(image, "png", bos);
byte[] imageBytes = bos.toByteArray();
return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(imageBytes);
}
@PostMapping("/verify")
public ResponseEntity<Boolean> verifyCode(@RequestBody String userInput) {
boolean isCorrect = verificationCodeService.verifyCode(userInput);
return ResponseEntity.ok(isCorrect);
}
}
在上述代碼中,getVerificationCode方法處理GET請求并返回新的驗證碼圖像。我們將返回的驗證碼圖像存儲為一個字節數組,以便將其作為HTTP響應的一部分發送回客戶端。
verifyCode方法接收用戶的驗證碼輸入,并通過與存儲在服務端的驗證碼進行比較來驗證輸入是否正確。
前端應用
綜合以上所述,我們已經成功地在后端實現驗證碼的生成和驗證。現在,我們需要一個前端用戶界面來顯示驗證碼,并提供一個輸入框讓用戶輸入驗證碼。
在這個例子中,我們將使用Vue.js來實現前端應用。前端應用將包含一個圖像組件用來顯示驗證碼,一個文本框用于用戶輸入,以及一個按鈕用于提交用戶輸入。
<template>
<div id="app">
<img :src="`data:image/png;base64,${captchaImage}`" @click="refreshCaptcha" />
<input v-model="userInput" type="text" placeholder="Enter the captcha" />
<button @click="verifyCaptcha">Submit</button>
</div>
</template>
<script>
export default {
data() {
return {
captchaImage: '',
userInput: ''
}
},
methods: {
refreshCaptcha() {
axios.get('/api/verificationCode', { responseType: 'arraybuffer' })
.then(response => {
let base64 = btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
this.captchaImage = base64;
});
},
verifyCaptcha() {
axios.post('/api/verify', this.userInput)
.then(response => {
if (response.data) {
alert("The captcha is correct.");
} else {
alert("The captcha is incorrect.");
this.refreshCaptcha();
}
});
}
},
mounted() {
this.refreshCaptcha();
}
}
</script>
在上述代碼中,我們使用Vue.js提供的兩個生命周期鉤子:methods中的refreshCaptcha方法獲取新的驗證碼,mounted中的refreshCaptcha在頁面加載時調用。在驗證碼提交后,一個警告會告訴用戶提交的驗證碼是否正確。如果驗證碼不正確,將會刷新新的驗證碼。
通過這種方式,我們成功創建了一個藝術風格驗證碼的完整應用示例,包含后端的驗證碼生成、前端的驗證碼展示和用戶輸入驗證等完整流程。
本文主要介紹了如何實現一個藝術風格的驗證碼系統,過程包含生成驗證碼、應用藝術效果、及其在前后端的實現。驗證碼生成部分,通過Java的RandomStringUtils工具生成隨機字符串作為驗證碼。藝術效果應用部分,實現了噪點擾動和模糊效果,來增強驗證碼的安全性同時賦予其獨特的藝術風格。在后端,我們創建了一個Spring Boot應用,實現了驗證碼的生成并返回給前端;在前端部分,我們使用Vue.js創建了一個用戶界面單元,用戶可以進行驗證碼的獲取與輸入驗證。這樣的系統結構使得驗證碼的生成及驗證過程更為靈活與高效。