이 기사는 모든 사람을위한 Imitation QQ Verification Code Style 이미지 확인 코드의 Java 버전을 공유합니다. 특정 내용은 다음과 같습니다
특징은 다음과 같습니다 : 사용자 정의 이미지 크기 및 문자 길이, 임의의 배경 색상 및 문자 색상, 임의의 문자 오프셋 각도, 문자 부드러운 가장자리, 간섭 선, 노이즈, 배경 왜곡.
원래 캐릭터를 비틀고 싶었지만 교사가 왜 텍스트를 작성한 후 오류를보고하는지 모르겠습니다. 지금은 해보자. 마스터가 수정하는 데 도움이되기를 바랍니다.
QQ 검증 코드와 비슷한 이유는이 알제리 글꼴 때문입니다. 시스템에 시스템이 없으면 직접 설치해야합니다. 바이두에서 글꼴 이름을 다운로드하고 시스템 글꼴 폴더를 버릴 수 있습니다.
생식 이미지 :
패키지 hh.com.util; import java.io.ioexception; javax.servlet.servletexception import; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; 공개 클래스 인증은 javax.servlet.http.httpservlet을 구현합니다. Public Void Service (httpservletRequest 요청, httpservletResponse Response) servleTexception, ioException {response.setheader ( "Pragma", "no-cache"); Response.SetHeader ( "Cache-Control", "No-Cache"); response.setDateHeader ( "만료", 0); Response.setContentType ( "image/jpeg"); // 임의의 문자열 생성 문자열 verifyCode = verifyCodeUtils.generateVerifyCode (4); // 세션 세션 저장 httpsession 세션 = request.getSession (true); session.setAttribute ( "rand", verifycode.tolowercase ()); // 이미지 생성 int w = 200, h = 80; verifyCodeUtils.outputImage (w, h, response.getOutputStream (), verifyCode); }} verifycodeutils 클래스
패키지 hh.com.util; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.graphics2d; import java.awt.lineargradientpaint; import java.awt.paint; import java.awt.renderinghints; import java.awt.geom.aftinetransform; java.awt.image.bufferedimage; import java.io.file; import java.io.fileoutputStream; import java.io.ioexception; import java.io.outputStream; import java.util.arrays; import java.util.random; import javax.imageio.imageio; 공개 클래스 verifyCodeUtils {// 알제리 글꼴을 사용하십시오. 시스템에 있지 않은 경우 글꼴은 대문자 만 표시하고 1,0, i, o public static final string verify_codes = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"를 제거합니다. 개인 정적 임의 임의 = 새로운 랜덤 (); / *** 시스템 기본 문자 소스를 사용하여 확인 코드를 생성합니다* @Param Verifysize verifize code length* @return*/ public static string generateVeryifyCode (int verifysize, verify_codes); } / *** 지정된 소스를 사용하여 검증 코드를 생성합니다* @Param 검증 코드 길이* @Param 소스 검증 코드 문자 소스* @return* / public static string generateVeryifyCode (int verifysize, String Sources) {if == null || sources.length () == 0) {sources = verify_codes; } int codeslen = sources.length (); random rand = new random (System.CurrentTimeMillis ()); StringBuilder QuerifyCode = new StringBuilder (verifysize); for (int i = 0; i <verifysize; i ++) {verifycode.append (sources.charat (rand.nextint (codeslen-1))); } return equifyCode.ToString (); } / ** * 임의의 검증 코드 파일을 생성하고 검증 코드 값을 반환합니다 * @param w * @param h * @param outputfile * @param verifysize * @return * @throws ioexception * / public static string outputverifyimage (int h, 파일 출력 파일, int verifysize (verifycode) (string verififode); outputImage (w, h, outputfile, verifycode); 반환 verifyCode; } / ** * 임의의 검증 코드 스트림을 출력하고 검증 코드 값을 반환하고 확인 코드 값을 반환합니다 * @param w * @param h * @param os * @param verifysize * @return * @throws ioexception * / public static outputverifyimage (int w, int h, outputstream os, int verifysize) {string verifycode (volififycode); outputImage (w, h, os, verifycode); 반환 verifyCode; } / ** * 지정된 확인 코드 이미지 파일 생성 * @param w * @param h * @param outputfile * @param code * @throws ioexception * / public static void outputimage (int w, int h, file outputfile, 문자열 코드)는 ioexception {if (outputfile == null) {return; } file dir = outputfile.getParentFile (); if (! dir.exists ()) {dir.mkdir (); } try {outputfile.createnewfile (); fileoutputStream fos = 새 FileOutputStream (outputFile); OutputImage (w, h, fos, code); fos.close (); } catch (ioexception e) {Throw e; }} / ** * 출력 지정된 검증 코드 이미지 스트림 * @param w * @param h * @param os * @param code * @throws ioexception * / public static void outputimage (int w, int h, outputstream os, 문자열 코드)는 ioexception {int verifysize = code.length (); bufferedImage image = new bufferedImage (w, h, bufferedimage.type_int_rgb); 랜덤 rand = 새로운 랜덤 (); Graphics2d g2 = image.creategraphics (); G2.SetRenderingHint (renderingHints.Key_antialiasing, renderingHints.Value_antialias_on); 색상 [] 색상 = 새로운 색상 [5]; Color [] Colorspaces = new Color [] {Color.white, Color.Cyan, Color.Gray, Color.light_gray, Color.Magenta, Color.Orange, Color.Pink, Color.Yellow}; float [] fractions = new float [colors.length]; for (int i = 0; i <colors.length; i ++) {colors [i] = colorspaces [rand.nextint (colorspaces.length)]; 분수 [i] = rand.nextfloat (); } arrays.sort (분수); g2.setColor (color.gray); // 테두리 색상 세트 g2.fillRect (0, 0, w, h); 색 C = GetRandColor (200, 250); g2.setColor (c); // 배경색 설정 g2.fillRect (0, 2, w, H-4); // 간섭 행을 그리기 행 random random = new random (); g2.setColor (getRandColor (160, 200)); // 선의 색상 (int i = 0; i <20; i ++) {int x = random.nextInt (w -1); int y = random.nextInt (h -1); int xl = random.nextint (6) + 1; int yl = random.nextint (12) + 1; G2.Drawline (X, Y, X + XL + 40, Y + YL + 20); } // 노이즈 플로트 yawprate = 0.05f 추가; // 노이즈 int int are = (int) (Yawprate * w * h); for (int i = 0; i <area; i ++) {int x = random.nextint (w); int y = random.nextint (h); int rgb = getrandomintcolor (); image.setrgb (x, y, rgb); } 전단 (G2, W, H, C); // 그림을 왜곡하여 g2.setColor (GetRandColor (100, 160)); int fontsize = h-4; font font = new Font ( "알제리안", font.italic, fontsize); g2. 세트 폰트 (font); char [] chars = code.tochararray (); for (int i = 0; i <verifysize; i ++) {affinetransform affine = new affinetransform (); affine.setTorotation (math.pi / 4 * rand.nextDouble () * (rand.nextBoolean ()? 1 : -1), (w / verifysize) * i + fontsize / 2, h / 2); g2. 세트 트랜스 폼 (affine); G2.DrawChars (chars, i, 1, ((W -10)/verifysize) * i + 5, h/2 + fontsize/2-10); } g2.dispose (); imageio.write (image, "jpg", os); } 개인 정적 색상 GetRandColor (int fc, int bc) {if (fc> 255) fc = 255; IF (BC> 255) BC = 255; int r = fc + random.nextint (bc -fc); int g = fc + random.nextint (bc -fc); int b = fc + random.nextint (bc -fc); 새로운 색을 반환합니다 (R, G, B); } private static int getrandomintcolor () {int [] rgb = getrandomrgb (); int color = 0; for (int c : rgb) {color = color << 8; 색상 = 색상 | 기음; } 반환 색상; } private static int [] getRandomrgb () {int [] rgb = new int [3]; for (int i = 0; i <3; i ++) {rgb [i] = random.nextint (255); } return rgb; } private static void 전단 (그래픽 g, int w1, int h1, color color) {shearx (g, w1, h1, color); Sheary (G, W1, H1, Color); } private static void shearx (그래픽 g, int w1, int h1, color color) {int perivice = random.nextInt (2); 부울 경계 갭 = 참; int 프레임 = 1; int phase = random.nextint (2); for (int i = 0; i <h1; i ++) {double d = (double) (double) * math.sin ((double) i / (이중) 기간+(6.2831853071795862d * (double) phase) / (double) 프레임); g.copyarea (0, i, w1, 1, (int) d, 0); if (bordergap) {g.setcolor (color); G.DrawLine ((int) d, i, 0, i); g.Drawline ((int) d + w1, i, w1, i); }}} private static void sheary (그래픽 g, int w1, int h1, color color) {int perivice = random.nextInt (40) + 10; // 50; 부울 경계 갭 = 참; int 프레임 = 20; int phase = 7; for (int i = 0; i <w1; i ++) {double d = (double) (기간 >> 1) * Math.sin ((double) i / (double) merial+(6.2831853071795862d * (double) phase) / (double) 프레임); g.copyarea (i, 0, 1, h1, 0, (int) d); if (bordergap) {g.setcolor (color); G.DrawLine (i, (int) d, i, 0); G.DrawLine (i, (int) d + h1, i, h1); }}} public static void main (String [] args)은 ioexception {file dir = new File ( "f :/verifier"); int w = 200, h = 80; for (int i = 0; i <50; i ++) {문자열 verifycode = generationificecode (4); 파일 = 새 파일 (dir, verifycode + ".jpg"); outputImage (w, h, 파일, verifycode); }}} web.xml 구성 :
<Servlet> <Servlet-name> 인증 </servlet-name> <servlet-comec.hh.com.util.authimage </servlet-class> </servlet-class> <servlet-mapping> <servlet-name> interimage </servlet-name> <url-pattern>/emucimage </url-pattern> </servlet-mapping>
위는이 기사에 관한 것입니다. Java 이미지 확인 코드를 배우도록 영감을주기를 바랍니다.