Sebelum membaca, Anda perlu memahami SpringMVC terlebih dahulu, dan kemudian lihat gambar efek terlebih dahulu.
Menulis kode
1. Paket Terkait Impor
2. File Konfigurasi
Web.xml
<? Xml Version = "1.0" encoding = "UTF-8"?> <Web-app xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns = "http://xmlnsmlnsp.org/org/xlns =" http://xmlnsmlnsp.org/org/xx = XSI: schemalocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/xml/xml/xml/nee/nee/JEE/JEE/JEE/XML/XML/XML/XML/XML/XML/XML/XML/XML/XML/XML/XML/XML/XML/XML/XML/XML/xml id = "webapp_id" version = "3.1"> <lplay-name> watermarkspringmvc </splay- <param-value> classpath: springmvc.xml </param-value> </it-param> <Boad-on-startup> 1 </load-on-startup> </servlet> <servlet-mapping> </servlet-name> </servlet-name> <rver-pattern> </url-pola> </servlet> <rerl-pattern> </url-pola> </servlet-name> <rerl-Pattern> <creendaking-file> index.jsp </welcome-file> </celcome-filt-file> </seb-app>
springmvc.xml
<? XML Versi = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmls xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemalocation = "http:BaMaM.MFC" xsi: schemalocation = "http:B http://www.springframework.org/schema/beans/spring-leans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd "> <mvc: default-servlet-handler/<mvc: annotation"> Base-package = "com.wenteryan"> </context: component-scan> <bean> <properti name = "prefix" value = "/"> </property> <properti name = "suffix" value = ". jsp"> </properties name = "viewclass" value = "org.springframework.weB.servlet.view.view.view. id = "multipartresolver"> <name properti = "DefaultEncoding" value = "UTF-8"> </property> <properti name = "maxuploadsize" value = "10485760000"> </property> <properti name = "maxInmemorySize" value = "40960"> </property> </bean> </bean "value =" 40960 "> </Properti> </bean> </bean" BEANSZE "=" 40960 "> </Properti> </bean> </bean" BEANT "value =" 40960 "> </Properti> </bean> </bean" BEANT "value =" 40960 "> </property> </Bean
3. Tulis tindakan
Watermarkaction. Tindakan
Paket com.wenteryan.watermarkspringmvc; impor javax.servlet.http.httpsession; impor org.springframework.beans.factory.annotation.Autowired; impor org.springframework.stereotypy.controller; impor org.springframework.stereotype.controller; impor org.springpring. org.springframework.web.bind.annotation.requestmethod; impor org.springframework.web.bind.annotation.requestparam; impor org.springframework.web.multipart.commons.commonsmultipartFile; org.springpringpring.commons.commonsmultipartfile; org.springpringpring.commons.commonsmultipartFile; org.springpringpringpring.commons.commonsmultipartil com.wenteryan.service.markservice; impor com.wenteryan.service.uploadservice; @ControllerPublic kelas watermarkaction {private markservice mackservice; UploadService Private UploadService; @RequestMapping (value = "/watermark", Method = requestMethod.post) Public ModelAndView Watermark (@RequestParam ("Image") File CommonsMultipartFile, Sesi Httpsession) melempar Exception {String uploadPath = "/gambar"; String realuploadpath = session.getSerVletContext (). GetRealPath (unggahPath); String ImageUrl = unggahService.uploadImage (File, Unggahpath, RealuploadPath); String logoimageUrl = mackservice.watermark (file, unggahpath, 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 (unggahService unggahanService) {this.uploadservice = unggahService; }}4. Tulis kelas layanan
Markservice .java
Paket com.wenteryan.service; import java.awt.color; impor java.awt.font; import java.io.file; string final statis public font_name = "Microsoft Yahei"; Public static final int font_size = 120; Public Static Final int font_stype = font.bold; public static final color font_color = color.red; Int final statis publik = 10; int y public static final y = 10; alpha float statis publik = 0,3F; Public String Watermark (file CommonsMultipartFile, String Unggahpath, String RealUploadPath); }
5. Tulis kelas implementasi antarmuka
Mengunggah layanan .java
Paket com.wenteryan.service.impl; import java.io.fileoutputStream; impor java.io.ioException; import java.io.inputstream; import java.io.outputStream; impor org.springframework.stereotipe.service; Impor; Impor; org.springframework.web.multipart.commons.CommonsMultipartFile; @servicepublic unggahanService {public string unggahan (file commonsmultipartfile, string unggah, string realuploadpath) {inputstream is = null; OutputStream OS = null; coba {is = file.getInputStream (); OS = FileOutputStream baru (RealuploadPath+"/"+File.getoriginalFileName ()); byte [] buffer = byte baru [1024]; int len = 0; while ((len = is.read (buffer))> 0) {os.write (buffer); }} catch (Exception e) {e.printstacktrace (); } akhirnya {if (is! = null) {coba {isClose (); } catch (ioException e) {// TODO AUTO-ENCEALATED Catch Block E.PrintStackTrace (); }} if (os! = null) {coba {os.close (); } catch (ioException e) {// TODO AUTO-ENCEALATED Catch Block E.PrintStackTrace (); }} return unggahPath+"/"+file.getoriginalFileName (); }}MarkerviceImpl .java
Paket com.wenteryan.service.impl; impor java.awt.alphacomposite; impor java.awt.font; impor java.awt.graphics2d; impor java.awt.image; impor java.awt.image.bufferedimage; impor java. java.io.ioException; import java.io.inputStream; impor java.out.outputStream; import javax.imageio.imageio; impor org.springframework.stereotype.sommons. com.sun.image.codec.jpeg.jpegcodec; import com.sun.image.codec.jpeg.jpegimageencoder; import com.wenteryan.service.markservice; @servicepublic cournePuleMpl mengimplementasikan markservice {@soverride Public COMPLICECLIC MARKSERVICEIMPL IMPLEMENSI MARKSERVICE {@OVERRIDE PUBLIC PUBLICEPULICEMPL IMPRISEMPL {@OVERRIDE PUBLIK PUBLIK RealuploadPath) {// TODO Metode yang dihasilkan secara otomatis stub string logofileName = "logo"+file.getoriginalFileName (); OutputStream OS = null; Coba {Image Image2 = ImageIo.read (file.getInputStream ()); int width = image2.getWidth (null); int tinggi = gambar2.getheight (null); BufferedImage bufferImage = BufferedImage baru (lebar, tinggi, bufferedImage.type_int_rgb); Graphics2d G = bufferImage.creategraphics (); G.DrawImage (Image2, 0, 0, Width, Height, Null); g.setfont (font baru (font_name, font_stype, font_size)); g.setColor (font_color); int width1 = font_size*getTextLength (mark_text); int height1 = font_size; int widthdiff = lebar lebar1; 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 = FileOutputStream baru (RealuploadPath+"/"+LogofileName); JpegimageEncoder en = jpegcodec.createJpegencoder (OS); en.encode (bufferImage); } catch (Exception e) {E.PrintStackTrace (); } akhirnya {if (os! = null) {coba {os.close (); } catch (ioException e) {// TODO AUTO-ENCEALATED Catch Block E.PrintStackTrace (); }} return unggahPath+"/"+logofileName; } public int getTextLength (string text) {int length = text.length (); untuk (int i = 0; i <text.length (); i ++) {string s = string.valueof (text.charat (i)); if (s.getbytes (). Length> 1) {length ++; }} panjang = panjang%2 == 0? Panjang/2: panjang/2+1; panjang pengembalian; }} 6. Tulis halaman
index.jsp
<Form Action = "Watermark" Metode = "Posting" enctype = "multipart/form-data"> <h2> Pilih gambar yang diunggah </h2> <div> <br> <input type = "file" name = "Image" ID = "Image"/> </Div> <br> <br> <bute type = "kirim"> start unggahan </unggahan> <br> <br> <br> <but button = "kirim"> start unggahan </Tombol> <br> <br> <br> <br> <Button = "KOMPORT"> start unggahan </Tombol>
watermark.jsp
<Div> <img src = "$ {pageContext.Request.contextPath} $ {imageUrl}"/> <img src = "$ {pagecontext.request.contextpath} $ {logoimageurl}"/<a href = "$ {$ {$ {$ {loGoAmageUrl}"/<a href = "$ {$ {$ {$ {$ {$ {$ {$ {$ {$ {$ </div>Meringkaskan
Java memiliki paket pemrosesan gambar khusus, yang juga harus dapat mengimplementasikan fungsi Watermark. Setelah memeriksa informasi, saya menemukan bahwa Java sangat nyaman untuk mengimplementasikan tanda air. Tanda air bisa berupa gambar atau teks. Akan ada tanda air di tahap selanjutnya. Jika Anda membutuhkannya di masa depan, Anda dapat menulis kode untuk memproses gambar Anda sendiri dalam batch.
Di atas adalah semua tentang artikel ini, saya harap akan sangat membantu bagi semua orang untuk belajar pemrograman Java.