1、读取图片
常见的有两种方式读取图片:
//通过java.awt.Toolkit工具类读取
Image image = Toolkit.getDefaultToolkit().getImage(String filename);
Image image = Toolkit.getDefaultToolkit().getImage(URL url);
Toolkit.getDefaultToolkit().createImage(byte[] imageData);
//通过javax.imageio.ImageIO工具类
BufferedImage bufImage = ImageIO.read(new File(filePath));
BufferedImage bufImage = ImageIO.read(URL filePath);
BufferedImage bufImage = ImageIO.read(InputStream input);
2、对图片进行操作
//获取图片的宽高
bufImage.getWidth();
bufImage.getHeight();
//裁剪图片 x,y为左上角的坐标 该方法返回一个新的BuffererImage实例
bufImage.getSubimage(int x,int y,int width,int height);
//添加文本
void setFont(Font font)
//绘制一段文本,x,y为文本序列的左下角坐标
void drawString(String str,int x,int y)
3、利用Graphics2D绘制图形标记图片
/**
* 绘制矩形标记图片
* @param x : 左上角x坐标
* @param y :左上角y坐标
* @param width :宽度
* @param height :高度
* @param filePath :图片读取路径
* @throws Exception
*/
public void signImage(int x,int y,int width,int height,String filePath) throws Exception{
//读取图片
BufferedImage bufImage = ImageIO.read(new File(filePath));
Graphics g = bufImage.getGraphics();
Graphics2D g2d = (Graphics2D) g.create();
//设置线条颜色
g2d.setColor(Color.RED);
//设置线条宽度为5像素
BasicStroke bs = new BasicStroke(5);
g2d.setStroke(bs);
//绘制一个矩形
g2d.drawRect(x,y,width,height);
//内容保存为图片
String outPath = "c:/file";
FileOutputStream out = new FileOutputStream(outPath);
ImageIO.write(bufImage,"jpeg",out);
}