java將圖片轉(zhuǎn)為base64返回給前端
本文實(shí)例為大家分享了java將圖片轉(zhuǎn)為base64返回給前端的具體代碼,供大家參考,具體內(nèi)容如下
一、controller端代碼
@RequestMapping(value = "/captcha") public void imagecode(HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject object = new JSONObject(); CaptchaGenerator vcg = new CaptchaGenerator(); String vcode = vcg.generatorVCode(); BufferedImage vcodeImage = vcg.generatorVCodeImage(vcode, true); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); response.addHeader("code", vcode.toLowerCase()); try { ImageIO.write(vcodeImage, "png", outputStream); BASE64Encoder encoder = new BASE64Encoder(); String base64 = encoder.encodeBuffer(outputStream.toByteArray()).trim(); base64 = base64.replaceAll("\n", "").replaceAll("\r", ""); object.put("code", "data:image/jpg;base64," + base64); response.getWriter().write(object.toString()); } catch (IOException e) { response.getWriter().write(""); } finally { if (outputStream != null) { outputStream.flush(); outputStream.close(); response.getWriter().close(); } } }
二、生成驗(yàn)證碼的代碼
(從某博客拷過來直接用的)
package com.kinth.security.web.util; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.Random; /** * 驗(yàn)證碼生成器 * * */ public class CaptchaGenerator { /** * 驗(yàn)證碼來源 */ final private char[] code = { '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; /** * 字體 */ final private String[] fontNames = new String[]{ "黑體", "宋體", "Courier", "Arial", "Verdana", "Times", "Tahoma", "Georgia"}; /** * 字體樣式 */ final private int[] fontStyles = new int[]{ Font.BOLD, Font.ITALIC|Font.BOLD }; /** * 驗(yàn)證碼長度 * 默認(rèn)4個字符 */ private int vcodeLen = 4; /** * 驗(yàn)證碼圖片字體大小 * 默認(rèn)17 */ private int fontsize = 21; /** * 驗(yàn)證碼圖片寬度 */ private int width = (fontsize+1)*vcodeLen+10; /** * 驗(yàn)證碼圖片高度 */ private int height = fontsize+12; /** * 干擾線條數(shù) * 默認(rèn)3條 */ private int disturbline = 3; public CaptchaGenerator(){} /** * 指定驗(yàn)證碼長度 * @param vcodeLen 驗(yàn)證碼長度 */ public CaptchaGenerator(int vcodeLen) { this.vcodeLen = vcodeLen; this.width = (fontsize+1)*vcodeLen+10; } /** * 生成驗(yàn)證碼圖片 * @param vcode 要畫的驗(yàn)證碼 * @param drawline 是否畫干擾線 * @return */ public BufferedImage generatorVCodeImage(String vcode, boolean drawline){ //創(chuàng)建驗(yàn)證碼圖片 BufferedImage vcodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = vcodeImage.getGraphics(); //填充背景色 g.setColor(new Color(246, 240, 250)); g.fillRect(0, 0, width, height); if(drawline){ drawDisturbLine(g); } //用于生成偽隨機(jī)數(shù) Random ran = new Random(); //在圖片上畫驗(yàn)證碼 for(int i = 0;i < vcode.length();i++){ //設(shè)置字體 g.setFont(new Font(fontNames[ran.nextInt(fontNames.length)], fontStyles[ran.nextInt(fontStyles.length)], fontsize)); //隨機(jī)生成顏色 g.setColor(getRandomColor()); //畫驗(yàn)證碼 g.drawString(vcode.charAt(i)+"", i*fontsize+10, fontsize+5); } //釋放此圖形的上下文以及它使用的所有系統(tǒng)資源 g.dispose(); return vcodeImage; } /** * 獲得旋轉(zhuǎn)字體的驗(yàn)證碼圖片 * @param vcode * @param drawline 是否畫干擾線 * @return */ public BufferedImage generatorRotateVCodeImage(String vcode, boolean drawline){ //創(chuàng)建驗(yàn)證碼圖片 BufferedImage rotateVcodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = rotateVcodeImage.createGraphics(); //填充背景色 g2d.setColor(new Color(246, 240, 250)); g2d.fillRect(0, 0, width, height); if(drawline){ drawDisturbLine(g2d); } //在圖片上畫驗(yàn)證碼 for(int i = 0;i < vcode.length();i++){ BufferedImage rotateImage = getRotateImage(vcode.charAt(i)); g2d.drawImage(rotateImage, null, (int) (this.height * 0.7) * i, 0); } g2d.dispose(); return rotateVcodeImage; } /** * 生成驗(yàn)證碼 * @return 驗(yàn)證碼 */ public String generatorVCode(){ int len = code.length; Random ran = new Random(); StringBuffer sb = new StringBuffer(); for(int i = 0;i < vcodeLen;i++){ int index = ran.nextInt(len); sb.append(code[index]); } return sb.toString(); } /** * 為驗(yàn)證碼圖片畫一些干擾線 * @param g */ private void drawDisturbLine(Graphics g){ Random ran = new Random(); for(int i = 0;i < disturbline;i++){ int x1 = ran.nextInt(width); int y1 = ran.nextInt(height); int x2 = ran.nextInt(width); int y2 = ran.nextInt(height); g.setColor(getRandomColor()); //畫干擾線 g.drawLine(x1, y1, x2, y2); } } /** * 獲取一張旋轉(zhuǎn)的圖片 * @param c 要畫的字符 * @return */ private BufferedImage getRotateImage(char c){ BufferedImage rotateImage = new BufferedImage(height, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = rotateImage.createGraphics(); //設(shè)置透明度為0 g2d.setColor(new Color(255, 255, 255, 0)); g2d.fillRect(0, 0, height, height); Random ran = new Random(); g2d.setFont(new Font(fontNames[ran.nextInt(fontNames.length)], fontStyles[ran.nextInt(fontStyles.length)], fontsize)); g2d.setColor(getRandomColor()); double theta = getTheta(); //旋轉(zhuǎn)圖片 g2d.rotate(theta, height/2, height/2); g2d.drawString(Character.toString(c), (height-fontsize)/2, fontsize+5); g2d.dispose(); return rotateImage; } /** * @return 返回一個隨機(jī)顏色 */ private Color getRandomColor(){ Random ran = new Random(); return new Color(ran.nextInt(220), ran.nextInt(220), ran.nextInt(220)); } /** * @return 角度 */ private double getTheta(){ return ((int) (Math.random()*1000) % 2 == 0 ? -1 : 1)*Math.random(); } /** * @return 驗(yàn)證碼字符個數(shù) */ public int getVcodeLen() { return vcodeLen; } /** * 設(shè)置驗(yàn)證碼字符個數(shù) * @param vcodeLen */ public void setVcodeLen(int vcodeLen) { this.width = (fontsize+3)*vcodeLen+10; this.vcodeLen = vcodeLen; } /** * @return 字體大小 */ public int getFontsize() { return fontsize; } /** * 設(shè)置字體大小 * @param fontsize */ public void setFontsize(int fontsize) { this.width = (fontsize+3)*vcodeLen+10; this.height = fontsize+15; this.fontsize = fontsize; } /** * @return 圖片寬度 */ public int getWidth() { return width; } /** * 設(shè)置圖片寬度 * @param width */ public void setWidth(int width) { this.width = width; } /** * @return 圖片高度 */ public int getHeight() { return height; } /** * 設(shè)置圖片高度 * @param height */ public void setHeight(int height) { this.height = height; } /** * @return 干擾線條數(shù) */ public int getDisturbline() { return disturbline; } /** * 設(shè)置干擾線條數(shù) * @param disturbline */ public void setDisturbline(int disturbline) { this.disturbline = disturbline; } }
三、前端顯示
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <script src="../static/model/js/jquery-1.11.2.min.js"></script> </head> <body> <img id="randomImage" src="" /> <script type="text/javascript"> $(function() { refreshimg(); }) function refreshimg() { $.ajax({ type : "POST", dataType : "json", url : "../article/captcha", success : function(data) { console.log('base64=' + data.codePic); $('#randomImage').attr('src', data.code); }, error : function() { } }); $("#randomImage").click(refreshimg) } </script> </body> </html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- java實(shí)現(xiàn)圖片轉(zhuǎn)base64字符串 java實(shí)現(xiàn)base64字符串轉(zhuǎn)圖片
- Java實(shí)現(xiàn)圖片與Base64編碼互轉(zhuǎn)
- Java處理圖片實(shí)現(xiàn)base64編碼轉(zhuǎn)換
- Java 8實(shí)現(xiàn)圖片BASE64編解碼
- Java中將base64編碼字符串轉(zhuǎn)換為圖片的代碼
- Java 處理圖片與base64 編碼的相互轉(zhuǎn)換的示例
- java實(shí)現(xiàn)后臺處理base64圖片還原為文件
- Java基于Base64實(shí)現(xiàn)編碼解碼圖片文件
- Java實(shí)現(xiàn)圖片轉(zhuǎn)base64完整代碼示例
相關(guān)文章
Springboot vue導(dǎo)出功能實(shí)現(xiàn)代碼
這篇文章主要介紹了Springboot vue導(dǎo)出功能實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04mybatis-plus之如何根據(jù)數(shù)據(jù)庫主鍵定義字段類型
這篇文章主要介紹了mybatis-plus之如何根據(jù)數(shù)據(jù)庫主鍵定義字段類型問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07SpringBoot使用Redisson實(shí)現(xiàn)延遲執(zhí)行的完整示例
這篇文章主要介紹了SpringBoot使用Redisson實(shí)現(xiàn)延遲執(zhí)行的完整示例,文中通過代碼示例講解的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-06-06java中使用雪花算法(Snowflake)為分布式系統(tǒng)生成全局唯一ID代碼示例
Java雪花算法是一種用于生成唯一ID的算法,它可以在分布式系統(tǒng)中生成全局唯一的ID,這篇文章主要給大家介紹了關(guān)于java中使用雪花算法(Snowflake)為分布式系統(tǒng)生成全局唯一ID的相關(guān)資料,需要的朋友可以參考下2024-07-07SpringBoot 集成JUnit5的詳細(xì)操作過程
JUnit5是最新的Java單元測試框架,提供了靈活的測試支持,它由JUnit Platform、JUnit Jupiter和JUnit Vintage組成,支持不同環(huán)境下的測試運(yùn)行,SpringBoot從2.2版本開始默認(rèn)支持JUnit5,本文介紹了SpringBoot 集成JUnit5的相關(guān)知識,感興趣的朋友跟隨小編一起看看吧2024-10-10Springboot任務(wù)之異步任務(wù)的使用詳解
今天學(xué)習(xí)了一個新技能SpringBoot實(shí)現(xiàn)異步任務(wù),所以特地整理了本篇文章,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06