Java 画 jpg 图片

package com.csii.hercules.password.zdy;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

/**
 * Created by zdy on 2017/3/13.
 */
public class exportImage {
    public static void drawImage() throws IOException {

        File file=new File("/Users/zdy/Workspace/java/pic/test.png");
        BufferedImage bufferedImage=javax.imageio.ImageIO.read(file);
        BufferedImage tag=new BufferedImage(200,100,BufferedImage.TYPE_INT_RGB);

        long startMili=System.currentTimeMillis();// 当前时间对应的毫秒数
        System.out.println("开始 "+startMili);
        Graphics g=tag.getGraphics();
        Graphics2D g2=(Graphics2D)g;

        //换背景
        g2.setBackground(Color.white);
        g2.clearRect(0,0,200,100);

        //画图
        g2.drawImage(bufferedImage,0,0,100,100,null);

        //画圆
        g2.setColor(Color.orange);
        BasicStroke basicStroke=new BasicStroke(20,BasicStroke.CAP_ROUND,BasicStroke.JOIN_BEVEL);
        g2.setStroke(basicStroke);
        Shape ellipse=new Ellipse2D.Double(5,5,100,100);//椭圆,此处是圆
        g2.draw(ellipse);

        //填充矩形
        g2.setColor(Color.blue);
        Shape rectangle=new Rectangle2D.Double(110,5,100,100);
        g2.fill(rectangle);

        //写字
        Color color=new Color(0x999999);
        g2.setColor(color);
        Font font=new Font("黑体",Font.BOLD+Font.ITALIC,16);
        Date date=new Date();
        System.out.println(date.toString());
        g2.setFont(font);
        g2.drawString( String.format("%tr",date),0,16);//位置为文字左下角
        long endMili=System.currentTimeMillis();
        System.out.println("结束 "+endMili);
        System.out.println("总耗时为:"+(endMili-startMili)+"毫秒");

        FileOutputStream out = new FileOutputStream("/Users/zdy/Workspace/java/pic/result.jpg");
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(tag);
        out.close();
    }

    public static void main(String[] args) throws IOException {
        drawImage();
    }
}

你可能感兴趣的:(Java 画 jpg 图片)