このブログは、プロジェクトに画像検証コードの実装を記録します。それはあまり複雑ではありませんが、良い記憶は悪いペンほど良くありません。覚えておいてください!
パッケージcom.zl.util; java.awt.colorをインポートします。 java.awt.fontをインポートします。 java.awt.graphicsをインポートします。 java.awt.image.bufferedimageをインポートします。 java.io.fileoutputStreamをインポートします。 java.io.ioexceptionをインポートします。 java.io.outputStreamをインポートします。 java.util.randomをインポートします。 javax.imageio.imageioをインポートします。 /** * @author ZZC * @date November 6, 2017* @param * @desc Graphic verification code generation* */ public class VerifyUtil { // Verification code character set private static final char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd'、 'e'、 'f'、 'g' '、' '、' '' '' '' '' '' '' '' ''、 'o'、 'p'、 'r'、 's'、 't'、 'u'、 'v'、 'w'、 'y' '、' '' '' '' '' '' '' '' '' '' f '' '' '、 'g'、 'h'、 'i' '' '' '' '' '' '、' k '、' l '、' m '、' n '、o'、 'p'、 'q'、 'r'、 's'、 't'、 'v'、 'w'、 'x'、 ''、 'z'}; //文字数プライベート静的最終int size = 4; //干渉線の数private static final int lines = 5; //幅private static final int width = 80; //高さプライベート静的最終int height = 40; //フォントサイズプライベート静的最終int font_size = 30; /***ランダム検証コードとpicture* Object [0]:検証コード文字列。 *オブジェクト[1]:検証コード画像。 */ public static object [] createimage(){stringbuffer sb = new StringBuffer(); // 1。空白の画像を作成するbufferedimage image = new BufferedImage(幅、高さ、bufferedimage.type_int_rgb); // 2。画像ブラシグラフィックグラフィック= image.getGraphics()を取得します。 //3。ブラシカラーグラフィックスを設定します。SetColor(color.light_gray); //4。長方形の背景グラフィックを描画します。 // 5。ランダム文字を描くランダムran = new Random(); for(int i = 0; i <size; i ++){//ランダム文字インデックスint n = ran.nextint(chars.length); //ランダムカラーGraphic.setColor(getRandomColor())を設定します。 //フォントサイズのグラフィックを設定します。SetFont(new Font(null、font.bold + font.italic、font_size)); //文字graghic.drawstring(chars [n] + ""、i * width/ size、height * 2/3)を描く; //文字sb.append(chars [n]); } //6。(int i = 0; i <lines; i ++){//ランダムカラーグラフィック.setcolor(getRandomColor());の干渉線を描画します。 //ランダムカラーGraphic.drawline(ran.nextint(width)、ran.nextint(height)、ran.nextint(width)、ran.nextint(height)); } // 7。検証コードを返し、画像新しいオブジェクトを返します[] {sb.toString()、image}; } / ***ランダムカラー* / public static color getRandomColor(){random ran = new Random();色= new Color(ran.nextint(256)、ran.nextint(256)、ran.nextint(256));色を返します。 } public static void main(string [] args)throws ioexception {object [] objs = createimage(); bufferedimage画像=(bufferedimage)objs [1]; outputStream os = new fileoutputStream( "d:/1.png"); Imageio.write(image、 "png"、os); os.close(); }}コントローラーレイヤー
/** * @Author ZZC * @Date 2017年11月6日 * @Param * @DESCグラフィック検証コード生成方法 * */@RequestMapping( "/valicode")public void valicode(httpservletresponse応答、httpsessionセッション)スロー例外object [] objs = verifyutil.createimage(); //検証コードをセッションセッションに保存します。SetAttribute( "ImageCode"、objs [0]); //画像をブラウザに出力しますBufferEdImage画像=(bufferedImage)objs [1]; Response.setContentType( "Image/PNG"); outputStream os = response.getOutputStream(); Imageio.write(image、 "png"、os); }
実行結果:
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。