App backend Design (--im4java+graphicsmagick) for Chinese watermark

Source: Internet
Author: User
Tags imagemagick

In the background of the app, sometimes in order to mark the copyright, you need to add a watermark to the image.

In Liunx, Im4java+graphicsmagick is an efficient process of image processing, image clipping is the use of this technical solution, in order to reduce unnecessary development costs and operational costs, corresponding watermark, we are planning to continue to use this program.

However, in the process of development, it was found that the scheme is not good for Chinese watermark support.

According to the search results on the internet, even if the use of Im4java gmoperation, and the watermark string into GBK encoding, add Chinese watermark, for odd number of Chinese, no problem, but for an even number of Chinese, there is garbled.

After many tries, found this problem can not solve, so tried jmagick+ ImageMagick.

However, on the Internet to find a document, http://javantsky.iteye.com/blog/747807, which refers to Jmagick+imagemagick as a disadvantage of application services, and recommends that you can use the Im4java:


the "JNI Hazard" Here's that if something your use (F.ex libtiff for reading TIFF files) h As a memory bug then it can make your whole JVM crash. Thats of course frustrating and therefore its great to has im4java around, which starts IM as an external process, so J   VM crashes is avoided. * * Coolest thing would be if Jmagick and Im4java could has the same API so it is easy-to-switch depending on luckynes S. Ive asked the author of Im4java to Attemt to being as compatible as possible, but as Im4java are very much different inte    Rnally its limited how much can is done in that direction. If you don ' t like the risk, stick to Im4java.    If your want optimal performance give Jmagick a try. And, its isn't jmagick that's is buggy, it's what it depends on (hereunder IM) that's not always (memory) bug free on long ru  Nning processes.  I also has never seen a mismatch between Jmagick binary and ImageMagick binaries leading to crashes. 


Finally, the following scheme is adopted for the Chinese watermark of line-of-Sight images:

1. Create a PNG image with transparent background in Chinese first

2. Attach these PNG images as image watermarks on the map

The code is as follows:


