--sunfruit
简介:JAVA在已有图片上面画图的实例,下面的程序在已有的图片上面画了一个蓝色的方块
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import java.util.Random;
import java.io.IOException;
import java.io.File;
 
public class ImageTest {
  public ImageTest() throws Exception {
    String ext="png";
    FileInputStream in = new FileInputStream("已有图片的路径");
    byte[] bytes = new byte[in.available()];
    in.read(bytes);
    in.close();
    Random random=new Random(System.currentTimeMillis());
    
    ImageIcon imageIcon = new ImageIcon(bytes);
    
    BufferedImage bufferedImage=new BufferedImage(imageIcon.getIconHeight(),imageIcon.getIconWidth(),BufferedImage.TYPE_INT_RGB);
    Graphics2D g=(Graphics2D)bufferedImage.getGraphics();
    g.setColor(Color.blue);
    g.drawRect(5,5,5,5);
    g.fillRect(5,5,5,5);
    g.drawImage(imageIcon.getImage(),0,0,imageIcon.getIconHeight(),imageIcon.getIconWidth(),imageIcon.getImageObserver());
 
    String filepath = System.getProperty("java.io.tmpdir") + random.nextInt(99999) + "." + ext;
    try {
      ImageIO.write(bufferedImage, ext,  new File(filepath));
      System.out.println("文件已经生成,路经为" + filepath);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
 
  }
 
  /**
   * @param args
   */
  public static void main(String[] args) throws Exception {
    new ImageTest();
  }
 
}