導入
Gooleのzxingパッケージが主に使用されています。以下はサンプルコードで、誰もが理解して学習するのに非常に便利です。コードは予備的なフレームワークに属し、機能を備えており、実際の使用法に応じて改善および最適化する必要があります。
ステップ1:MavenインポートZxing
<Dependency> GroupId> com.google.zxing </groupid> <artifactid> core </artifactid> <version> 3.2.1 </version> </dependency>
ステップ2:QRコードの生成を開始します:
プライベート静的最終int black = 0xff000000; private static final int white = 0xffffffff;/***生成されたQRコードを画像に保存* @Param Matrix QRコードクラス* @return*/public static bufferedimage tobufferedimage(bitmatrix matrix){int width.getwidt(); int height = matrix.getheight(); bufferedimage image = new BufferedImage(幅、高さ、bufferedimage.type_int_rgb); for(int x = 0; x <width; x ++){for(int y = 0; y <height; y ++){image.setrgb(x、y、matrix.get(x、y)?black:white); }} return image;}/*** qrコードを生成し、ファイルに書き込み* @paramコンテンツqrコードのコンテンツをスキャンします* @param形式の画像形式Jpg* @paramファイル* @throws例外*/public static void writetofile(string content、rigning format、file file)throws exception @suppresswarnings( "rawTypes")マップヒント= new Hashmap(); // utf-8を設定して、中国の文字化けヒントを防ぐ。 // QRコードの周りの白い領域のサイズを設定します。 // QRコードのフォールトトレランスを設定します。 // QRコードBitMatrix BitMatrix = multiformatwriter.encode(content、barcodeformat.qr_code、width、height、hints)を描画します。 bufferedimage image = tobufferedimage(bitmatrix); if(!imageio.write(image、format、file)){throw new ioexception( "format" + format + "to" + file); }}ステップ3:テキストをQRコード画像に書き込みます:
/*** QRコード画像にテキストを追加* @Param PressText Text* @Param QRFILE QR CODE FILE* @PARAM FONTSTYLE* @PARAM COLOR* @PARAM FONTSIZE*/PUBLIC STATIC VOID PRESSTEXT(STRING PRESSTEXT(STRING PRESSTEXT)、FILE QRFILE、INT FONTSTYLE、COLOR、INT FONTEXT) 「UTF-8」);画像src = imageio.read(qrfile); int imagew = src.getWidth(null); int imageh = src.getheight(null); bufferedimage image = new bufferedimage(imagew、mageh、bufferedimage.type_int_rgb);グラフィックg = image.creategraphics(); G.Drawimage(SRC、0、0、ImageW、ImageH、Null); //ブラシG.setColor(色)の色を設定します。 //フォントフォントフォント= new Font( "安安"、fontstyle、fontsize); fontmetrics metrics = g.getFontmetrics(font); //写真のテキストの座標は、ここで中央に設定されていますint startx =(width -metrics.stringwidth(presstext)) /2; int starty = height/2; G.SetFont(Font); G.DrawString(PressText、StartX、Starty); g.dispose(); fileoutputStream out = new fileoutputStream(qrfile); Imageio.write(image、 "jpeg"、out); out.close(); System.out.println( "Image Press Success");}
ステップ4:主な方法でテストし、中央にテキストを含むQRコードが生成されます
public static void main(string [] args)throws exception {file qrcfile = new file( "/users/deweixu/"、 "google.jpg"); writetofile( "www.google.com.hk"、 "jpg"、qrcfile); PressText( "Google"、qrcfile、5、color.red、32);}要約します
上記は、この記事のコンテンツ全体です。この記事の内容があなたの研究や仕事に役立つことを願っています。ご質問がある場合は、メッセージを残してコミュニケーションをとることができます。