sunfruit[请访问http://www.fruitres.cn]

--我相信JAVA能走得更远 QQ:316228067

[原创]JAVA在已有图片上面画图的实例

--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();
  }
 
}

posted on 2006-03-11 12:39 sunfruit 阅读(2058) 评论(1)  编辑  收藏 所属分类: JAVA SE & EE

评论

# re: [原创]JAVA在已有图片上面画图的实例[未登录] 2015-02-02 14:10 Allen

很感谢你的代码,帮了我大忙
指出你的两点遗漏
1:public ImageTest() throws Exception {没有写方法的返回值
2:g.drawImage(imageIcon.getImage(),0,0,imageIcon.getIconHeight(),imageIcon.getIconWidth(),imageIcon.getImageObserver());图片的长宽参数设置反了  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: