В этой статье представлен пример кода для добавления водяных знаков в Java Pictures. Очень удобно внедрить водяные знаки в Java. Водяным знаком может быть картинки или текст. Конкретный контент заключается в следующем
Пакет Michael.io.image; импортировать java.awt.alphacomposite; импортировать java.awt.graphics2d; импортировать java.awt.image; Импорт java.awt.renderinghints; Импорт java.awt.image.bufferedImage; Импорт java.io.file; импортировать java.io.fileinputstream; Импорт java.io.fileOutputStream; импортировать java.io.inputstream; импортировать java.io.outputstream; Импорт javax.imageio.imageio; Импорт javax.swing.imageicon; Импорт com.sun.image.codec.jpeg.jpegcodec; Import com.sun.image.codec.jpeg.jpegimagedecoder; Импорт com.sun.image.codec.jpeg.jpegimageencoder; /** * Изображение Watermark * @blog http://sjsky.iteye.com * @author michael */public class Imagemarklogobyicon {/** * @param args */public void main (string [] args) {string srcimgpath = "d: /test/michael/myblog_01.pg"; String iconpath = "d: /test/michael/blog_logo.png"; String TargetPath = "d: /test/michael/img_mark_icon.jpg"; String targetPath2 = "d: /test/michael/img_mark_icon_rotate.jpg"; // Добавить водяной знак в Image ImageMarklogobyicon.markimagebyicon (Iconpath, Srcimgpath, TargetPath); // Добавить водяной знак к изображению, watermark rowation -45 ImageMarklogobyicon.markimagebyicon (Iconpath, Srcimgpath, TargetPath2, -45); } / *** Добавить водяной знак к изображению* @param ICONPATH PATH PATH* @param Srcimgpath Изображение* @param TargetPath Path* / public static void markimagebyicon (string iconpath, string srcimgpath, string targetpath) {markimagebyicon (iconpath, srcimgpath, nearly) {markimagebycon (iconpath, srcimgpath, narull, nearlul, nearlul; } /** * Add a watermark to the image and set the rotation angle of the watermark image* @param iconPath Watermark image path* @param srcImgPath Source image path* @param targetPath Target image path* @param degree Watermark image rotation angle*/ public static void markImageByIcon(String iconPath, String srcImgPath, String targetPath, Integer degree) { OutputStream os = нулевой; try {image srcimg = imageio.read (новый файл (srcimgpath)); BufferedImage buffimg = new BufferedImage (srcimg.getwidth (null), srcimg.getheight (null), bufferedimage.type_int_rgb); // Получить объект кисти // Graphics G = buffimg.getGraphics (); Graphics2d g = buffimg.creategraphics (); // Установите обработку зазубного края линейного сегмента g.setRenderingHint (renderingHints.key_interpolation, renderingHints.value_interpolation_bilinear); g.drawimage (srcimg.getscaledinstance (srcimg.getwidth (null), srcimg .getheight (null), image.scale_smooth), 0, 0, null); if (null! = degraph) {// установить вращение водяного знака g.rotate (math.toradians (степень), (двойной) buffimg.getwidth () / 2, (двойной) buffimg .getheight () / 2); } // Путь изображения водяного знака, как правило, GIF или PNG, так что прозрачность может быть установлена ImageICon Imgicon = new Imageicon (Iconpath); // Получить объект изображения. Image img = imgicon.getimage (); Float Alpha = 0,5F; // прозрачность g.setcomposite (alphacomposite.getinstance (alphacomposite.src_atop, alpha)); // указывает местоположение изображения водяного знака G.Drawimage (IMG, 150, 300, NULL); g.setcomposite (alphacomposite.getinstance (alphacomposite.src_over)); g.dispose (); OS = New FileOutputStream (TargerPath); // генерировать Image Imageio.Write (buffimg, "jpg", OS); System.out.println («Изображение закончено добавление уплотнения значков ...»); } catch (Exception e) {e.printstackTrace (); } наконец {try {if (null! = os) os.close (); } catch (Exception e) {e.printstackTrace (); }}}}Позвольте мне поделиться с вами другим примером:
Импорт java.awt.color; import java.awt.font; import java.awt.graphics; импорт java.awt.image; импорт java.awt.image.bufferedimage; импорт java.io.file; импорт java.io.fileOutputStream; import javax.iMageio; com.sun.image.codec.jpeg.jpegcodec; импорт com.sun.image.codec.jpeg.jpegimageencoder; public final Class ImageUtils {public ImageUtils () {}/** * public final Static String getPressImgPath () {return ApplicationContext * .getRealPath ("/template/data/util/shuiyin.gif"); } *//** * Распечатайте изображение на изображении * * @param pressimg - * file watermark * @param targetimg - * Target File * @param x * --x координаты * @param y * -y координаты */public static void pressimage (string pressimg, string target, int x, int y) {try {// arget file file _file =; Image src = imageio.read (_file); int wideth = src.getwidth (null); int height = src.getheight (null); BufferedImage Image = new BufferedImage (Wiveth, высота, BufferedImage.type_int_rgb); Graphics g = image.creategraphics (); g.drawimage (src, 0, 0, wareth, высота, нулевая); // файл watermark file _filebiao = new File (pressimg); Image src_biao = imageio.read (_filebiao); int wideth_biao = src_biao.getWidth (null); int height_biao = src_biao.getheight (null); g.drawimage (src_biao, (wideth - wideth_biao) / 2, (высота - height_biao) / 2, wideth_biao, height_biao, null); // конец водяного файла g.dispose (); FileOutputStream OUT = new FileOutPutStream (TargetImg); Jpegimageencoder encoder = jpegcodec.createjpegenceder (out); encoder.encode (image); out.close (); } catch (Exception e) {e.printstackTrace (); }} / ** * Печать текстовое изображение водяного знака * * @param presstext * –text * @param targetimg - * target image * @param fontname - * font name * @param fontstyle - * @param style * @param - * font color * @param fontsize - * font size * @param x -fortset * @param y * publis fontname, int fontstyle, int color, int fontsize, int x, int y) {try {file _file = new File (targetimg); Image src = imageio.read (_file); int wideth = src.getwidth (null); int height = src.getheight (null); BufferedImage Image = new BufferedImage (Wiveth, высота, BufferedImage.type_int_rgb); Graphics g = image.creategraphics (); g.drawimage (src, 0, 0, wareth, высота, нулевая); g.setcolor (color.red); g.setfont (новый шрифт (fontname, fontstyle, fontsize)); g.drawstring (presstext, wideth - fontsize - x, height - fontsize / 2 - y); g.dispose (); FileOutputStream OUT = new FileOutPutStream (TargetImg); Jpegimageencoder encoder = jpegcodec.createjpegenceder (out); encoder.encode (image); out.close (); } catch (Exception e) {System.out.println (e); }} public static void main (string [] args) {pressimage ("f: /logo.png", "f: /123.jpg", 0, 0); }}Я надеюсь, что эта статья будет полезна для всех, чтобы использовать Java Language, чтобы добавить водяные знаки к изображениям.