Java-生成动态图片验证码

傷城~ 2023-10-07 16:33 173阅读 0赞

先看效果:
2022010707060742415.gif
获取验证码接口:

  1. @Override
  2. public Map getPictureCode() {
  3. GifCaptcha gifCaptcha = new GifCaptcha(130, 48, 5);
  4. Map<String, Object> map = new HashMap<>();
  5. String key = UUID.randomUUID().toString();
  6. String verCode = gifCaptcha.text().toLowerCase();
  7. map.put("key", key);
  8. map.put("image", gifCaptcha.toBase64());
  9. System.out.println(verCode);
  10. redisTemplate.opsForValue().set(key, verCode, 5, TimeUnit.MINUTES);
  11. return map;
  12. }

接口返回的参数是这样的(data:image/gif;base64,格式的):

  1. {
  2. "code": "200",
  3. "data": {
  4. "image": "https://img-blog.csdnimg.cn/2022010707060742415.gif",
  5. "key": "bd13a0fb-1b8a-42bc-9af1-662dfda4e309"
  6. },
  7. "message": "请求成功!"
  8. }

然后我们可以通过下面这个文本打开,先创建一个txt文本,将接口返回的参数放入下面的![Image 1][]标签中,将后缀改为html,保存后双击打开就可以看到效果了。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>标题</title>
  5. </head>
  6. <body>
  7. <p>Hello World!</p>
  8. <img src="https://img-blog.csdnimg.cn/2022010707060742415.gif"/>
  9. </body>
  10. </html>

打开效果:
在这里插入图片描述

验证码生成工具类:

  1. import java.awt.*;
  2. import java.awt.geom.CubicCurve2D;
  3. import java.awt.image.BufferedImage;
  4. import java.io.IOException;
  5. import java.io.OutputStream;
  6. public class GifCaptcha extends Captcha {
  7. public GifCaptcha() {
  8. }
  9. public GifCaptcha(int width, int height) {
  10. setWidth(width);
  11. setHeight(height);
  12. }
  13. public GifCaptcha(int width, int height, int len) {
  14. this(width, height);
  15. setLen(len);
  16. }
  17. public GifCaptcha(int width, int height, int len, Font font) {
  18. this(width, height, len);
  19. setFont(font);
  20. }
  21. @Override
  22. public boolean out(OutputStream os) {
  23. try {
  24. char[] strs = textChar(); // 获取验证码数组
  25. // 随机生成每个文字的颜色
  26. Color fontColor[] = new Color[len];
  27. for (int i = 0; i < len; i++) {
  28. fontColor[i] = color();
  29. }
  30. // 随机生成贝塞尔曲线参数
  31. int x1 = 5, y1 = num(5, height / 2);
  32. int x2 = width - 5, y2 = num(height / 2, height - 5);
  33. int ctrlx = num(width / 4, width / 4 * 3), ctrly = num(5, height - 5);
  34. if (num(2) == 0) {
  35. int ty = y1;
  36. y1 = y2;
  37. y2 = ty;
  38. }
  39. int ctrlx1 = num(width / 4, width / 4 * 3), ctrly1 = num(5, height - 5);
  40. int[][] besselXY = new int[][]{
  41. {
  42. x1, y1}, {
  43. ctrlx, ctrly}, {
  44. ctrlx1, ctrly1}, {
  45. x2, y2}};
  46. // 开始画gif每一帧
  47. GifEncoder gifEncoder = new GifEncoder();
  48. gifEncoder.setQuality(180);
  49. gifEncoder.setDelay(100);
  50. gifEncoder.setRepeat(0);
  51. gifEncoder.start(os);
  52. for (int i = 0; i < len; i++) {
  53. BufferedImage frame = graphicsImage(fontColor, strs, i, besselXY);
  54. gifEncoder.addFrame(frame);
  55. frame.flush();
  56. }
  57. gifEncoder.finish();
  58. return true;
  59. } catch (Exception e) {
  60. e.printStackTrace();
  61. } finally {
  62. try {
  63. os.close();
  64. } catch (IOException e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. return false;
  69. }
  70. @Override
  71. public String toBase64() {
  72. return toBase64("data:image/gif;base64,");
  73. }
  74. /**
  75. * 画随机码图
  76. *
  77. * @param fontColor 随机字体颜色
  78. * @param strs 字符数组
  79. * @param flag 透明度
  80. * @param besselXY 干扰线参数
  81. * @return BufferedImage
  82. */
  83. private BufferedImage graphicsImage(Color[] fontColor, char[] strs, int flag, int[][] besselXY) {
  84. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  85. Graphics2D g2d = (Graphics2D) image.getGraphics();
  86. // 填充背景颜色
  87. g2d.setColor(Color.WHITE);
  88. g2d.fillRect(0, 0, width, height);
  89. // 抗锯齿
  90. g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  91. // 画干扰圆圈
  92. g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f * num(10))); // 设置透明度
  93. drawOval(2, g2d);
  94. // 画干扰线
  95. g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f)); // 设置透明度
  96. g2d.setStroke(new BasicStroke(1.2f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
  97. g2d.setColor(fontColor[0]);
  98. CubicCurve2D shape = new CubicCurve2D.Double(besselXY[0][0], besselXY[0][1], besselXY[1][0], besselXY[1][1], besselXY[2][0], besselXY[2][1], besselXY[3][0], besselXY[3][1]);
  99. g2d.draw(shape);
  100. // 画验证码
  101. g2d.setFont(getFont());
  102. FontMetrics fontMetrics = g2d.getFontMetrics();
  103. int fW = width / strs.length; // 每一个字符所占的宽度
  104. int fSp = (fW - (int) fontMetrics.getStringBounds("W", g2d).getWidth()) / 2; // 字符的左右边距
  105. for (int i = 0; i < strs.length; i++) {
  106. // 设置透明度
  107. AlphaComposite ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getAlpha(flag, i));
  108. g2d.setComposite(ac3);
  109. g2d.setColor(fontColor[i]);
  110. int fY = height - ((height - (int) fontMetrics.getStringBounds(String.valueOf(strs[i]), g2d).getHeight()) >> 1); // 文字的纵坐标
  111. g2d.drawString(String.valueOf(strs[i]), i * fW + fSp + 3, fY - 3);
  112. }
  113. g2d.dispose();
  114. return image;
  115. }
  116. /**
  117. * 获取透明度,从0到1,自动计算步长
  118. *
  119. * @param i
  120. * @param j
  121. * @return 透明度
  122. */
  123. private float getAlpha(int i, int j) {
  124. int num = i + j;
  125. float r = (float) 1 / (len - 1);
  126. float s = len * r;
  127. return num >= len ? (num * r - s) : num * r;
  128. }
  129. }

其它辅助工具:

  1. import java.awt.*;
  2. import java.awt.geom.CubicCurve2D;
  3. import java.awt.geom.QuadCurve2D;
  4. import java.io.ByteArrayOutputStream;
  5. import java.io.IOException;
  6. import java.io.OutputStream;
  7. import java.util.Base64;
  8. public abstract class Captcha extends Randoms {
  9. // 常用颜色
  10. public static final int[][] COLOR = {
  11. {
  12. 0, 135, 255}, {
  13. 51, 153, 51}, {
  14. 255, 102, 102}, {
  15. 255, 153, 0}, {
  16. 153, 102, 0}, {
  17. 153, 102, 153}, {
  18. 51, 153, 153}, {
  19. 102, 102, 255}, {
  20. 0, 102, 204}, {
  21. 204, 51, 51}, {
  22. 0, 153, 204}, {
  23. 0, 51, 102}};
  24. // 验证码文本类型
  25. public static final int TYPE_DEFAULT = 1; // 字母数字混合
  26. public static final int TYPE_ONLY_NUMBER = 2; // 纯数字
  27. public static final int TYPE_ONLY_CHAR = 3; // 纯字母
  28. public static final int TYPE_ONLY_UPPER = 4; // 纯大写字母
  29. public static final int TYPE_ONLY_LOWER = 5; // 纯小写字母
  30. public static final int TYPE_NUM_AND_UPPER = 6; // 数字大写字母
  31. // 内置字体
  32. public static final int FONT_1 = 0;
  33. public static final int FONT_2 = 1;
  34. public static final int FONT_3 = 2;
  35. public static final int FONT_4 = 3;
  36. public static final int FONT_5 = 4;
  37. public static final int FONT_6 = 5;
  38. public static final int FONT_7 = 6;
  39. public static final int FONT_8 = 7;
  40. public static final int FONT_9 = 8;
  41. public static final int FONT_10 = 9;
  42. private static final String[] FONT_NAMES = new String[]{
  43. "actionj.ttf", "epilog.ttf", "fresnel.ttf", "headache.ttf", "lexo.ttf", "prefix.ttf", "progbot.ttf", "ransom.ttf", "robot.ttf", "scandal.ttf"};
  44. private Font font = null; // 验证码的字体
  45. protected int len = 5; // 验证码随机字符长度
  46. protected int width = 130; // 验证码显示宽度
  47. protected int height = 48; // 验证码显示高度
  48. protected int charType = TYPE_DEFAULT; // 验证码类型
  49. protected String chars = null; // 当前验证码
  50. /**
  51. * 生成随机验证码
  52. *
  53. * @return 验证码字符数组
  54. */
  55. protected char[] alphas() {
  56. char[] cs = new char[len];
  57. for (int i = 0; i < len; i++) {
  58. switch (charType) {
  59. case 2:
  60. cs[i] = alpha(numMaxIndex);
  61. break;
  62. case 3:
  63. cs[i] = alpha(charMinIndex, charMaxIndex);
  64. break;
  65. case 4:
  66. cs[i] = alpha(upperMinIndex, upperMaxIndex);
  67. break;
  68. case 5:
  69. cs[i] = alpha(lowerMinIndex, lowerMaxIndex);
  70. break;
  71. case 6:
  72. cs[i] = alpha(upperMaxIndex);
  73. break;
  74. default:
  75. cs[i] = alpha();
  76. }
  77. }
  78. chars = new String(cs);
  79. return cs;
  80. }
  81. /**
  82. * 给定范围获得随机颜色
  83. *
  84. * @param fc 0-255
  85. * @param bc 0-255
  86. * @return 随机颜色
  87. */
  88. protected Color color(int fc, int bc) {
  89. if (fc > 255)
  90. fc = 255;
  91. if (bc > 255)
  92. bc = 255;
  93. int r = fc + num(bc - fc);
  94. int g = fc + num(bc - fc);
  95. int b = fc + num(bc - fc);
  96. return new Color(r, g, b);
  97. }
  98. /**
  99. * 获取随机常用颜色
  100. *
  101. * @return 随机颜色
  102. */
  103. protected Color color() {
  104. int[] color = COLOR[num(COLOR.length)];
  105. return new Color(color[0], color[1], color[2]);
  106. }
  107. /**
  108. * 验证码输出,抽象方法,由子类实现
  109. *
  110. * @param os 输出流
  111. * @return 是否成功
  112. */
  113. public abstract boolean out(OutputStream os);
  114. /**
  115. * 输出base64编码
  116. *
  117. * @return base64编码字符串
  118. */
  119. public abstract String toBase64();
  120. /**
  121. * 输出base64编码
  122. *
  123. * @param type 编码头
  124. * @return base64编码字符串
  125. */
  126. public String toBase64(String type) {
  127. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  128. out(outputStream);
  129. return type + Base64.getEncoder().encodeToString(outputStream.toByteArray());
  130. }
  131. /**
  132. * 获取当前的验证码
  133. *
  134. * @return 字符串
  135. */
  136. public String text() {
  137. checkAlpha();
  138. return chars;
  139. }
  140. /**
  141. * 获取当前验证码的字符数组
  142. *
  143. * @return 字符数组
  144. */
  145. public char[] textChar() {
  146. checkAlpha();
  147. return chars.toCharArray();
  148. }
  149. /**
  150. * 检查验证码是否生成,没有则立即生成
  151. */
  152. public void checkAlpha() {
  153. if (chars == null) {
  154. alphas(); // 生成验证码
  155. }
  156. }
  157. /**
  158. * 随机画干扰线
  159. *
  160. * @param num 数量
  161. * @param g Graphics2D
  162. */
  163. public void drawLine(int num, Graphics2D g) {
  164. drawLine(num, null, g);
  165. }
  166. /**
  167. * 随机画干扰线
  168. *
  169. * @param num 数量
  170. * @param color 颜色
  171. * @param g Graphics2D
  172. */
  173. public void drawLine(int num, Color color, Graphics2D g) {
  174. for (int i = 0; i < num; i++) {
  175. g.setColor(color == null ? color() : color);
  176. int x1 = num(-10, width - 10);
  177. int y1 = num(5, height - 5);
  178. int x2 = num(10, width + 10);
  179. int y2 = num(2, height - 2);
  180. g.drawLine(x1, y1, x2, y2);
  181. }
  182. }
  183. /**
  184. * 随机画干扰圆
  185. *
  186. * @param num 数量
  187. * @param g Graphics2D
  188. */
  189. public void drawOval(int num, Graphics2D g) {
  190. drawOval(num, null, g);
  191. }
  192. /**
  193. * 随机画干扰圆
  194. *
  195. * @param num 数量
  196. * @param color 颜色
  197. * @param g Graphics2D
  198. */
  199. public void drawOval(int num, Color color, Graphics2D g) {
  200. for (int i = 0; i < num; i++) {
  201. g.setColor(color == null ? color() : color);
  202. int w = 5 + num(10);
  203. g.drawOval(num(width - 25), num(height - 15), w, w);
  204. }
  205. }
  206. /**
  207. * 随机画贝塞尔曲线
  208. *
  209. * @param num 数量
  210. * @param g Graphics2D
  211. */
  212. public void drawBesselLine(int num, Graphics2D g) {
  213. drawBesselLine(num, null, g);
  214. }
  215. /**
  216. * 随机画贝塞尔曲线
  217. *
  218. * @param num 数量
  219. * @param color 颜色
  220. * @param g Graphics2D
  221. */
  222. public void drawBesselLine(int num, Color color, Graphics2D g) {
  223. for (int i = 0; i < num; i++) {
  224. g.setColor(color == null ? color() : color);
  225. int x1 = 5, y1 = num(5, height / 2);
  226. int x2 = width - 5, y2 = num(height / 2, height - 5);
  227. int ctrlx = num(width / 4, width / 4 * 3), ctrly = num(5, height - 5);
  228. if (num(2) == 0) {
  229. int ty = y1;
  230. y1 = y2;
  231. y2 = ty;
  232. }
  233. if (num(2) == 0) {
  234. // 二阶贝塞尔曲线
  235. QuadCurve2D shape = new QuadCurve2D.Double();
  236. shape.setCurve(x1, y1, ctrlx, ctrly, x2, y2);
  237. g.draw(shape);
  238. } else {
  239. // 三阶贝塞尔曲线
  240. int ctrlx1 = num(width / 4, width / 4 * 3), ctrly1 = num(5, height - 5);
  241. CubicCurve2D shape = new CubicCurve2D.Double(x1, y1, ctrlx, ctrly, ctrlx1, ctrly1, x2, y2);
  242. g.draw(shape);
  243. }
  244. }
  245. }
  246. public Font getFont() {
  247. if (font == null) {
  248. try {
  249. setFont(FONT_1);
  250. } catch (Exception e) {
  251. setFont(new Font("Arial", Font.BOLD, 32));
  252. }
  253. }
  254. return font;
  255. }
  256. public void setFont(Font font) {
  257. this.font = font;
  258. }
  259. public void setFont(int font) throws IOException, FontFormatException {
  260. setFont(font, 32f);
  261. }
  262. public void setFont(int font, float size) throws IOException, FontFormatException {
  263. setFont(font, Font.BOLD, size);
  264. }
  265. public void setFont(int font, int style, float size) throws IOException, FontFormatException {
  266. this.font = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream("/" + FONT_NAMES[font])).deriveFont(style, size);
  267. }
  268. public int getLen() {
  269. return len;
  270. }
  271. public void setLen(int len) {
  272. this.len = len;
  273. }
  274. public int getWidth() {
  275. return width;
  276. }
  277. public void setWidth(int width) {
  278. this.width = width;
  279. }
  280. public int getHeight() {
  281. return height;
  282. }
  283. public void setHeight(int height) {
  284. this.height = height;
  285. }
  286. public int getCharType() {
  287. return charType;
  288. }
  289. public void setCharType(int charType) {
  290. this.charType = charType;
  291. }
  292. }
  293. import java.security.SecureRandom;
  294. public class Randoms {
  295. protected static final SecureRandom RANDOM = new SecureRandom();
  296. // 定义验证码字符.去除了0、O、I、L等容易混淆的字母
  297. public static final char ALPHA[] = {
  298. '2', '3', '4', '5', '6', '7', '8', '9',
  299. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  300. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  301. protected static final int numMaxIndex = 8; // 数字的最大索引,不包括最大值
  302. protected static final int charMinIndex = numMaxIndex; // 字符的最小索引,包括最小值
  303. protected static final int charMaxIndex = ALPHA.length; // 字符的最大索引,不包括最大值
  304. protected static final int upperMinIndex = charMinIndex; // 大写字符最小索引
  305. protected static final int upperMaxIndex = upperMinIndex + 23; // 大写字符最大索引
  306. protected static final int lowerMinIndex = upperMaxIndex; // 小写字母最小索引
  307. protected static final int lowerMaxIndex = charMaxIndex; // 小写字母最大索引
  308. /**
  309. * 产生两个数之间的随机数
  310. *
  311. * @param min 最小值
  312. * @param max 最大值
  313. * @return 随机数
  314. */
  315. public static int num(int min, int max) {
  316. return min + RANDOM.nextInt(max - min);
  317. }
  318. /**
  319. * 产生0-num的随机数,不包括num
  320. *
  321. * @param num 最大值
  322. * @return 随机数
  323. */
  324. public static int num(int num) {
  325. return RANDOM.nextInt(num);
  326. }
  327. /**
  328. * 返回ALPHA中的随机字符
  329. *
  330. * @return 随机字符
  331. */
  332. public static char alpha() {
  333. return ALPHA[num(ALPHA.length)];
  334. }
  335. /**
  336. * 返回ALPHA中第0位到第num位的随机字符
  337. *
  338. * @param num 到第几位结束
  339. * @return 随机字符
  340. */
  341. public static char alpha(int num) {
  342. return ALPHA[num(num)];
  343. }
  344. /**
  345. * 返回ALPHA中第min位到第max位的随机字符
  346. *
  347. * @param min 从第几位开始
  348. * @param max 到第几位结束
  349. * @return 随机字符
  350. */
  351. public static char alpha(int min, int max) {
  352. return ALPHA[num(min, max)];
  353. }
  354. }
  355. import java.io.IOException;
  356. import java.io.OutputStream;
  357. public class Encoder {
  358. private static final int EOF = -1;
  359. // 图片的宽高
  360. private int imgW, imgH;
  361. private byte[] pixAry;
  362. private int initCodeSize; // 验证码位数
  363. private int remaining; // 剩余数量
  364. private int curPixel; // 像素
  365. static final int BITS = 12;
  366. static final int HSIZE = 5003; // 80% 占用率
  367. int n_bits; // number of bits/code
  368. int maxbits = BITS; // user settable max # bits/code
  369. int maxcode; // maximum code, given n_bits
  370. int maxmaxcode = 1 << BITS; // should NEVER generate this code
  371. int[] htab = new int[HSIZE];
  372. int[] codetab = new int[HSIZE];
  373. int hsize = HSIZE; // for dynamic table sizing
  374. int free_ent = 0; // first unused entry
  375. // block compression parameters -- after all codes are used up,
  376. // and compression rate changes, start over.
  377. boolean clear_flg = false;
  378. // Algorithm: use open addressing double hashing (no chaining) on the
  379. // prefix code / next character combination. We do a variant of Knuth's
  380. // algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  381. // secondary probe. Here, the modular division first probe is gives way
  382. // to a faster exclusive-or manipulation. Also do block compression with
  383. // an adaptive reset, whereby the code table is cleared when the compression
  384. // ratio decreases, but after the table fills. The variable-length output
  385. // codes are re-sized at this point, and a special CLEAR code is generated
  386. // for the decompressor. Late addition: construct the table according to
  387. // file size for noticeable speed improvement on small files. Please direct
  388. // questions about this implementation to ames!jaw.
  389. int g_init_bits;
  390. int ClearCode;
  391. int EOFCode;
  392. // output
  393. //
  394. // Output the given code.
  395. // Inputs:
  396. // code: A n_bits-bit integer. If == -1, then EOF. This assumes
  397. // that n_bits =< wordsize - 1.
  398. // Outputs:
  399. // Outputs code to the file.
  400. // Assumptions:
  401. // Chars are 8 bits long.
  402. // Algorithm:
  403. // Maintain a BITS character long buffer (so that 8 codes will
  404. // fit in it exactly). Use the VAX insv instruction to insert each
  405. // code in turn. When the buffer fills up empty it and start over.
  406. int cur_accum = 0;
  407. int cur_bits = 0;
  408. int masks[] =
  409. {
  410. 0x0000,
  411. 0x0001,
  412. 0x0003,
  413. 0x0007,
  414. 0x000F,
  415. 0x001F,
  416. 0x003F,
  417. 0x007F,
  418. 0x00FF,
  419. 0x01FF,
  420. 0x03FF,
  421. 0x07FF,
  422. 0x0FFF,
  423. 0x1FFF,
  424. 0x3FFF,
  425. 0x7FFF,
  426. 0xFFFF};
  427. // Number of characters so far in this 'packet'
  428. int a_count;
  429. // Define the storage for the packet accumulator
  430. byte[] accum = new byte[256];
  431. //----------------------------------------------------------------------------
  432. /**
  433. * @param width 宽度
  434. * @param height 高度
  435. * @param pixels 像素
  436. * @param color_depth 颜色
  437. */
  438. Encoder(int width, int height, byte[] pixels, int color_depth) {
  439. imgW = width;
  440. imgH = height;
  441. pixAry = pixels;
  442. initCodeSize = Math.max(2, color_depth);
  443. }
  444. // Add a character to the end of the current packet, and if it is 254
  445. // characters, flush the packet to disk.
  446. /**
  447. * @param c 字节
  448. * @param outs 输出流
  449. * @throws IOException IO异常
  450. */
  451. void char_out(byte c, OutputStream outs) throws IOException {
  452. accum[a_count++] = c;
  453. if (a_count >= 254)
  454. flush_char(outs);
  455. }
  456. // Clear out the hash table
  457. // table clear for block compress
  458. /**
  459. * @param outs 输出流
  460. * @throws IOException IO异常
  461. */
  462. void cl_block(OutputStream outs) throws IOException {
  463. cl_hash(hsize);
  464. free_ent = ClearCode + 2;
  465. clear_flg = true;
  466. output(ClearCode, outs);
  467. }
  468. // reset code table
  469. /**
  470. * @param hsize int
  471. */
  472. void cl_hash(int hsize) {
  473. for (int i = 0; i < hsize; ++i)
  474. htab[i] = -1;
  475. }
  476. /**
  477. * @param init_bits int
  478. * @param outs 输出流
  479. * @throws IOException IO异常
  480. */
  481. void compress(int init_bits, OutputStream outs) throws IOException {
  482. int fcode;
  483. int i /* = 0 */;
  484. int c;
  485. int ent;
  486. int disp;
  487. int hsize_reg;
  488. int hshift;
  489. // Set up the globals: g_init_bits - initial number of bits
  490. g_init_bits = init_bits;
  491. // Set up the necessary values
  492. clear_flg = false;
  493. n_bits = g_init_bits;
  494. maxcode = MAXCODE(n_bits);
  495. ClearCode = 1 << (init_bits - 1);
  496. EOFCode = ClearCode + 1;
  497. free_ent = ClearCode + 2;
  498. a_count = 0; // clear packet
  499. ent = nextPixel();
  500. hshift = 0;
  501. for (fcode = hsize; fcode < 65536; fcode *= 2)
  502. ++hshift;
  503. hshift = 8 - hshift; // set hash code range bound
  504. hsize_reg = hsize;
  505. cl_hash(hsize_reg); // clear hash table
  506. output(ClearCode, outs);
  507. outer_loop:
  508. while ((c = nextPixel()) != EOF) {
  509. fcode = (c << maxbits) + ent;
  510. i = (c << hshift) ^ ent; // xor hashing
  511. if (htab[i] == fcode) {
  512. ent = codetab[i];
  513. continue;
  514. } else if (htab[i] >= 0) // non-empty slot
  515. {
  516. disp = hsize_reg - i; // secondary hash (after G. Knott)
  517. if (i == 0)
  518. disp = 1;
  519. do {
  520. if ((i -= disp) < 0)
  521. i += hsize_reg;
  522. if (htab[i] == fcode) {
  523. ent = codetab[i];
  524. continue outer_loop;
  525. }
  526. } while (htab[i] >= 0);
  527. }
  528. output(ent, outs);
  529. ent = c;
  530. if (free_ent < maxmaxcode) {
  531. codetab[i] = free_ent++; // code -> hashtable
  532. htab[i] = fcode;
  533. } else
  534. cl_block(outs);
  535. }
  536. // Put out the final code.
  537. output(ent, outs);
  538. output(EOFCode, outs);
  539. }
  540. //----------------------------------------------------------------------------
  541. /**
  542. * @param os 输出流
  543. * @throws IOException IO异常
  544. */
  545. void encode(OutputStream os) throws IOException {
  546. os.write(initCodeSize); // write "initial code size" byte
  547. remaining = imgW * imgH; // reset navigation variables
  548. curPixel = 0;
  549. compress(initCodeSize + 1, os); // compress and write the pixel data
  550. os.write(0); // write block terminator
  551. }
  552. // Flush the packet to disk, and reset the accumulator
  553. /**
  554. * @param outs 输出流
  555. * @throws IOException IO异常
  556. */
  557. void flush_char(OutputStream outs) throws IOException {
  558. if (a_count > 0) {
  559. outs.write(a_count);
  560. outs.write(accum, 0, a_count);
  561. a_count = 0;
  562. }
  563. }
  564. /**
  565. * @param n_bits int
  566. * @return int
  567. */
  568. final int MAXCODE(int n_bits) {
  569. return (1 << n_bits) - 1;
  570. }
  571. //----------------------------------------------------------------------------
  572. // Return the next pixel from the image
  573. //----------------------------------------------------------------------------
  574. /**
  575. * @return int
  576. */
  577. private int nextPixel() {
  578. if (remaining == 0)
  579. return EOF;
  580. --remaining;
  581. byte pix = pixAry[curPixel++];
  582. return pix & 0xff;
  583. }
  584. /**
  585. * @param code int
  586. * @param outs 输出流
  587. * @throws IOException IO异常
  588. */
  589. void output(int code, OutputStream outs) throws IOException {
  590. cur_accum &= masks[cur_bits];
  591. if (cur_bits > 0)
  592. cur_accum |= (code << cur_bits);
  593. else
  594. cur_accum = code;
  595. cur_bits += n_bits;
  596. while (cur_bits >= 8) {
  597. char_out((byte) (cur_accum & 0xff), outs);
  598. cur_accum >>= 8;
  599. cur_bits -= 8;
  600. }
  601. // If the next entry is going to be too big for the code size,
  602. // then increase it, if possible.
  603. if (free_ent > maxcode || clear_flg) {
  604. if (clear_flg) {
  605. maxcode = MAXCODE(n_bits = g_init_bits);
  606. clear_flg = false;
  607. } else {
  608. ++n_bits;
  609. if (n_bits == maxbits)
  610. maxcode = maxmaxcode;
  611. else
  612. maxcode = MAXCODE(n_bits);
  613. }
  614. }
  615. if (code == EOFCode) {
  616. // At EOF, write the rest of the buffer.
  617. while (cur_bits > 0) {
  618. char_out((byte) (cur_accum & 0xff), outs);
  619. cur_accum >>= 8;
  620. cur_bits -= 8;
  621. }
  622. flush_char(outs);
  623. }
  624. }
  625. }
  626. public class Quant {
  627. protected static final int netsize = 256; /* number of colours used */
  628. /* four primes near 500 - assume no image has a length so large */
  629. /* that it is divisible by all four primes */
  630. protected static final int prime1 = 499;
  631. protected static final int prime2 = 491;
  632. protected static final int prime3 = 487;
  633. protected static final int prime4 = 503;
  634. protected static final int minpicturebytes = (3 * prime4);
  635. /* minimum size for input image */
  636. /* Program Skeleton
  637. ----------------
  638. [select samplefac in range 1..30]
  639. [read image from input file]
  640. pic = (unsigned char*) malloc(3*width*height);
  641. initnet(pic,3*width*height,samplefac);
  642. learn();
  643. unbiasnet();
  644. [write output image header, using writecolourmap(f)]
  645. inxbuild();
  646. write output image using inxsearch(b,g,r) */
  647. /* Network Definitions
  648. ------------------- */
  649. protected static final int maxnetpos = (netsize - 1);
  650. protected static final int netbiasshift = 4; /* bias for colour values */
  651. protected static final int ncycles = 100; /* no. of learning cycles */
  652. /* defs for freq and bias */
  653. protected static final int intbiasshift = 16; /* bias for fractions */
  654. protected static final int intbias = (((int) 1) << intbiasshift);
  655. protected static final int gammashift = 10; /* gamma = 1024 */
  656. protected static final int gamma = (((int) 1) << gammashift);
  657. protected static final int betashift = 10;
  658. protected static final int beta = (intbias >> betashift); /* beta = 1/1024 */
  659. protected static final int betagamma =
  660. (intbias << (gammashift - betashift));
  661. /* defs for decreasing radius factor */
  662. protected static final int initrad = (netsize >> 3); /* for 256 cols, radius starts */
  663. protected static final int radiusbiasshift = 6; /* at 32.0 biased by 6 bits */
  664. protected static final int radiusbias = (((int) 1) << radiusbiasshift);
  665. protected static final int initradius = (initrad * radiusbias); /* and decreases by a */
  666. protected static final int radiusdec = 30; /* factor of 1/30 each cycle */
  667. /* defs for decreasing alpha factor */
  668. protected static final int alphabiasshift = 10; /* alpha starts at 1.0 */
  669. protected static final int initalpha = (((int) 1) << alphabiasshift);
  670. protected int alphadec; /* biased by 10 bits */
  671. /* radbias and alpharadbias used for radpower calculation */
  672. protected static final int radbiasshift = 8;
  673. protected static final int radbias = (((int) 1) << radbiasshift);
  674. protected static final int alpharadbshift = (alphabiasshift + radbiasshift);
  675. protected static final int alpharadbias = (((int) 1) << alpharadbshift);
  676. /* Types and Global Variables
  677. -------------------------- */
  678. protected byte[] thepicture; /* the input image itself */
  679. protected int lengthcount; /* lengthcount = H*W*3 */
  680. protected int samplefac; /* sampling factor 1..30 */
  681. // typedef int pixel[4]; /* BGRc */
  682. protected int[][] network; /* the network itself - [netsize][4] */
  683. protected int[] netindex = new int[256];
  684. /* for network lookup - really 256 */
  685. protected int[] bias = new int[netsize];
  686. /* bias and freq arrays for learning */
  687. protected int[] freq = new int[netsize];
  688. protected int[] radpower = new int[initrad];
  689. /* radpower for precomputation */
  690. /* Initialise network in range (0,0,0) to (255,255,255) and set parameters
  691. ----------------------------------------------------------------------- */
  692. public Quant(byte[] thepic, int len, int sample) {
  693. int i;
  694. int[] p;
  695. thepicture = thepic;
  696. lengthcount = len;
  697. samplefac = sample;
  698. network = new int[netsize][];
  699. for (i = 0; i < netsize; i++) {
  700. network[i] = new int[4];
  701. p = network[i];
  702. p[0] = p[1] = p[2] = (i << (netbiasshift + 8)) / netsize;
  703. freq[i] = intbias / netsize; /* 1/netsize */
  704. bias[i] = 0;
  705. }
  706. }
  707. public byte[] colorMap() {
  708. byte[] map = new byte[3 * netsize];
  709. int[] index = new int[netsize];
  710. for (int i = 0; i < netsize; i++)
  711. index[network[i][3]] = i;
  712. int k = 0;
  713. for (int i = 0; i < netsize; i++) {
  714. int j = index[i];
  715. map[k++] = (byte) (network[j][0]);
  716. map[k++] = (byte) (network[j][1]);
  717. map[k++] = (byte) (network[j][2]);
  718. }
  719. return map;
  720. }
  721. /* Insertion sort of network and building of netindex[0..255] (to do after unbias)
  722. ------------------------------------------------------------------------------- */
  723. public void inxbuild() {
  724. int i, j, smallpos, smallval;
  725. int[] p;
  726. int[] q;
  727. int previouscol, startpos;
  728. previouscol = 0;
  729. startpos = 0;
  730. for (i = 0; i < netsize; i++) {
  731. p = network[i];
  732. smallpos = i;
  733. smallval = p[1]; /* index on g */
  734. /* find smallest in i..netsize-1 */
  735. for (j = i + 1; j < netsize; j++) {
  736. q = network[j];
  737. if (q[1] < smallval) {
  738. /* index on g */
  739. smallpos = j;
  740. smallval = q[1]; /* index on g */
  741. }
  742. }
  743. q = network[smallpos];
  744. /* swap p (i) and q (smallpos) entries */
  745. if (i != smallpos) {
  746. j = q[0];
  747. q[0] = p[0];
  748. p[0] = j;
  749. j = q[1];
  750. q[1] = p[1];
  751. p[1] = j;
  752. j = q[2];
  753. q[2] = p[2];
  754. p[2] = j;
  755. j = q[3];
  756. q[3] = p[3];
  757. p[3] = j;
  758. }
  759. /* smallval entry is now in position i */
  760. if (smallval != previouscol) {
  761. netindex[previouscol] = (startpos + i) >> 1;
  762. for (j = previouscol + 1; j < smallval; j++)
  763. netindex[j] = i;
  764. previouscol = smallval;
  765. startpos = i;
  766. }
  767. }
  768. netindex[previouscol] = (startpos + maxnetpos) >> 1;
  769. for (j = previouscol + 1; j < 256; j++)
  770. netindex[j] = maxnetpos; /* really 256 */
  771. }
  772. /* Main Learning Loop
  773. ------------------ */
  774. public void learn() {
  775. int i, j, b, g, r;
  776. int radius, rad, alpha, step, delta, samplepixels;
  777. byte[] p;
  778. int pix, lim;
  779. if (lengthcount < minpicturebytes)
  780. samplefac = 1;
  781. alphadec = 30 + ((samplefac - 1) / 3);
  782. p = thepicture;
  783. pix = 0;
  784. lim = lengthcount;
  785. samplepixels = lengthcount / (3 * samplefac);
  786. delta = samplepixels / ncycles;
  787. alpha = initalpha;
  788. radius = initradius;
  789. rad = radius >> radiusbiasshift;
  790. if (rad <= 1)
  791. rad = 0;
  792. for (i = 0; i < rad; i++)
  793. radpower[i] =
  794. alpha * (((rad * rad - i * i) * radbias) / (rad * rad));
  795. //fprintf(stderr,"beginning 1D learning: initial radius=%d\n", rad);
  796. if (lengthcount < minpicturebytes)
  797. step = 3;
  798. else if ((lengthcount % prime1) != 0)
  799. step = 3 * prime1;
  800. else {
  801. if ((lengthcount % prime2) != 0)
  802. step = 3 * prime2;
  803. else {
  804. if ((lengthcount % prime3) != 0)
  805. step = 3 * prime3;
  806. else
  807. step = 3 * prime4;
  808. }
  809. }
  810. i = 0;
  811. while (i < samplepixels) {
  812. b = (p[pix + 0] & 0xff) << netbiasshift;
  813. g = (p[pix + 1] & 0xff) << netbiasshift;
  814. r = (p[pix + 2] & 0xff) << netbiasshift;
  815. j = contest(b, g, r);
  816. altersingle(alpha, j, b, g, r);
  817. if (rad != 0)
  818. alterneigh(rad, j, b, g, r); /* alter neighbours */
  819. pix += step;
  820. if (pix >= lim)
  821. pix -= lengthcount;
  822. i++;
  823. if (delta == 0)
  824. delta = 1;
  825. if (i % delta == 0) {
  826. alpha -= alpha / alphadec;
  827. radius -= radius / radiusdec;
  828. rad = radius >> radiusbiasshift;
  829. if (rad <= 1)
  830. rad = 0;
  831. for (j = 0; j < rad; j++)
  832. radpower[j] =
  833. alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
  834. }
  835. }
  836. //fprintf(stderr,"finished 1D learning: final alpha=%f !\n",((float)alpha)/initalpha);
  837. }
  838. /* Search for BGR values 0..255 (after net is unbiased) and return colour index
  839. ---------------------------------------------------------------------------- */
  840. public int map(int b, int g, int r) {
  841. int i, j, dist, a, bestd;
  842. int[] p;
  843. int best;
  844. bestd = 1000; /* biggest possible dist is 256*3 */
  845. best = -1;
  846. i = netindex[g]; /* index on g */
  847. j = i - 1; /* start at netindex[g] and work outwards */
  848. while ((i < netsize) || (j >= 0)) {
  849. if (i < netsize) {
  850. p = network[i];
  851. dist = p[1] - g; /* inx key */
  852. if (dist >= bestd)
  853. i = netsize; /* stop iter */
  854. else {
  855. i++;
  856. if (dist < 0)
  857. dist = -dist;
  858. a = p[0] - b;
  859. if (a < 0)
  860. a = -a;
  861. dist += a;
  862. if (dist < bestd) {
  863. a = p[2] - r;
  864. if (a < 0)
  865. a = -a;
  866. dist += a;
  867. if (dist < bestd) {
  868. bestd = dist;
  869. best = p[3];
  870. }
  871. }
  872. }
  873. }
  874. if (j >= 0) {
  875. p = network[j];
  876. dist = g - p[1]; /* inx key - reverse dif */
  877. if (dist >= bestd)
  878. j = -1; /* stop iter */
  879. else {
  880. j--;
  881. if (dist < 0)
  882. dist = -dist;
  883. a = p[0] - b;
  884. if (a < 0)
  885. a = -a;
  886. dist += a;
  887. if (dist < bestd) {
  888. a = p[2] - r;
  889. if (a < 0)
  890. a = -a;
  891. dist += a;
  892. if (dist < bestd) {
  893. bestd = dist;
  894. best = p[3];
  895. }
  896. }
  897. }
  898. }
  899. }
  900. return (best);
  901. }
  902. public byte[] process() {
  903. learn();
  904. unbiasnet();
  905. inxbuild();
  906. return colorMap();
  907. }
  908. /* Unbias network to give byte values 0..255 and record position i to prepare for sort
  909. ----------------------------------------------------------------------------------- */
  910. public void unbiasnet() {
  911. int i, j;
  912. for (i = 0; i < netsize; i++) {
  913. network[i][0] >>= netbiasshift;
  914. network[i][1] >>= netbiasshift;
  915. network[i][2] >>= netbiasshift;
  916. network[i][3] = i; /* record colour no */
  917. }
  918. }
  919. /* Move adjacent neurons by precomputed alpha*(1-((i-j)^2/[r]^2)) in radpower[|i-j|]
  920. --------------------------------------------------------------------------------- */
  921. protected void alterneigh(int rad, int i, int b, int g, int r) {
  922. int j, k, lo, hi, a, m;
  923. int[] p;
  924. lo = i - rad;
  925. if (lo < -1)
  926. lo = -1;
  927. hi = i + rad;
  928. if (hi > netsize)
  929. hi = netsize;
  930. j = i + 1;
  931. k = i - 1;
  932. m = 1;
  933. while ((j < hi) || (k > lo)) {
  934. a = radpower[m++];
  935. if (j < hi) {
  936. p = network[j++];
  937. try {
  938. p[0] -= (a * (p[0] - b)) / alpharadbias;
  939. p[1] -= (a * (p[1] - g)) / alpharadbias;
  940. p[2] -= (a * (p[2] - r)) / alpharadbias;
  941. } catch (Exception e) {
  942. } // prevents 1.3 miscompilation
  943. }
  944. if (k > lo) {
  945. p = network[k--];
  946. try {
  947. p[0] -= (a * (p[0] - b)) / alpharadbias;
  948. p[1] -= (a * (p[1] - g)) / alpharadbias;
  949. p[2] -= (a * (p[2] - r)) / alpharadbias;
  950. } catch (Exception e) {
  951. }
  952. }
  953. }
  954. }
  955. /* Move neuron i towards biased (b,g,r) by factor alpha
  956. ---------------------------------------------------- */
  957. protected void altersingle(int alpha, int i, int b, int g, int r) {
  958. /* alter hit neuron */
  959. int[] n = network[i];
  960. n[0] -= (alpha * (n[0] - b)) / initalpha;
  961. n[1] -= (alpha * (n[1] - g)) / initalpha;
  962. n[2] -= (alpha * (n[2] - r)) / initalpha;
  963. }
  964. /* Search for biased BGR values
  965. ---------------------------- */
  966. protected int contest(int b, int g, int r) {
  967. /* finds closest neuron (min dist) and updates freq */
  968. /* finds best neuron (min dist-bias) and returns position */
  969. /* for frequently chosen neurons, freq[i] is high and bias[i] is negative */
  970. /* bias[i] = gamma*((1/netsize)-freq[i]) */
  971. int i, dist, a, biasdist, betafreq;
  972. int bestpos, bestbiaspos, bestd, bestbiasd;
  973. int[] n;
  974. bestd = ~(((int) 1) << 31);
  975. bestbiasd = bestd;
  976. bestpos = -1;
  977. bestbiaspos = bestpos;
  978. for (i = 0; i < netsize; i++) {
  979. n = network[i];
  980. dist = n[0] - b;
  981. if (dist < 0)
  982. dist = -dist;
  983. a = n[1] - g;
  984. if (a < 0)
  985. a = -a;
  986. dist += a;
  987. a = n[2] - r;
  988. if (a < 0)
  989. a = -a;
  990. dist += a;
  991. if (dist < bestd) {
  992. bestd = dist;
  993. bestpos = i;
  994. }
  995. biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));
  996. if (biasdist < bestbiasd) {
  997. bestbiasd = biasdist;
  998. bestbiaspos = i;
  999. }
  1000. betafreq = (freq[i] >> betashift);
  1001. freq[i] -= betafreq;
  1002. bias[i] += (betafreq << gammashift);
  1003. }
  1004. freq[bestpos] += beta;
  1005. bias[bestpos] -= betagamma;
  1006. return (bestbiaspos);
  1007. }
  1008. }
  1009. import java.awt.*;
  1010. import java.awt.image.BufferedImage;
  1011. import java.awt.image.DataBufferByte;
  1012. import java.io.*;
  1013. /**
  1014. * Gif生成工具
  1015. * Class AnimatedGifEncoder - Encodes a GIF file consisting of one or
  1016. * more frames.
  1017. * <pre>
  1018. * Example:
  1019. * AnimatedGifEncoder e = new AnimatedGifEncoder();
  1020. * e.start(outputFileName);
  1021. * e.setDelay(1000); // 1 frame per sec
  1022. * e.addFrame(image1);
  1023. * e.addFrame(image2);
  1024. * e.finish();
  1025. * </pre>
  1026. * No copyright asserted on the source code of this class. May be used
  1027. * for any purpose, however, refer to the Unisys LZW patent for restrictions
  1028. * on use of the associated Encoder class. Please forward any corrections
  1029. * to questions at fmsware.com.
  1030. */
  1031. public class GifEncoder {
  1032. protected int width; // image size
  1033. protected int height;
  1034. protected Color transparent = null; // transparent color if given
  1035. protected int transIndex; // transparent index in color table
  1036. protected int repeat = -1; // no repeat
  1037. protected int delay = 0; // frame delay (hundredths)
  1038. protected boolean started = false; // ready to output frames
  1039. protected OutputStream out;
  1040. protected BufferedImage image; // current frame
  1041. protected byte[] pixels; // BGR byte array from frame
  1042. protected byte[] indexedPixels; // converted frame indexed to palette
  1043. protected int colorDepth; // number of bit planes
  1044. protected byte[] colorTab; // RGB palette
  1045. protected boolean[] usedEntry = new boolean[256]; // active palette entries
  1046. protected int palSize = 7; // color table size (bits-1)
  1047. protected int dispose = -1; // disposal code (-1 = use default)
  1048. protected boolean closeStream = false; // close stream when finished
  1049. protected boolean firstFrame = true;
  1050. protected boolean sizeSet = false; // if false, get size from first frame
  1051. protected int sample = 10; // default sample interval for quantizer
  1052. /**
  1053. * Sets the delay time between each frame, or changes it
  1054. * for subsequent frames (applies to last frame added).
  1055. *
  1056. * @param ms int delay time in milliseconds
  1057. */
  1058. public void setDelay(int ms) {
  1059. delay = Math.round(ms / 10.0f);
  1060. }
  1061. /**
  1062. * Sets the GIF frame disposal code for the last added frame
  1063. * and any subsequent frames. Default is 0 if no transparent
  1064. * color has been set, otherwise 2.
  1065. *
  1066. * @param code int disposal code.
  1067. */
  1068. public void setDispose(int code) {
  1069. if (code >= 0) {
  1070. dispose = code;
  1071. }
  1072. }
  1073. /**
  1074. * Sets the number of times the set of GIF frames
  1075. * should be played. Default is 1; 0 means play
  1076. * indefinitely. Must be invoked before the first
  1077. * image is added.
  1078. *
  1079. * @param iter int number of iterations.
  1080. */
  1081. public void setRepeat(int iter) {
  1082. if (iter >= 0) {
  1083. repeat = iter;
  1084. }
  1085. }
  1086. /**
  1087. * Sets the transparent color for the last added frame
  1088. * and any subsequent frames.
  1089. * Since all colors are subject to modification
  1090. * in the quantization process, the color in the final
  1091. * palette for each frame closest to the given color
  1092. * becomes the transparent color for that frame.
  1093. * May be set to null to indicate no transparent color.
  1094. *
  1095. * @param c Color to be treated as transparent on display.
  1096. */
  1097. public void setTransparent(Color c) {
  1098. transparent = c;
  1099. }
  1100. /**
  1101. * Adds next GIF frame. The frame is not written immediately, but is
  1102. * actually deferred until the next frame is received so that timing
  1103. * data can be inserted. Invoking <code>finish()</code> flushes all
  1104. * frames. If <code>setSize</code> was not invoked, the size of the
  1105. * first image is used for all subsequent frames.
  1106. *
  1107. * @param im BufferedImage containing frame to write.
  1108. * @return true if successful.
  1109. */
  1110. public boolean addFrame(BufferedImage im) {
  1111. if ((im == null) || !started) {
  1112. return false;
  1113. }
  1114. boolean ok = true;
  1115. try {
  1116. if (!sizeSet) {
  1117. // use first frame's size
  1118. setSize(im.getWidth(), im.getHeight());
  1119. }
  1120. image = im;
  1121. getImagePixels(); // convert to correct format if necessary
  1122. analyzePixels(); // build color table & map pixels
  1123. if (firstFrame) {
  1124. writeLSD(); // logical screen descriptior
  1125. writePalette(); // global color table
  1126. if (repeat >= 0) {
  1127. // use NS app extension to indicate reps
  1128. writeNetscapeExt();
  1129. }
  1130. }
  1131. writeGraphicCtrlExt(); // write graphic control extension
  1132. writeImageDesc(); // image descriptor
  1133. if (!firstFrame) {
  1134. writePalette(); // local color table
  1135. }
  1136. writePixels(); // encode and write pixel data
  1137. firstFrame = false;
  1138. } catch (IOException e) {
  1139. ok = false;
  1140. }
  1141. return ok;
  1142. }
  1143. //added by alvaro
  1144. public boolean outFlush() {
  1145. boolean ok = true;
  1146. try {
  1147. out.flush();
  1148. return ok;
  1149. } catch (IOException e) {
  1150. ok = false;
  1151. }
  1152. return ok;
  1153. }
  1154. public byte[] getFrameByteArray() {
  1155. return ((ByteArrayOutputStream) out).toByteArray();
  1156. }
  1157. /**
  1158. * Flushes any pending data and closes output file.
  1159. * If writing to an OutputStream, the stream is not
  1160. * closed.
  1161. *
  1162. * @return boolean
  1163. */
  1164. public boolean finish() {
  1165. if (!started) return false;
  1166. boolean ok = true;
  1167. started = false;
  1168. try {
  1169. out.write(0x3b); // gif trailer
  1170. out.flush();
  1171. if (closeStream) {
  1172. out.close();
  1173. }
  1174. } catch (IOException e) {
  1175. ok = false;
  1176. }
  1177. return ok;
  1178. }
  1179. public void reset() {
  1180. // reset for subsequent use
  1181. transIndex = 0;
  1182. out = null;
  1183. image = null;
  1184. pixels = null;
  1185. indexedPixels = null;
  1186. colorTab = null;
  1187. closeStream = false;
  1188. firstFrame = true;
  1189. }
  1190. /**
  1191. * Sets frame rate in frames per second. Equivalent to
  1192. * <code>setDelay(1000/fps)</code>.
  1193. *
  1194. * @param fps float frame rate (frames per second)
  1195. */
  1196. public void setFrameRate(float fps) {
  1197. if (fps != 0f) {
  1198. delay = Math.round(100f / fps);
  1199. }
  1200. }
  1201. /**
  1202. * Sets quality of color quantization (conversion of images
  1203. * to the maximum 256 colors allowed by the GIF specification).
  1204. * Lower values (minimum = 1) produce better colors, but slow
  1205. * processing significantly. 10 is the default, and produces
  1206. * good color mapping at reasonable speeds. Values greater
  1207. * than 20 do not yield significant improvements in speed.
  1208. *
  1209. * @param quality int greater than 0.
  1210. */
  1211. public void setQuality(int quality) {
  1212. if (quality < 1) quality = 1;
  1213. sample = quality;
  1214. }
  1215. /**
  1216. * Sets the GIF frame size. The default size is the
  1217. * size of the first frame added if this method is
  1218. * not invoked.
  1219. *
  1220. * @param w int frame width.
  1221. * @param h int frame width.
  1222. */
  1223. public void setSize(int w, int h) {
  1224. if (started && !firstFrame) return;
  1225. width = w;
  1226. height = h;
  1227. if (width < 1) width = 320;
  1228. if (height < 1) height = 240;
  1229. sizeSet = true;
  1230. }
  1231. /**
  1232. * Initiates GIF file creation on the given stream. The stream
  1233. * is not closed automatically.
  1234. *
  1235. * @param os OutputStream on which GIF images are written.
  1236. * @return false if initial write failed.
  1237. */
  1238. public boolean start(OutputStream os) {
  1239. if (os == null) return false;
  1240. boolean ok = true;
  1241. closeStream = false;
  1242. out = os;
  1243. try {
  1244. writeString("GIF89a"); // header
  1245. } catch (IOException e) {
  1246. ok = false;
  1247. }
  1248. return started = ok;
  1249. }
  1250. /**
  1251. * Initiates writing of a GIF file with the specified name.
  1252. *
  1253. * @param file String containing output file name.
  1254. * @return false if open or initial write failed.
  1255. */
  1256. public boolean start(String file) {
  1257. boolean ok = true;
  1258. try {
  1259. out = new BufferedOutputStream(new FileOutputStream(file));
  1260. ok = start(out);
  1261. closeStream = true;
  1262. } catch (IOException e) {
  1263. ok = false;
  1264. }
  1265. return started = ok;
  1266. }
  1267. /**
  1268. * Analyzes image colors and creates color map.
  1269. */
  1270. protected void analyzePixels() {
  1271. int len = pixels.length;
  1272. int nPix = len / 3;
  1273. indexedPixels = new byte[nPix];
  1274. Quant nq = new Quant(pixels, len, sample);
  1275. // initialize quantizer
  1276. colorTab = nq.process(); // create reduced palette
  1277. // convert map from BGR to RGB
  1278. for (int i = 0; i < colorTab.length; i += 3) {
  1279. byte temp = colorTab[i];
  1280. colorTab[i] = colorTab[i + 2];
  1281. colorTab[i + 2] = temp;
  1282. usedEntry[i / 3] = false;
  1283. }
  1284. // map image pixels to new palette
  1285. int k = 0;
  1286. for (int i = 0; i < nPix; i++) {
  1287. int index =
  1288. nq.map(pixels[k++] & 0xff,
  1289. pixels[k++] & 0xff,
  1290. pixels[k++] & 0xff);
  1291. usedEntry[index] = true;
  1292. indexedPixels[i] = (byte) index;
  1293. }
  1294. pixels = null;
  1295. colorDepth = 8;
  1296. palSize = 7;
  1297. // get closest match to transparent color if specified
  1298. if (transparent != null) {
  1299. transIndex = findClosest(transparent);
  1300. }
  1301. }
  1302. /**
  1303. * Returns index of palette color closest to c
  1304. *
  1305. * @param c color
  1306. * @return int
  1307. */
  1308. protected int findClosest(Color c) {
  1309. if (colorTab == null) return -1;
  1310. int r = c.getRed();
  1311. int g = c.getGreen();
  1312. int b = c.getBlue();
  1313. int minpos = 0;
  1314. int dmin = 256 * 256 * 256;
  1315. int len = colorTab.length;
  1316. for (int i = 0; i < len; ) {
  1317. int dr = r - (colorTab[i++] & 0xff);
  1318. int dg = g - (colorTab[i++] & 0xff);
  1319. int db = b - (colorTab[i] & 0xff);
  1320. int d = dr * dr + dg * dg + db * db;
  1321. int index = i / 3;
  1322. if (usedEntry[index] && (d < dmin)) {
  1323. dmin = d;
  1324. minpos = index;
  1325. }
  1326. i++;
  1327. }
  1328. return minpos;
  1329. }
  1330. /**
  1331. * Extracts image pixels into byte array "pixels"
  1332. */
  1333. protected void getImagePixels() {
  1334. int w = image.getWidth();
  1335. int h = image.getHeight();
  1336. int type = image.getType();
  1337. if ((w != width)
  1338. || (h != height)
  1339. || (type != BufferedImage.TYPE_3BYTE_BGR)) {
  1340. // create new image with right size/format
  1341. BufferedImage temp =
  1342. new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
  1343. Graphics2D g = temp.createGraphics();
  1344. g.drawImage(image, 0, 0, null);
  1345. image = temp;
  1346. }
  1347. pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
  1348. }
  1349. /**
  1350. * Writes Graphic Control Extension
  1351. *
  1352. * @throws IOException IO异常
  1353. */
  1354. protected void writeGraphicCtrlExt() throws IOException {
  1355. out.write(0x21); // extension introducer
  1356. out.write(0xf9); // GCE label
  1357. out.write(4); // data block size
  1358. int transp, disp;
  1359. if (transparent == null) {
  1360. transp = 0;
  1361. disp = 0; // dispose = no action
  1362. } else {
  1363. transp = 1;
  1364. disp = 2; // force clear if using transparent color
  1365. }
  1366. if (dispose >= 0) {
  1367. disp = dispose & 7; // user override
  1368. }
  1369. disp <<= 2;
  1370. // packed fields
  1371. out.write(0 | // 1:3 reserved
  1372. disp | // 4:6 disposal
  1373. 0 | // 7 user input - 0 = none
  1374. transp); // 8 transparency flag
  1375. writeShort(delay); // delay x 1/100 sec
  1376. out.write(transIndex); // transparent color index
  1377. out.write(0); // block terminator
  1378. }
  1379. /**
  1380. * Writes Image Descriptor
  1381. *
  1382. * @throws IOException IO异常
  1383. */
  1384. protected void writeImageDesc() throws IOException {
  1385. out.write(0x2c); // image separator
  1386. writeShort(0); // image position x,y = 0,0
  1387. writeShort(0);
  1388. writeShort(width); // image size
  1389. writeShort(height);
  1390. // packed fields
  1391. if (firstFrame) {
  1392. // no LCT - GCT is used for first (or only) frame
  1393. out.write(0);
  1394. } else {
  1395. // specify normal LCT
  1396. out.write(0x80 | // 1 local color table 1=yes
  1397. 0 | // 2 interlace - 0=no
  1398. 0 | // 3 sorted - 0=no
  1399. 0 | // 4-5 reserved
  1400. palSize); // 6-8 size of color table
  1401. }
  1402. }
  1403. /**
  1404. * Writes Logical Screen Descriptor
  1405. *
  1406. * @throws IOException IO异常
  1407. */
  1408. protected void writeLSD() throws IOException {
  1409. // logical screen size
  1410. writeShort(width);
  1411. writeShort(height);
  1412. // packed fields
  1413. out.write((0x80 | // 1 : global color table flag = 1 (gct used)
  1414. 0x70 | // 2-4 : color resolution = 7
  1415. 0x00 | // 5 : gct sort flag = 0
  1416. palSize)); // 6-8 : gct size
  1417. out.write(0); // background color index
  1418. out.write(0); // pixel aspect ratio - assume 1:1
  1419. }
  1420. /**
  1421. * Writes Netscape application extension to define
  1422. * repeat count.
  1423. *
  1424. * @throws IOException IO异常
  1425. */
  1426. protected void writeNetscapeExt() throws IOException {
  1427. out.write(0x21); // extension introducer
  1428. out.write(0xff); // app extension label
  1429. out.write(11); // block size
  1430. writeString("NETSCAPE" + "2.0"); // app id + auth code
  1431. out.write(3); // sub-block size
  1432. out.write(1); // loop sub-block id
  1433. writeShort(repeat); // loop count (extra iterations, 0=repeat forever)
  1434. out.write(0); // block terminator
  1435. }
  1436. /**
  1437. * Writes color table
  1438. *
  1439. * @throws IOException IO异常
  1440. */
  1441. protected void writePalette() throws IOException {
  1442. out.write(colorTab, 0, colorTab.length);
  1443. int n = (3 * 256) - colorTab.length;
  1444. for (int i = 0; i < n; i++) {
  1445. out.write(0);
  1446. }
  1447. }
  1448. /**
  1449. * Encodes and writes pixel data
  1450. *
  1451. * @throws IOException IO异常
  1452. */
  1453. protected void writePixels() throws IOException {
  1454. Encoder encoder = new Encoder(width, height, indexedPixels, colorDepth);
  1455. encoder.encode(out);
  1456. }
  1457. /**
  1458. * Write 16-bit value to output stream, LSB first
  1459. *
  1460. * @param value int
  1461. * @throws IOException IO异常
  1462. */
  1463. protected void writeShort(int value) throws IOException {
  1464. out.write(value & 0xff);
  1465. out.write((value >> 8) & 0xff);
  1466. }
  1467. /**
  1468. * Writes string to output stream
  1469. *
  1470. * @param s string
  1471. * @throws IOException IO异常
  1472. */
  1473. protected void writeString(String s) throws IOException {
  1474. for (int i = 0; i < s.length(); i++) {
  1475. out.write((byte) s.charAt(i));
  1476. }
  1477. }
  1478. }

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,173人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java生成图片验证

    功能介绍:自定义图片尺寸和字符长度,随机背景颜色和字符颜色,随机字符偏移角度,字符平滑边缘,干扰线,噪点,背景扭曲。 VerifyCodeUtils类,生成图片流,然后不同框

    相关 动态生成验证

    动态生成验证码在很多地方可以用到,最近在学习牛腩视频的时候,正好看到了,就此简单总结一下。 为了简单方便,我们新建一个验证码测试的项目名为test,然后在项目中新建一个文件夹

    相关 生成图片验证

    问题描述 在项目中遇到有人恶意拉取图片资源,无限刷资源,导致阿里图片服务器流量暴涨(钱遭不住),使得带宽一直处于上限,正常用户不能好的访问。 解决办法 这个功能设