Package Test;import Java.awt.basicstroke;import Java.awt.color;import java.awt.font;import java.awt.Graphics;import Java.awt.graphics2d;import Java.awt.image;import Java.awt.transparency;import Java.awt.font.FontRenderContext; Import Java.awt.geom.affinetransform;import Java.awt.geom.rectangle2d;import Java.awt.image.bufferedimage;import Java.io.file;import Java.io.ioexception;import Javax.imageio.imageio;import Org.im4java.core.compositecmd;import Org.im4java.core.convertcmd;import Org.im4java.core.gmoperation;import Org.im4java.core.graphicsmagickcmd;import Org.im4java.core.im4javaexception;import Org.im4java.core.imoperation;public class Watermark {/** * add watermark by Nine grid * @ param srcpath Original picture path * @param distpath new picture path * @param watermarkimg watermark Picture Path * @param position nine Gongge position [1-9], from top down, left to right sort * @param x Horizontal margin * @param y longitudinal margin * @param alpha transparency * @throws IOException * @throws interruptedexception * @throws im4javaexception */pu Blic void Watermarkimg (String srcpath,string distpath,string watermarkimg, INT position, int x, int y, int alpha) throws IOException, Interruptedexception, im4javaexception{int[] Watermarkimgside = Getimageside (watermarkimg); int[] Srcimgside = Getimageside (Srcpath); int[] xy = Getxy (Srcimgside, WatermarkImgSide, Position, y, x); Watermarkimg (Srcpath,distpath,watermarkimg,watermarkimgside[0],watermarkimgside[1],xy[0],xy[1], Alpha);}    Private int[] Getimageside (String imgpath) throws IOException {int[] side = new INT[2];    Image img = imageio.read (new File (Imgpath));    Side[0] = Img.getwidth (null);    SIDE[1] =img.getheight (NULL); return side;} /** * Add Picture watermark * @param srcpath original picture path * @param distpath new picture path * @param watermarkimg watermark Picture Path * @param width of the watermark (can be different size of watermark picture) * @p Height of Aram height watermark (can be different size of watermark picture) * @param x watermark start x coordinate * @param y watermark start y coordinate * @param alpha transparency [0-100] * @throws IOException * @throws Interruptedexception * @throws im4javaexception */private synchronized void watermarkimg (String srcpath,string Distpath , String watermarkimg, int width, int height, int x, int y, int alpha) throws IOException, Interruptedexception, im4javaexception{compositecmd cmd = new Compositecmd (true); String Path = "C://program files//graphicsmagick-1.3.19-q8"; cmd.setsearchpath (path); imoperation op = new Imopera  tion (); op.dissolve (Alpha); Op.geometry (width, height, x, y); Op.addimage (watermarkimg);  Op.addimage (Srcpath);  Op.addimage (Distpath); Cmd.run (OP);} Private int[] Getxy (int[] image, int[] watermark, int position, int x, int y) {int[] xy = new Int[2];if (position==1) { Xy[0] = x;xy[1] = y;}  else if (position==2) {xy[0] = (image[0]-watermark[0])/2;//transverse margin xy[1] = y; Longitudinal margin}else if (position==3) {xy[0] = image[0]-watermark[0]-x;xy[1] = y;} else if (position==4) {xy[0] = x;xy[1] = (image[1]-watermark[1])/2;} else if (position==5) {xy[0] = (image[0]-watermark[0])/2;xy[1] = (image[1]-watermark[1])/2;} else if (position==6) {xy[0] = image[0]-watermark[0]-x;xy[1] = (image[1]-watermark[1])/2;} else if (position==7) {xy[0] = x;xy[1] = image[1]-watermark[1]-y;} else IF (position==8) {xy[0] = (image[0]-watermark[0])/2;xy[1] = image[1]-watermark[1]-y;} Else{xy[0] = image[0]-watermark[0]-x;xy[1] = image[1]-watermark[1]-y;} return XY;} /** * Convert text to a background transparent PNG image * @param the contents of the str text * @param fonttype fonts, such as Arial * @param fontSize font size * @param colorstr font Color without #, example such as "990033" * @param outfile png picture path * @throws Exception */public void Converfonttoimage (String str,string fonttype,int F Ontsize,string colorstr, String outfile) throws Exception{font font=new Font (fonttype,font.bold,fontsize); File File=new file (outfile);//Gets the font's style applied to the entire rectangle on str rectangle2d r=font.getstringbounds (str, New FontRenderContext (  Affinetransform.getscaleinstance (1, 1), false,false)); int unitheight= (int) Math.floor (r.getheight ());//Gets the height of a single character//gets the entire str with the width of the font style here with rounding after +1 to ensure that the width can hold this string as the width of the picture int  width= (int) Math.Round (R.getwidth ()) +1; int height=unitheight+3;//The height of a single character +3 guaranteed height absolutely can hold the string as the height of the picture//create picture bufferedimage image = new BufferedImage (width, height, B  UFFEREDIMAGE.TYPE_INT_RGB); GrapHics2d g2d = Image.creategraphics ();  Image = G2d.getdeviceconfiguration (). Createcompatibleimage (width, height, transparency.translucent);  G2d.dispose ();  G2d = Image.creategraphics ();  G2d.setcolor (Color.White);  G2d.setstroke (New Basicstroke (1));  G2d.setcolor (new Color (Integer.parseint (COLORSTR, 16)));//replace the desired font color g2d.setfont (font);    G2d.drawstring (str, 0,font.getsize ()); Imageio.write (Image, "PNG", file);//Output PNG image}}

Test Example:


Package Test;import Java.awt.basicstroke;import Java.awt.color;import java.awt.font;import java.awt.Graphics;import Java.awt.graphics2d;import Java.awt.transparency;import Java.awt.font.fontrendercontext;import Java.awt.geom.affinetransform;import Java.awt.geom.rectangle2d;import Java.awt.image.bufferedimage;import Java.io.file;import Javax.imageio.imageio;import Org.im4java.core.compositecmd;import ORG.IM4JAVA.CORE.CONVERTCMD Import Org.im4java.core.gmoperation;import Org.im4java.core.imoperation;public class Test {public static void main (  String[] (args) {try {String src= "d://src.jpg"; A source image that needs to be watermarked string desc= "d://desc.jpg"; The path of the generated watermark picture string water= "D://water.png"; The background transparent PNG picture converted in Chinese into a string fonttype= "C:\\WINDOWS\\FONTS\\SIMSUN.TTC"; Specifies that the font file is a arial string colorstr= "990033"; color int fontsize=18;  Watermark watermark=new Watermark (); * * Convert text to a background transparent PNG image * @param the contents of str text * @param fonttype fonts, such as Arial * @param fontSize Font size * @param colorstr font color, without # #, for example "990033" * @param outfile png picture path * @Throws Exception */watermark.converfonttoimage ("Chinese People", Fonttype, FontSize, colorstr, water);/* * Paste the text of the PNG image on the original, create a watermark * @ param srcpath Original picture path * @param distpath new picture path * @param watermarkimg watermark Picture Path * @param position nine Gongge position [1-9], from top down, left to right sort * @param x Horizontal to margin * @param y longitudinal margin * @param alpha transparency */watermark. WATERMARKIMG (SRC, desc, water, 1, 20, 20, 100);}  catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} }}


The source has been put in github:https://github.com/newjueqi/chinesewatermark#


App back end series articles Total Directory

New "app backend technology" communication QQ Group: 254659220

[Article author] Zeng Jiansen

[Author Email] [Email protected]

[Author qq]190678908

[Sina Weibo] @newjueqi

[Blog]http://blog.csdn.net/newjueqi









App backend Design (--im4java+graphicsmagick) for Chinese watermark

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.