ITeye博客

java图片处理 文字水印 图片水印 缩放 补白

ericxu131 · 2009-01-04 10:23 · java & ee · Markdown

参考网上的资料 修正了里面的问题 增加了补白的功能 重构了代码 :D


import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * @author Eric Xu
 *
 */
public final class ImageUtils {
	/**
	 * 图片水印
	 * @param pressImg 水印图片
	 * @param targetImg 目标图片
	 * @param x 修正值 默认在中间
	 * @param y 修正值 默认在中间
	 * @param alpha 透明度
	 */
	public final static void pressImage(String pressImg, String targetImg, int x, int y, float alpha) {
		try {
			File img = new File(targetImg);
			Image src = ImageIO.read(img);
			int wideth = src.getWidth(null);
			int height = src.getHeight(null);
			BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = image.createGraphics();
			g.drawImage(src, 0, 0, wideth, height, null);
			//水印文件
			Image src_biao = ImageIO.read(new File(pressImg));
			int wideth_biao = src_biao.getWidth(null);
			int height_biao = src_biao.getHeight(null);
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
			g.drawImage(src_biao, (wideth - wideth_biao) / 2, (height - height_biao) / 2, wideth_biao, height_biao, null);
			//水印文件结束
			g.dispose();
			ImageIO.write((BufferedImage) image, "jpg", img);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 文字水印
	 * @param pressText 水印文字
	 * @param targetImg 目标图片
	 * @param fontName 字体名称
	 * @param fontStyle 字体样式
	 * @param color 字体颜色
	 * @param fontSize 字体大小
	 * @param x 修正值
	 * @param y 修正值
	 * @param alpha 透明度
	 */
	public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, Color color, int fontSize, int x, int y, float alpha) {
		try {
			File img = new File(targetImg);
			Image src = ImageIO.read(img);
			int width = src.getWidth(null);
			int height = src.getHeight(null);
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = image.createGraphics();
			g.drawImage(src, 0, 0, width, height, null);
			g.setColor(color);
			g.setFont(new Font(fontName, fontStyle, fontSize));
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
			g.drawString(pressText, (width - (getLength(pressText) * fontSize)) / 2 + x, (height - fontSize) / 2 + y);
			g.dispose();
			ImageIO.write((BufferedImage) image, "jpg", img);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 缩放
	 * @param filePath 图片路径
	 * @param height 高度
	 * @param width 宽度
	 * @param bb 比例不对时是否需要补白
	 */
	public static void resize(String filePath, int height, int width, boolean bb) {
		try {
			double ratio = 0.0; //缩放比例 
			File f = new File(filePath);
			BufferedImage bi = ImageIO.read(f);
			Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
			//计算比例
			if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
				if (bi.getHeight() > bi.getWidth()) {
					ratio = (new Integer(height)).doubleValue() / bi.getHeight();
				} else {
					ratio = (new Integer(width)).doubleValue() / bi.getWidth();
				}
				AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
				itemp = op.filter(bi, null);
			}
			if (bb) {
				BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				Graphics2D g = image.createGraphics();
				g.setColor(Color.white);
				g.fillRect(0, 0, width, height);
				if (width == itemp.getWidth(null))
					g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
				else
					g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null);
				g.dispose();
				itemp = image;
			}
			ImageIO.write((BufferedImage) itemp, "jpg", f);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws IOException {
		pressImage("G:\\imgtest\\sy.jpg", "G:\\imgtest\\test1.jpg", 0, 0, 0.5f);
		pressText("我是文字水印", "G:\\imgtest\\test1.jpg", "黑体", 36, Color.white, 80, 0, 0, 0.3f);
		resize("G:\\imgtest\\test1.jpg", 500, 500, true);
	}

	public static int getLength(String text) {
		int length = 0;
		for (int i = 0; i < text.length(); i++) {
			if (new String(text.charAt(i) + "").getBytes().length > 1) {
				length += 2;
			} else {
				length += 1;
			}
		}
		return length / 2;
	}
}

getLength 这个方法用来得到文字的长度 全角一个字 半角算半个字 但是感觉这种方法不太好 不知道有没有更好地方法~

评论(11)

  1. #11 楼 · yangpeihai · 2009-12-22 09:35

    谢谢lz。不过调用resize方法后,图片的质量就变差了,期待楼主3.0版本

  2. #10 楼 · chenlixun · 2009-12-02 16:04

    ericxu131 writes:

    参考网上的资料 修正了里面的问题 增加了补白的功能 重构了代码 :D [code=java] import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException;

    import javax.imageio.ImageIO;

    /**

    • @author Eric Xu * / public final class ImageUtils { /*
      • 图片水印
      • @param pressImg 水印图片
      • @param targetImg 目标图片
      • @param x 修正值 默认在中间
      • @param y 修正值 默认在中间
      • @param alpha 透明度 */ public final static void pressImage(String pressImg, String targetImg, int x, int y, float alpha) { try { File img = new File(targetImg); Image src = ImageIO.read(img); int wideth = src.getWidth(null); int height = src.getHeight(null); BufferedImage image = new BufferedImage(wideth, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.drawImage(src, 0, 0, wideth, height, null); //水印文件 Image src_biao = ImageIO.read(new File(pressImg)); int wideth_biao = src_biao.getWidth(null); int height_biao = src_biao.getHeight(null); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); g.drawImage(src_biao, (wideth - wideth_biao) / 2, (height - height_biao) / 2, wideth_biao, height_biao, null); //水印文件结束 g.dispose(); ImageIO.write((BufferedImage) image, "jpg", img); } catch (Exception e) { e.printStackTrace(); } }

    /** * 文字水印 * @param pressText 水印文字 * @param targetImg 目标图片 * @param fontName 字体名称 * @param fontStyle 字体样式 * @param color 字体颜色 * @param fontSize 字体大小 * @param x 修正值 * @param y 修正值 * @param alpha 透明度 */ public static void pressText(String pressText, String targetImg, String fontName, int fontStyle, Color color, int fontSize, int x, int y, float alpha) { try { File img = new File(targetImg); Image src = ImageIO.read(img); int width = src.getWidth(null); int height = src.getHeight(null); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.drawImage(src, 0, 0, width, height, null); g.setColor(color); g.setFont(new Font(fontName, fontStyle, fontSize)); g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); g.drawString(pressText, (width - (getLength(pressText) * fontSize)) / 2 + x, (height - fontSize) / 2 + y); g.dispose(); ImageIO.write((BufferedImage) image, "jpg", img); } catch (Exception e) { e.printStackTrace(); } }

    /** * 缩放 * @param filePath 图片路径 * @param height 高度 * @param width 宽度 * @param bb 比例不对时是否需要补白 */ public static void resize(String filePath, int height, int width, boolean bb) { try { double ratio = 0.0; //缩放比例 File f = new File(filePath); BufferedImage bi = ImageIO.read(f); Image itemp = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH); //计算比例 if ((bi.getHeight() > height) || (bi.getWidth() > width)) { if (bi.getHeight() > bi.getWidth()) { ratio = (new Integer(height)).doubleValue() / bi.getHeight(); } else { ratio = (new Integer(width)).doubleValue() / bi.getWidth(); } AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null); itemp = op.filter(bi, null); } if (bb) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setColor(Color.white); g.fillRect(0, 0, width, height); if (width == itemp.getWidth(null)) g.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null), Color.white, null); else g.drawImage(itemp, (width - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null), Color.white, null); g.dispose(); itemp = image; } ImageIO.write((BufferedImage) itemp, "jpg", f); } catch (IOException e) { e.printStackTrace(); } }

    public static void main(String[] args) throws IOException { pressImage("G:\imgtest\sy.jpg", "G:\imgtest\test1.jpg", 0, 0, 0.5f); pressText("我是文字水印", "G:\imgtest\test1.jpg", "黑体", 36, Color.white, 80, 0, 0, 0.3f); resize("G:\imgtest\test1.jpg", 500, 500, true); }

    public static int getLength(String text) { int length = 0; for (int i = 0; i < text.length(); i++) { if (new String(text.charAt(i) + "").getBytes().length > 1) { length += 2; } else { length += 1; } } return length / 2; } } [/code]

    getLength 这个方法用来得到文字的长度 全角一个字 半角算半个字 但是感觉这种方法不太好 不知道有没有更好地方法~

    大并发且图片比较大时,有没有对性能做个测试!?

  3. #9 楼 · ericxu131 · 2009-11-19 15:41

    zelsa writes:

    直接用ImageMagick处理吧,就没这么多问题了。

    ImageMagick 进行翻转、缩放大小、旋转: [url]http://www.coffeeba.net/?p=289[/url]

    ImageMagick 圆角和边框: [url]http://www.coffeeba.net/?p=271[/url]

    ImageMagick 教程: [url]http://www.coffeeba.net/?p=210[/url]

    再附上一段调用ImageMagick的方法: [code=java] public static void main(String[] args){ ArrayList command = new ArrayList(); command.add("/usr/bin/convert"); command.add("/home/bigImage.jpg"); command.add("-resize"); command.add("120x80"); command.add("/home/smallImage.jpg"); exec(command); }

    public static boolean exec(ArrayList command) {
        Process proc;
    
        try {
            //System.out.println("Trying to execute command " + Arrays.asList(command));
            proc = Runtime.getRuntime().exec((String[]) command.toArray(new String[1]));
        } catch (IOException e) {
            System.out.println("IOException while trying to execute " + command);
            return false;
        }
    
        //System.out.println("Got process object, waiting to return.");
    
        int exitStatus;
    
        while (true) {
            try {
                exitStatus = proc.waitFor();
                break;
            } catch (java.lang.InterruptedException e) {
                System.out.println("Interrupted: Ignoring and waiting");
            }
        }
        if (exitStatus != 0) {
            System.out.println("Error executing command: " + exitStatus);
        }
        return (exitStatus == 0);
    }
    

    [/code]

    cool~ :D

  4. #8 楼 · zelsa · 2009-11-18 18:40

    直接用ImageMagick处理吧,就没这么多问题了。

    ImageMagick 进行翻转、缩放大小、旋转: http://www.coffeeba.net/?p=289

    ImageMagick 圆角和边框: http://www.coffeeba.net/?p=271

    ImageMagick 教程: http://www.coffeeba.net/?p=210

    再附上一段调用ImageMagick的方法:

    
        public static void main(String[] args){
            ArrayList<String> command = new ArrayList<String>();
            command.add("/usr/bin/convert");
            command.add("/home/bigImage.jpg");
            command.add("-resize");
            command.add("120x80");
            command.add("/home/smallImage.jpg");
            exec(command);
        }
    
        public static boolean exec(ArrayList command) {
            Process proc;
    
            try {
                //System.out.println("Trying to execute command " + Arrays.asList(command));
                proc = Runtime.getRuntime().exec((String[]) command.toArray(new String[1]));
            } catch (IOException e) {
                System.out.println("IOException while trying to execute " + command);
                return false;
            }
    
            //System.out.println("Got process object, waiting to return.");
    
            int exitStatus;
    
            while (true) {
                try {
                    exitStatus = proc.waitFor();
                    break;
                } catch (java.lang.InterruptedException e) {
                    System.out.println("Interrupted: Ignoring and waiting");
                }
            }
            if (exitStatus != 0) {
                System.out.println("Error executing command: " + exitStatus);
            }
            return (exitStatus == 0);
        }
    
    
  5. #7 楼 · xiangyh · 2009-11-18 15:39

    多线程的情况会有内存泄露的问题吧!

  6. #6 楼 · skyuck · 2009-11-11 10:53

    图片大了造成内存溢出

  7. #5 楼 · fffddd · 2009-07-19 02:38

    处理后的图质量明显低于以前了。

  8. #4 楼 · 331008019 · 2009-07-10 12:25

    很不错, 在网上看到很多相关的帖子都是一样的, 这个功能算是最齐全的了, 多谢!

  9. #3 楼 · longhong · 2009-03-09 10:48

    如何在图片中加斜向文字

  10. #2 楼 · insiku · 2009-01-04 13:41

    FontMetrics 不好

    Font.getStringBounds(String str, FontRenderContext frc) 返回指定 FontRenderContext 中指定 String 的逻辑边界。

    Graphics2D.getFontRenderContext()

  11. #1 楼 · guooscar · 2009-01-04 13:22

    FontMetrics

评论功能维护中,当前仅展示历史评论。