📄 imagecreator.java
字号:
package tool;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class ImageCreator {
// 字符数组
private char mapTable[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'z', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9' };
/**
* 得到图片对象的字符串 和图片对象
*
* @param width
* 宽度
* @param height
* 高度
* @param out
* 输出流对象 字节流的所有类的超类 子类对象即可
* @return 字符串
*/
public String getImage(int width, int height, OutputStream os) {
if (width <= 0) {
width = 80; // 默认宽度
}
if (height <= 0) {
height = 30; // 默认高度
}
// java.awt.image.BufferedImage; 图像数据缓冲区
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics graphics = image.getGraphics();
// 设定背景色
graphics.setColor(new Color(0xFFCCDC));
graphics.fillRect(0, 0, width, height);
// 画边框
graphics.setColor(Color.black);
graphics.drawRect(0, 0, width-1 , height-1);
// 取随机产生的认证码
String strImageString = "";
// 5代码5为验证码
for (int i = 0; i < 5; i++) {
strImageString += mapTable[(int) (mapTable.length * Math.random())];
}
// 将认证码显示到图像中
graphics.setColor(Color.black);
graphics.setFont(new Font("Arial", Font.PLAIN, 18));
String string = strImageString.substring(0, 1);
graphics.drawString(string, 8, 27);
string = strImageString.substring(1, 2);
graphics.drawString(string, 20, 15);
string = strImageString.substring(2, 3);
graphics.drawString(string, 35, 18);
string = strImageString.substring(3, 4);
graphics.drawString(string, 47, 20);
string = strImageString.substring(4, 5);
graphics.drawString(string, 58, 22);
// 随机产生100干扰点
for (int i = 0; i < 100; i++) {
int x = new Random().nextInt(width);
int y = new Random().nextInt(height);
graphics.drawOval(x, y, 1, 1);
}
// 释放图形上下文
graphics.dispose();
try {
ImageIO.write(image, "JPEG", os);
} catch (Exception e) {
return "";
}
return strImageString;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -