package www9m12;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class TestBufferedImage {
public static void main(String[] args) {
Random random=new Random();
JFrame jf=new JFrame();
//在内存中创建一个画图板
BufferedImage image=new BufferedImage(70, 30, BufferedImage.TYPE_INT_RGB);
//获得画笔
Graphics graphics=image.getGraphics();
//设置画笔颜色
graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
//画一个带填充色的矩形作为背景色
graphics.fillRect(0, 0, 70, 30);
//设置画笔颜色
graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
//设置字体
graphics.setFont(new Font("Consolas",Font.BOLD+Font.ITALIC,18));
//生成一个5位的随机字符串,字符串中包括[a,z][A,Z][0,9]
String s="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
StringBuffer code=new StringBuffer();
for (int i = 0; i < 5; i++) {
int index=random.nextInt(s.length());
code.append(s.charAt(index));
}
//将文字写入图片
graphics.drawString(code.toString(), 5 , 20);
//画3条干扰线
for (int i = 0; i < 3; i++) {
//设置画笔颜色
graphics.setColor(new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)));
//生成[a,z]char c=(char) ((int) (Math.random()*('z'-'a'+1))+'a');
//画一条线
graphics.drawLine(random.nextInt(71), random.nextInt(31), random.nextInt(71), random.nextInt(31));
}
Icon ic=new ImageIcon(image);
JLabel jl=new JLabel(ic);
jf.add(jl);
jf.pack();
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
分析:
1.画一条线,初始位置(x1,y1),末位置(x2,y2)
void drawLine(int x1,int y1,int x2,int y2)
2.将文字写入图片
StringBuffer code=new StringBuffer();
for (int i = 0; i < 5; i++) {
int index=random.nextInt(s.length());
code.append(s.charAt(index));
}
graphics.drawString(code.toString(), 5 , 20);
Icon ic=new ImageIcon(image);
JLabel jl=new JLabel(ic);
jf.add(jl);
转载:
void drawArc(int x,int y,int width,int height,int startAngle,int arcAngle)
- 1
绘制弧形,起始位置由<x,y>
指定,宽和高由width和height指定,弧的起始角度为startAngle,弧的角度为arcAngle
void drawLine(int x1,int y1,int x2,int y2)
- 1
画一条线,起点和终点由<x1,y1>,<x2,y2>
确定
void drawRect(int x,int y,int width,int height)
- 1
绘制矩形,左上角位置由
void drawstring(String str,int x,int y)
- 1
使用当前的颜色和字体绘制字符串str,字符串向右伸展
void drawArc(int x,int y,int width,int height,int startAngle,int arcAngle)
drawOval (int x,int y,int width,int height)
void drawRect(int x,int y,int width,int height)
- 1
- 2
- 3
和其draw的对等方法相同,但以当前景色填充
Color getColor()
返回本图形上下文的前景色
void setColor(Color Color)
使用指定的颜色color设置本图形上下文的颜色
转载出处 https://blog.csdn.net/xiaoyiaoyou/article/details/47383085
把图片加载到窗口中,Icon-->JLabel
JLabel jl=new JLabel("测试JLabel");
jf.add(jl);
Icon ic=new ImageIcon("C:/Users/Robert/OneDrive/图片/849695d371933836b50a69fe13e7219f.jpg");
JLabel jl2=new JLabel(ic);
jf.add(jl2);