읽기 전에 먼저 SpringMVC를 이해하고 효과 그림을 먼저보아야합니다.
코드 쓰기
1. 관련 패키지 가져 오기
2. 구성 파일
web.xml
<? xml version = "1.0"encoding = "utf-8"?> <web-app xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xsi : schemalocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd. id = "webapp_id"version = "3.1"> <splay-name> WaterMarkSpringmvc </display-name> <servlet> <servlet-name> dispatcherservlet </servlet-name> org.springframework.web.servlet.dispatcherservlet </servletclass> <param-name> conte-name> conte-name> <Param-value> classPath : SpringMvc.xml </param-value> </init-param> </init-on-startup> 1 </load-on-startup> </servlet-mapping> <servlet-name> dispatcherservlet </servlet-name> <url-pattern>/</url-fattern> <환영----하고--- List> <welcome-file> index.jsp </welcome-file> </welcome-file-list> </web-app>
Springmvc.xml
<? xml 버전 = "1.0"alcoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans"xmlns : xsi = "http://ww.w.w3.org/2001/xmlschema-instance" xmlns : context = "http://www.springframework.org/schema/context"xmlns : mvc = "http://www.springframework.org/schema/mvc"xsi : skemalocation = "http://www.spremframframwork.org/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.spramframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <mvc : default-servlet hander/> <mvc : annotation-driven/> <concentxt : contentip BASE-PACKAGE = "com.wenteryan"> </context : component-scan> <ean> <bean> <property name = "prefix"value = "/"> </property> <property name = "toldix"value = ". jsp"> </property> <property name = "viewclass"value = "org.springframework.weeb.view.view. id = "multipartresolver"> <property name = "defaultencoding"value = "utf-8"> </property> <property name = "maxuploadsize"value = "10485760000"> </property> <property name = "maxinmemorysize"value = "40960"> </beans>
3. 행동을 작성하십시오
watermarkaction .Action
패키지 com.wenteryan.watermarkspringmvc; import javax.servlet.http.httpsession; import org.springframework.beans.beans.annotation.autowired; import org.springframework.stereotyp.controll.controll.controll.controller; import org.springframework.westmapt org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.multipart.commons.commonsmultipartfile; import org.springframework.web.servlet.web.serv.web.servlet.web com.wenteryan.service.markservice; import com.wenteryan.service.uploadservice; @controllerpublic class watermarkaction {private markservice mackservice; 개인 업로드 서비스 업로드 서비스; @requestmapping (value = "/watermark", method = requestmethod.post) public modelandview watermark (@requestparam ( "image") commonsmultipartfile 파일, httpsession 세션) 예외 {string ubloadpath = "/images"; 문자열 realuploadpath = session.getServletContext (). getRealPath (uploadPath); String imageUrl = uploadService.uploadimage (파일, UploadPath, RealUploadPath); 문자열 logoImageUrl = mackService.WaterMark (파일, UPLOADPATH, RealUPLOADPATH); ModelAndView ret = 새로운 ModelAndView (); ret.addoBject ( "imageUrl", imageUrl); ret.addoBject ( "logoImageUrl", logoImageUrl); ret.setViewName ( "WaterMark"); Ret Ret; } @autowired public void setMackService (markservice mackservice) {this.mackservice = mackservice; } @autowized public void setuploadService (UploadService UploadService) {this.uploadservice = uploadservice; }}4. 서비스 수업을 작성하십시오
Markservice .java
package com.wenteryan.service; import java.awt.color; import java.awt.font; import java.io.file; import org.sprameframework.web.multipart.commons.commonsmultipartfile; public static markservice {public static final mark_text = "genteryan"; 공개 정적 최종 문자열 font_name = "Microsoft Yahei"; 공개 정적 최종 int font_size = 120; 공개 정적 최종 int font_stype = font.bold; 공개 정적 최종 색상 font_color = color.red; 공개 정적 최종 int x = 10; 공개 정적 최종 int y = 10; 공개 정적 플로트 알파 = 0.3f; public String WaterMark (CommonSmultipartFile 파일, String UploadPath, String RealUploadPath); }5. 인터페이스 구현 클래스를 작성하십시오
업로드 서비스 .java
패키지 com.wenteryan.service.impl; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputStream; import java.io.outputstream; import org.springframework.stereotyp.service; import org.springframework.web.multipart.commons.commonsmultipartfile; @servicepublic class uploadservice {public string uploadimage (commonsmultipartfile 파일, 문자열 업로드 포트, 문자열 realuploadpath) {inputstream is = null; OutputStream os = null; try {is = file.getInputStream (); os = new FileOutputStream (realUploadPath+"/"+file.getoriginalFilename ()); 바이트 [] 버퍼 = 새로운 바이트 [1024]; int len = 0; while ((len = is.read (buffer))> 0) {os.write (buffer); }} catch (예외 e) {e.printstacktrace (); } 마침내 {if (is! = null) {try {is.close (); } catch (ioexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} if (os! = null) {try {os.close (); } catch (ioexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} return uploadpath+"/"+file.getoriginalFilename (); }}Markserviceimpl .java
package com.wenteryan.service.impl; import java.awt.alphacomposite; import java.awt.font; import java.awt.graphics2d; import java.awt.image; import java.awt.image.bufferedimage; import java.io.file; java.io.fileoutputstrem; java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import javax.imageio.imageio; import org.spramework.stereotyp.service; import org.springframework.web.multipart.commons.commonsmultipartfile; com.sun.image.codec.jpeg.jpegcodec; import com.sun.image.codec.jpeg.jpegimageencoder; import com.wenteryan.service.markservice; @servicepublic class Markserviceimpl emplements markservice {@overridate watermark (componsmmonsmmonsmmondmentmultipartfile). realuploadpath) {// todo 자동 생성 메소드 스터브 문자열 logofilename = "logo"+file.getoriginalFilename (); OutputStream os = null; {image image2 = imageio.read (file.getInputStream ()); int width = image2.getWidth (null); int height = image2.getheight (null); BufferedImage bufferimage = 새로운 bufferedImage (너비, 높이, bufferedImage.type_int_rgb); 그래픽 2d g = bufferimage.creategraphics (); g.DrawImage (image2, 0, 0, 너비, 높이, 널); g.setfont (new font (font_name, font_stype, font_size)); g.setcolor (font_color); int width1 = font_size*getTextLength (mark_text); int height1 = font_size; int widthdiff = width-width1; int highdiff = height-height1; int x = x; int y = y; if (x> widthdiff) {x = widthdiff; } if (y> highdiff) {y = highdiff; } g.setComposite (alphacomposite.getInstance (alphacomposite.src_atop, alpha)); G.DrawString (Mark_Text, X, y+font_size); g.dispose (); os = new FileOutputStream (realUploadPath+"/"+logofilename); JPEGIMAGEENCODER EN = JPEGCODEC.CREATEJPEGENCODER (OS); en.encode (bufferimage); } catch (예외 e) {e.printstacktrace (); } 마침내 {if (os! = null) {try {os.close (); } catch (ioexception e) {// todo 자동 생성 캐치 블록 e.printstacktrace (); }} retury uploadpath+"/"+logofilename; } public int getTextLength (문자열 텍스트) {int longth = text.length (); for (int i = 0; i <text.length (); i ++) {string s = string.valueof (text.charat (i)); if (s.getBytes (). 길이> 1) {길이 ++; }} 길이 = 길이%2 == 0? 길이/2 : 길이/2+1; 반환 길이; }} 6. 페이지를 작성하십시오
index.jsp
<form action = "watermark"method = "post"enctype = "multipart/form-data"> <h2> 업로드 된 이미지를 선택하십시오 </h2> <div> <br> <input type = "file"name = "image"id = "id ="ID "/> <bl> <button type ="button "> </div> </div> </div> </div> </div> </div> </div> </div> </div>
watermark.jsp
<div> <img src = "$ {pagecontext.request.contextpath} $ {imageUrl}"/> <img src = "$ {pagecontext.request.contextpath} $ {logoImageUrl}"/> <a href = "$ {pagecontext.context.context.context.context. </div>요약
Java에는 특수 이미지 처리 패키지가 있으며 Watermark 기능도 구현할 수 있습니다. 정보를 확인한 후 Java가 워터 마크를 구현하기에 매우 편리하다는 것을 알았습니다. 워터 마크는 그림이나 텍스트 일 수 있습니다. 후반에는 워터 마크가 있습니다. 앞으로 필요한 경우 자신의 사진을 배치로 처리하기위한 코드를 작성할 수 있습니다.
위의 내용은이 기사에 관한 모든 것입니다. 모든 사람들이 Java 프로그래밍을 배우는 것이 도움이되기를 바랍니다.