Antes de leer, primero debe comprender SpringMVC y luego mirar la imagen del efecto primero.
Redacción de código
1. PAQUETES RELACIONADOS DE IMPORTA
2. Archivo de configuración
web.xml
<? xml versión = "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" id = "WebApp_id" Version = "3.1"> <Spant-Name> WaterMarkSpringMvc </sipplave-name> <Servlet> <Servlet-name> DispatcherServlet </servlet-name> <ervlet-class> org.springframework.web.servlet.disdispatcherservlet </servlet-class> <itin-param> <amamname> contextciglation </paramconfiglation </paramconfiglation> <Amam-Value> classpath: springmvc.xml </param-value> </it-param> <load-on-startup> 1 </load-on-startup> </ervlet> <ervlet-mapping> <ervlet-name> disipterservlet </servlet-name> <url-patter-patter <velceed-file> index.jsp </Welcome-File> </Welcome-File-List> </web-app>
springmvc.xml
<? xml versión = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" "" "" xmlns: contexte = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemalocation http://www.springframework.org/schema/Beans/spring-Beans.xsd http://www.springframework.org/schema/context http://www.springfframework.org/schema/context/spring-contexsext http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <mvc: default-servlet-handler/> <mvc: annotation-driven/> <contextion-scan Base-Package = "com.wenteryan"> </context: component-scan> <Bean> <Property name = "prefix" value = "/"> </propiedad> <propiedad name = "sufix" value = ". jsp"> </sperty> <propiedad name = "viewclass" value = "org.springframework.web.servlet.view.jstlview id = "Multipresolver"> <Property name = "DefaultEncoding" value = "UTF-8"> </Property> <Property Name = "MaxUploadSize" valor = "10485760000"> </property> <Property name = "MaxInMemorySize" Value = "40960"> </Property> </Beans> </beans>
3. Escribe una acción
Acción de marcar de agua.
paquete com.wenteryan.watermarkspringmvc; import javax.servlet.http.httpsession; import org.springframework.beans.factory.annotation.auTowired; import org.springframework.stereotype.controller; import 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.servlet.modelandsmodeland com.wenteryan.service.markservice; import com.wenteryan.service.uploadservice; @ControllerPublic Class WaterMarkaction {private MarkService MackService; SuboadService privado SubloadService; @RequestMapping (value = "/Watermark", método = requestmethod.post) public ModelAndView Watermark (@RequestParam ("Image") CommonsMultipartFile File, Httpsession Session) lanza la excepción {String uploadPath = "/imágenes"; Cadena realUploadPath = session.getServletContext (). GetRealPath (uploadPath); Cadena imageUrl = uploadService.uploadImage (archivo, uploadPath, realUploadPath); String logoImageUrl = mackService.watermark (archivo, uploadPath, realUploadPath); ModelandView ret = new ModelAndView (); ret.addoBject ("imageUrl", imageUrl); ret.addoBject ("logoImageUrl", logoImageUrl); ret.setViewName ("Watermark"); regresar ret; } @AUtowired public void setMackService (MarkService MackService) {this.mackservice = mackService; } @AUtowired public void setUploadService (uploadService uploadService) {this.uploadService = uploadService; }}4. Escribir clases de servicio
Markservice .Java
paquete com.wenteryan.service; import java.awt.color; import java.awt.font; import java.io.file; import org.springframework.web.multipart.commons.commonsMultipartFile; Markservice de interfaz pública {Public estatic final string_text = "WOreryan"; Public static final String font_name = "Microsoft Yahei"; Public static final int font_size = 120; public static final int font_stype = font.bold; Color final estático público font_color = color.red; Public estática final int x = 10; Public estática final int y = 10; Alfa float estático público = 0.3f; Public String Watermark (el archivo CommonSMultIPartFile, String uploadPath, string realUploadPath); }5. Escribir clases de implementación de interfaz
SubloadService .Java
paquete com.wenteryan.service.impl; import java.io.fileOutputStream; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import org.springframework.stereotype.service; org.springframework.web.multipart.commons.commonsMultipartFile; @ServicePublic UploadService {public String uploadImage (commonsMultipartFile file, string uploadPath, string realuploadpath) {inputStream is = null; OutputStream OS = NULL; try {is = file.getInputStream (); OS = nuevo FileOutputStream (RealuploadPath+"/"+File.getOriginalFileName ()); byte [] buffer = new Byte [1024]; int len = 0; while ((len = is.read (buffer))> 0) {os.write (buffer); }} catch (Exception e) {E.PrintStackTrace (); } finalmente {if (is! = null) {try {is.close (); } Catch (ioException e) {// tODO Auto Generated BLOCK E.PrintStackTRace (); }} if (os! = null) {try {os.close (); } Catch (ioException e) {// tODO Auto Generated BLOCK E.PrintStackTRace (); }} return uploadPath+"/"+file.getOriginalFileName (); }}MarkserviceImpl .java
paquete 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.inputstream; import java.io.outputstream; import javax.imageio.imageio; import org.springframework.stereotype.service; importar org.springframework.web.multipart.commons.commonsmultiPartfile; import.sun.image.codec.comegeG com.sun.image.codec.jpeg.JPEGImageEncoder;import com.wenteryan.service.MarkService;@Servicepublic class MarkServiceImpl implements MarkService { @Override public String watermark(CommonsMultipartFile file, String uploadPath, String realUploadPath) { // TODO Auto-generated method stub String logoFileName = "logo"+file.getOriginalFileName (); OutputStream OS = NULL; intente {image image2 = imageIO.read (file.getInputStream ()); int width = image2.getWidth (nulo); int hight = image2.getheight (nulo); BufferedImage BufferImage = new BufferedImage (ancho, altura, bufferedimage.type_int_rgb); Graphics2d G = BufferImage.CreateGraphics (); G.DrawImage (imagen2, 0, 0, ancho, altura, nulo); G.SetFont (nuevo FONT (FONT_NAME, FONT_STYPE, FONT_SIZE)); G.SetColor (font_color); int width1 = font_size*getTextLength (mark_text); int hight1 = font_size; int widthdiff = width-width1; int hightdiff = altura-aguja1; int x = x; int y = y; if (x> widthdiff) {x = widthdiff; } if (y> altura) {y = altura; } g.setCompositE (alphacomposis.getInstance (alfacomposis.src_atop, alfa)); G.DrawString (mark_text, x, y+font_size); G.Dispose (); OS = nuevo FileOutputStream (RealuploadPath+"/"+logOfileName); JpegimageEncoder en = jpegcodec.createjpegencoder (OS); en.Encode (BufferImage); } catch (Exception e) {E.PrintStackTrace (); } finalmente {if (os! = null) {try {os.close (); } Catch (ioException e) {// tODO Auto Generated BLOCK E.PrintStackTRace (); }} return uploadPath+"/"+logOfileName; } public int getTextLength (string text) {int long = text.length (); for (int i = 0; i <text.length (); i ++) {string s = string.valueOf (text.charat (i)); if (s.getBytes (). longitud> 1) {longitud ++; }} longitud = longitud%2 == 0? Longitud/2: Longitud/2+1; longitud de retorno; }} 6. Escribe una página
index.jsp
<Form Action = "Watermark" Method = "Post" Enctype = "Multipart/Form-Data"> <h2> Seleccione la imagen cargada </h2> <div> <br> <input type = "file" name = "imagen" id = "imagen"/> </div> <br> <br> <button type = "enviar"> iniciar la carga </botin> </div> </form>
Watermark.jsp
<div> <img src = "$ {pageContext.request.contextPath} $ {imageUrl}"/> <img src = "$ {pageContext.request.contextPath} $ {logoiMageUrl}"/> <a href = "$ {pageconteNtext.request.request.contextExtExt}" </div>Resumir
Java tiene un paquete especial de procesamiento de imágenes, que también debería poder implementar la función de marca de agua. Después de verificar la información, descubrí que Java es muy conveniente para implementar marcas de agua. La marca de agua puede ser imágenes o texto. Habrá marcas de agua en la etapa posterior. Si lo necesita en el futuro, puede escribir un código para procesar sus propias imágenes en lotes.
Lo anterior se trata de este artículo, espero que sea útil para todos aprender la programación de Java.