Avant de lire, vous devez d'abord comprendre SpringMVC, puis regarder l'image de l'effet d'abord.
Écriture de code
1. Importer des packages connexes
2. Fichier de configuration
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. id = "webApp_id" version = "3.1"> <splay-name> watermarkspringmvc </ display-name> <Servlet> <Serplet-name> Dispatterservlet </vrlet-name> <Servlet-Class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <IniT-Param> <Am param-Value> CLASSPATH: Springmvc.xml </ Param-Value> </Init-Param> <Choad-on-Startup> 1 </ Load-on-Startup> </ Servlet> <Serplet-Mapping> <Serplet-Name> Dispatterservlet </vrlet-name> <url-Pattern> / </ url-Pattern> </vrlett-Maping> <Lelcome-File> index.jsp </ Welcome-File> </ Welcome-File-list> </ web -pp>
Springmvc.xml
<? xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemalation = "http://www.springframework.org/schea/bans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://wwww.springframework.org/schema/context/spring-context-4.0.xsdd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <mvc: default-servlet-handler /> <mvc: annotation-dred /> <contex Base-Package = "com.wengeryan"> </ context: composant-scan> <anan> <propriété name = "prefix" value = "/"> </ propriété> <propriété name = "suffix" value = ". jsp"> </ propriété> <propriété = "ViewClass" value = "org.springframework.web.servlet.view.jstlview"> </ property> id = "multipartreSolver"> <propriété name = "DeftherNcoding" value = "utf-8"> </ propriété> <propriété name = "maxuploadSize" value = "10485760000"> </ propriété> <propriété name = "maxinMemorySize" value = "40960"> </ propriété> </Eple> </EGHES>
3. Écrivez une action
WatermarkAction .Action
Package com.wenteryan.watermarkspringmvc; import javax.servlet.http.httpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.sterreeotype.contreler; import org.springframework.web.bind.annotation.requewing; org.springframework.web.bind.annotation.requestMethod; import org.springframework.web.bind.annotation.requestParam; import org.springframework.web.multipart.commons.commonsmultupartfile; import org.springframework.web.sservlet.Modandiew; com.wenteryan.service.markService; import com.wenteryan.service.uploadService; @ControllerPublic class watermarkAction {private markservice mackservice; Téléchargement privé UploadService; @RequestMapping (value = "/ watermark", méthode = requestMethod.Post) public ModelAndView Watermark (@RequestParam ("image") CommonsMultiPartFile Fichier, HttpSession Session) lève exception {String uploadPath = "/ images"; String realUploadPath = session.getServletContext (). GetRealPath (uploadPath); String ImageUrl = uploadService.uploadImage (fichier, uploadPath, RealUploadPath); String LOGOIMAGEURL = MACKSERVICE.WaterMark (fichier, uploadPath, RealUploadPath); ModelAndView ret = new ModelAndView (); ret.addObject ("ImageUrl", imageUrl); ret.addObject ("LOGOIMAGEURL", LOGOIMAGEURL); ret.setViewName ("Watermark"); return ret; } @Autowired public void SetMackService (MarkService MackService) {this.mackService = MackService; } @Autowired public void setuploadService (uploadService uploadService) {this.uploadService = uploadService; }}4. Écrivez des cours de service
Markservice .java
Package com.wenteryan.service; Importer java.awt.color; import java.awt.font; import java.io.file; import org.springframework.web.multipart.commons.commonsmultipartfile; interface publique MarkService {public static final mark_text = "weeryan"; 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 statique publique Font_Color = Color.red; Public statique final int x = 10; Final statique publique int y = 10; Public Static Float Alpha = 0,3F; Public String WaterMark (fichier commonsMultiPartFile, String uploadPath, String realUploadPath); }5. Écrivez des classes d'implémentation d'interface
Téléchargement de service .java
package com.wenteryan.service.impl; import java.io.fileoutputStream; import java.io.ioexception; import java.io.inputStream; import java.io.outputStream; import org.springframework.sterreotype.service; importer; org.springframework.web.multupart.commons.commonsMultupartfile; @ServicePublic class uploadService {public String uploadImage (commonsMultiparTfile file, string uploadPath) smeuploadPath) {inputStream is = null; OutputStream os = null; try {is = file.getInputStream (); OS = new FileOutputStream (RealUploadPath + "/" + file.getoriginalFileName ()); octet [] tampon = nouveau octet [1024]; int len = 0; while ((len = is.read (tampon))> 0) {os.write (tampon); }} catch (exception e) {e.printStackTrace (); } enfin {if (is! = null) {try {is.close (); } catch (ioException e) {// TODO Bloc de capture généré automatiquement e.printStackTrace (); }} if (os! = null) {try {os.close (); } catch (ioException e) {// TODO Bloc de capture généré automatiquement 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.inputStream; Importer java.io.outputstream; import javax.imageio.imageio; import org.springframework.sterereotype.service; import org.springframework.web.multipart.commons.commonsmultupartfile; import co.sun.image.codec.jpeg.jpeg.jpeg.JPEGCODEC; com.sun.image.codec.jpeg.jpegimageencoder; import com.wengeryan.service.markservice; @ServicePublic Class MarkServiceImplt implémente MarkService {@Override public watermark (CommonsMultiparpartFile Fichier, String uploadPath LogoLiploadPath) {// ToDo Auto-Generated Method LogoFilame = String LogoLipPath) ot "logo" + file.getoriginalFileName (); OutputStream os = null; try {image image2 = imageo.read (file.getInputStream ()); int width = image2.getWidth (null); int height = image2.getheight (null); BufferedImage Bufferimage = new BufferedImage (largeur, hauteur, bufferedImage.type_int_rgb); Graphics2d g = tamperImage.creategraphics (); G.DrawImage (image2, 0, 0, largeur, hauteur, null); 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 heightDiff = height-height1; int x = x; int y = y; if (x> widthDiff) {x = widthDiff; } if (y> heightDiff) {y = heightDiff; } 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 (exception e) {e.printStackTrace (); } enfin {if (os! = null) {try {os.close (); } catch (ioException e) {// TODO Bloc de capture généré automatiquement e.printStackTrace (); }} return uploadPath + "/" + LogoFileName; } public int getTextLength (string text) {int longueur = text.length (); for (int i = 0; i <text.length (); i ++) {String s = string.valueof (text.charat (i)); if (s.getBytes (). longueur> 1) {longueur ++; }} longueur = longueur% 2 == 0? Longueur / 2: longueur / 2 + 1; longueur de retour; }} 6. Écrivez une page
index.jsp
<form action = "watermark" méthode = "post" encType = "multipart / form-data"> <h2> Veuillez sélectionner l'image téléchargée </h2> <v> <br> <input type = "file" name = "image" id = "image" /> </ div> </v> <br> <bouton type = "soumettre"> Démarrer </ bouton> </ div> </vorm>
filigrane.jsp
<div> <img src = "$ {pagecontext.request.contextPath} $ {imageurl}" /> <img src = "$ {pagecontext.request.contextPath} $ {LOGOIMAGEURL}" /> <a href = "$ {pageContex </div>Résumer
Java a un ensemble spécial de traitement d'image, qui devrait également être en mesure d'implémenter la fonction de filigrane. Après avoir vérifié les informations, j'ai constaté que Java est très pratique de mettre en œuvre des filigranes. Le filigrane peut être des images ou du texte. Il y aura des filigranes au stade ultérieur. Si vous en avez besoin à l'avenir, vous pouvez écrire un code pour traiter vos propres images par lots.
Ce qui précède concerne cet article, j'espère qu'il sera utile pour tout le monde d'apprendre la programmation Java.