먼저, 이미지 확인 코드를 로컬로 생성하는 방법을 살펴본 다음 웹 페이지에 확인 코드 출력을 작성하여 구현하겠습니다.
먼저 가장 간단한 기능을 살펴 보겠습니다. 구현은 문자열을 이미지로 바꾸고 파일에 작성하는 것입니다.
구현 코드 :
패키지 cn.hncu.img; import java.awt.graphics; import java.awt.image.bufferedimage; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import javax.imageio.imageio; // import javax.imageio.imageio; 간단한 인코딩 및 디코딩을 수행합니다. import org.junit.test; public class imgdemo {// 문자열을 이미지로 바꾸고 파일 @test public void void imgdemo1 ()에 쓰는 방법을 배웁니다. filenotfoundexception, ioexception {bufferedimage img = new bufferedimage (60, 30, bufferedemage.type_int_rgb); // 합성 정수 픽셀의 8 비트 RGB 색상 구성 요소가있는 이미지를 나타냅니다. 그래픽 g = img.getGraphics (); G.DrawString ( "Hello", 10,20); //이 그래픽 컨텍스트의 현재 글꼴과 색상을 사용하여 지정된 문자열로 주어진 텍스트를 그립니다. 가장 왼쪽 문자의 기준은이 그래프 컨텍스트 좌표 시스템의 (x, y) 위치에 있습니다. g.dispose (); //// 스트림의 Close ()와 유사하게 Flush () --- 데이터를 IMG 객체로 플래시합니다. //이 그래프의 컨텍스트와 사용하는 모든 시스템 리소스를 릴리스합니다. Dispose를 호출 한 후 더 이상 그래픽 객체를 사용할 수 없습니다. imageio.write (img, "jpg", new FileOutputStream ( "IMG/A.JPG")); // 주어진 형식을 지원하는 모든 imageWriter를 사용하여 파일에 이미지를 작성하십시오. }}결과:
위는 매우 간단합니다. 우리가 보는 검증 코드는 다음과 같습니다. 좋아, 간섭 선, 배경색, 문자 및 Y 좌표를 추가해 봅시다.
간섭 줄 및 배경색이있는 검증 코드 - 파일에 쓰기
데모 코드 :
패키지 CN.hncu.img; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.image.bufferedimage; import java.io.filenotfoundException; import java.io.fileoutputstream; import java.dateal; import java.date; java.util.random; import javax.imageio.imageio; //이 클래스에는 ImageReader와 ImageWriter를 찾는 데 사용되는 일부가 포함되어 있으며 간단한 인코딩 및 디코딩을 수행하기위한 정적이고 편리한 방법이 포함되어 있습니다. import org.junit.test; public class imgdemo {// 위의 문자열을 우리가 일반적으로 사용하는 검증 코드로 변경 - 배경색 및 간섭 줄이있는 몇 가지 임의 숫자를 생성합니다. int 높이 = 40; int lines = 10; BufferedImage img = 새로운 BufferedImage (너비, 높이, BufferedImage.type_int_rgb); 그래픽 g = img.getGraphics (); // 배경색 G.SetColor (Color.white)를 설정합니다. g.fillRect (0, 0, 너비, 높이); // 배경을 그립니다. // 지정된 사각형을 채우십시오. 그래픽 컨텍스트의 현재 색상으로 사각형을 채우십시오. // 글꼴 G.setfont (새 글꼴 ( "宋体", font.bold, 18))을 설정하십시오. // 랜덤 번호 날짜 d = 새 날짜 (); //system.out.println (d.gettime ()); 랜덤 r = 새로운 랜덤 (d.gettime ()); for (int i = 0; i <4; i ++) {int a = r.nextint (10); // 10 [0, 9] 이내의 정수를 제발 int y = 10+r.nextint (20); // y coordinate color c = new color (r.nextInt (255), r.nextInt (255), R.NextInt (255))와 같이 범위 10 ~ 30의 정수; G. 세트 콜러 (c); G.DrawString ( ""+a, 5+i*너비/4, y); } // (int i = 0; i <lines; i ++) {color c = new color (r.nextInt (255), r.nextInt (255), R.NextInt (255))에 대한 간섭선; G. 세트 콜러 (c); G.DrawLine (R.NextInt (너비), R.NextInt (높이), R.NextInt (너비), R.NextInt (높이)); } g.dispose (); // 스트림의 Close ()와 유사하고 Flush () --- 플래시 데이터를 img 객체 imageio.write로 플래시 데이터 (img, "jpg", new FileoutputStream ( "IMG/B.JPG")으로 드라이브합니다. }}데모 결과 :
마지막으로 회전 및 스케일링 할 수있는 검증 코드를 살펴 보겠습니다. 사진의 로컬 파일에 쓰십시오.
데모 코드 :
패키지 cn.hncu.img; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.graphics2d; import java.awt.geom.affinetransform; import java.awt.image.bufferedimage; java.io.fileoutputStream; import java.io.ioexception; import java.util.date; import java.util.random; import javax.imageio.imageio; // import javax.imageio.imageio; image and imagewriter를 찾고 단순한 인코딩 및 디코딩을 수행하는 몇 가지 정적이고 편리한 방법이 포함되어 있습니다. import org.junit.test; public class imgdemo { @test // public void imgdemo3 ()를 돌릴 수있는 vovid imgdemo3 ()가 filenotfoundexception, ioexception {int width = 80; int 높이 = 40; int lines = 10; BufferedImage img = 새로운 BufferedImage (너비, 높이, BufferedImage.type_int_rgb); Graphics2d G2D = (Graphics2d) img.getGraphics (); g2d.setfont (new font ( "宋体", font.bold, 20)); random r = new random (new date (). gettime ()); // 배경색 g2d.setColor (new color (r.nextInt (255), R.NextInt (255), R.NextInt (255))를 설정합니다. G2D.DrawRect (0, 0, 너비, 높이); // 지정된 사각형의 경계를 그립니다. g2d.setColor (새로운 색 (r.nextInt (255), R.NextInt (255), R.NextInt (255)); g2d.fillRect (0, 0, 너비, 높이); // 지정된 사각형을 채우십시오. for (int i = 0; i <4; i ++) {String str = ""+r.nextint (10); // 회전 처리 AffinetRansform TX = New Affinetransform (); tx.rotate (math.random (), 5+i*15, height-5); // 라디안으로 측정 된 회전 각도, 회전 앵커의 X 좌표 및 회전 앵커의 y 좌표 //tx.scale (0.7+math.random (), 0.7+math.random ()); // x 좌표 방향으로 배수를 스케일링하고, y 좌표 방향 g2d.settransform (tx)의 스케일링 다중; 색 C = 새로운 색상 (R.NextInt (255), R.NextInt (255), R.NextInt (255)); G2D.SetColor (C); G2D.DrawString (str, 2+i*너비/4, 높이 -13); } // (int i = 0; i <lines; i ++) {color c = new color (r.nextInt (255), r.nextInt (255), R.NextInt (255))에 대한 간섭선; G2D.SetColor (C); g2d. drawline (r.nextint (너비), r.nextint (높이), r.nextint (너비), r.nextint (높이)); } g2d.dispose (); imageio.write (img, "jpg", new FileOutputStream ( "IMG/C.JPG")); }}데모 결과 :
이제 우리는 프론트 데스크 이미지 검증 기술을 시연하기 시작합니다.
프론트 데스크 사진 검증 기술
이 프로젝트의 구조 다이어그램 :
index.jsp :
<%@ page language = "java"import = "java.util.*"pageencoding = "utf-8"%> <! doctype html public "-// w3c // dtd html 4.01 전환 // document.getElementById ( "servletimg"); var d = 새로운 날짜 (); var time = d.gettime (); //이 문장이 없으면 다음 문장이 작동하지 않습니다. 브라우저의 캐싱 기술이기 때문에 이미지가 새로 고침되지 않습니다. img.src = "/myhelloweb/servlet/imageservlet?"+시간; // 숫자 뒤에있는 것은 get}를 통해 전달됩니다} </script> </head> <hod> 이것은 내 수동 홈페이지입니다! <br/> <img id = "servletimg"src = "/myhelloweb/servlet/imageservlet"/> <a href = "javaScript : changimg ()"> 불분명 </a> </body> </html>
web.xml :
<? xml version = "1.0"encoding = "utf-8"?> <web-app version = "3.0"xmlns = "http://java.sun.com/xml/xml/ns/javaee"xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance. xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd <cription> 이것은 내 j2ee 구성 요소의 설명 </description> <display-name>이 내 j2ee 구성 요소의 디스플레이 이름 </display-name> <servlet-name> imageservlet </servlet-name> <servlet-class> cn.hncu.img.imageservlet </servlet-mapping> <servlet> imagevlet> imageervlet> <Url-pattern>/servlet/imageservlet </url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> index.jsp </welcome-file> </welcome-file-list> </web-app>
imageservlet.java
패키지 cn.hncu.img; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.image.bufferedimage; import java.io.ioexception; import java.io.printwriter; import java.util.date; java. java.rand; javax.imageio.imageio; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.htttp.htttp.httpervletrequest; import javax.servlet.http.htttp.htttp.htttp.httpletresponse; public ervervlet httervlet httervlet httervlet extended doget (httpservletrequest request, httpservletresponse response) servletexception, ioexception {dopost (요청, 응답); } public void dopost (httpservletRequest 요청, httpservletResponse 응답)는 servletexception, ioexception {// 출력 형식 응답을 클라이언트에게 알려줍니다. int 너비 = 80; int 높이 = 40; int lines = 10; BufferedImage img = 새로운 BufferedImage (너비, 높이, BufferedImage.type_int_rgb); 그래픽 g = img.getGraphics (); // 배경색 G.SetColor (Color.white)를 설정합니다. G.FillRect (0, 0, 너비, 높이); // 글꼴 G.setfont를 설정합니다 (새 글꼴 ( "宋体", font.bold, 20)); // random random r = new random (새 날짜 (). gettime ()); for (int i = 0; i <4; i ++) {int a = r.nextint (10); int y = 10+r.nextint (20); // y coordinate color c = new color (r.nextInt (255), r.nextInt (255), R.NextInt (255)); G. 세트 콜러 (c); G.DrawString ( ""+a, 5+i*너비/4, y); } // (int i = 0; i <lines; i ++) {color c = new color (r.nextInt (255), r.nextInt (255), R.NextInt (255))의 간섭 줄; G. 세트 콜러 (c); G.DrawLine (R.NextInt (너비), R.NextInt (높이), R.NextInt (너비), R.NextInt (높이)); } g.dispose (); // 스트림의 close ()와 유사하고, drive flush () --- img 객체 imageio.write로 플래시 데이터 (img, "jpg", response.getoutputStream ()); }}데모 결과 :
다음은 index.jsp입니다.
이 문장이 사용되는 경우 :
img.src =”/myhelloweb/servlet/imageservlet”;
응답 헤더를 확인할 수 있습니다.
이 문장을 사용하여 응답 헤더를 살펴 보겠습니다.
img.src =”/myhelloweb/servlet/imageservlet?”+시간;
추가 날짜 응답이 있습니다!
시간이 바뀌었기 때문에 클릭 할 때마다 볼 때마다 다시 서버에 요청하고 브라우저의 캐시 때문에 요청을 중단하지 않습니다.
검증 코드는 여기서 끝납니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.