在app的后台中,有时候为了标示版权,需要给图片加上水印。
在liunx中,IM4JAVA+GraphicsMagick是个高效处理图片的方案,图片的裁剪是使用了这个技术方案,为了减少不必要的开发成本和运维成本,对应水印,我们是打算继续采用这个方案。
但在开发的过程中,发现这个方案对中文水印支持得不好。
根据网上的搜索结果,就算采用了im4java的GMOperation,并将水印的字符串转成GBK的编码,添加中文水印时,对于奇数个数的中文,没问题;但对于偶数个数的中文,就出现乱码了。
试了多次后,发现这个问题没法解决,于是试了JMagick+ ImageMagick。
但是,在网上找到一份资料,http://javantsky.iteye.com/blog/747807, 里面提到JMagick+ImageMagick作为应用服务的缺点,并建议可以使用IM4JAVA:
The "JNI hazard" here is that if something you use (f.ex libtiff for reading
TIFF files) has a memory bug then it can make your whole JVM crash. Thats of
course frustrating and therefore its great to have im4java around, which
starts IM as an external process, so JVM crashes are avoided.
* *
Coolest thing would be if JMagick and im4java could have the same API so it
was easy to switch depending on luckyness. Ive asked the author of im4java
to attemt to be as compatible as possible, but as im4java is very much
different internally its limited how much can be 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 not JMagick that is buggy, its what it depends on (hereunder IM)
that is not always (memory) bug free on long running processes.
I also have never seen a mismatch between JMagick binary and ImageMagick
binaries leading to crashes.
最后,采用了以下的方案视线图片的中文水印:
1.先把中文生成背景透明的png图片
2.把这些png图片作为图片水印贴在图上
代码如下:
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.Affine