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