ZXing 배치를 사용하여 준비된 카드 배경 이미지의 지정된 위치에서 QR 코드를 생성하고 지정된 텍스트 내용 (링크 주소, 텍스트 등)을 배치하고 해당 위치에 배치하고 마지막으로 카드 번호를 추가하십시오.
단계:
1). 아래 그림과 같이 배경 사진을 만드십시오.
2). QR 코드 BufferedImage 객체를 생성합니다. 코드는 다음과 같습니다.
/ ** * * * @title : TobufferedImage * @description : 텍스트를 QR 코드로 변환 이미지 객체 * @param 텍스트 * QR 코드 내용 * @param width * qr 코드 높이 * @param 높이 * @param width * @param * @param Exception * @return bufferedimage return */ public static extrow (strow), Intstation (bublofferdimage). 높이)은 예외를 던지고 {int black = 0xff000000; int white = 0xffffffff; hashtable <encodehinttype, object> hints = new hashtable <encodehinttype, object> (); hints.put (encodehinttype.character_set, "utf-8"); // 컨텐츠에서 사용하는 문자 세트 인코딩은 hints.put (encodeHintType.Margin, 1); bitmatrix matrix = new multiformatwriter (). encode (텍스트, barcodeformat.qr_code, 너비, 높이, 힌트); BufferedImage image = 새로운 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); }} 반환 이미지; }3). 카드 배경 이미지의 지정된 위치에서 QR 코드를 생성하면 코드는 다음과 같습니다.
/ ** * * @title : markImageByCode * @Description : 이미지의 지정된 위치에 QR 코드 추가 * @param img * qr 코드 이미지 객체 * @param srcimgpath * 배경 이미지 * @param targetpath * target map * @param positionwidth * 위치 수평 코디네이트 * @param positionheight * @retor void void void return void return * @param positionheight * @param positionwidth * MarkImageByCode (Image IMG, String SrcImgPath, String TargetPath, int positionWidth, int positionHeight) {outputStream os = null; try {image srcimg = imageio.read (새 파일 (srcimgpath)); bufferedImage buffimg = new bufferedImage (srcimg.getWidth (null), srcimg.getheight (null), bufferedImage.type_int_rgb); // 1. 브러시 개체를 가져옵니다. graphics2d g = buffimg.creategraphics (); // 2. 라인 세그먼트 G.SetRenderingHint (renderingHints.Key_InterPolation, renderingHints.Value_InterPolation_BiLinear)의 제기 에지 처리를 설정합니다. G.DrawImage (srcimg.getScaledInstance (srcimg.getWidth (null), srcimg.getheight (null), image.scale_smooth), 0, 0, null); g.setcomposite (alphacomposite.getinstance (alphacomposite.src_atop, alpha)); // 3. QR 코드 위치 G.DrawImage (IMG, 위치 위, 위치 하이이트, NULL); g.setcomposite (alphacomposite.getinstance (alphacomposite.src_over)); // 4. 자원 g.dispose ()를 해제합니다. // 5. 이미지 생성 (PNG를 생성하는 것이 좋습니다. imageio.write (buffimg, "png", os); System.out.println ( "QR 코드 이미지 생성 성공"); } catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (null! = os) os.close (); } catch (예외 e) {e.printstacktrace (); }}} 4). 카드 번호를 카드에 추가하십시오
/ ** * * * @title : pressText * @Description : 이미지의 지정된 위치에 텍스트 추가 * @param presstext * 텍스트 내용 * @param srcimagefile * original image * @param destimagefile * target image * @param x * 수평 좌표 * @param y * vertical codernatine * @param alpha * transparency * @return void void void return void void return * @the void void void return * @param alpha * @param x * @param x * @param x * void pressText (String pressText, String srcImageFile, String destimageFile, int x, int y, float alpha) {try {file img = new File (srcimageFile); image src = imageio.read (img); int width = src.getWidth (null); int height = src.getheight (null); BufferedImage image = 새로운 BufferedImage (너비, 높이, BufferedImage.type_int_rgb); Graphics2d g = image.creategraphics (); // 텍스트를 제거하기 위해 텍스트를 열기 텍스트 g.setRenderingHint (renderinghints.key_text_antialiasing, renderinghints.value_text_antialias_on); G.DrawImage (SRC, 0, 0, 너비, 높이, 널); // 색상 G.SetColor를 설정합니다 (새 색상 (89, 87, 87)); // font g.setfont 세트 (new font ( "Fangzheng lanting black_gbk", font.bold, 14); g.setcomposite (alphacomposite.getinstance (alphacomposite.src_atop, alpha)); // 첫 번째 매개 변수 -> 컨텐츠를 설정하고 다음 두 매개 변수 -> 그림에서 텍스트의 좌표 위치 (x, y). G.DrawString (pressText, X, y); g.dispose (); imageio.write ((bufferedImage) image, "png", 새 파일 (destimageFile)); // 파일 스트림으로의 출력} catch (예외 e) {e.printstacktrace (); }} 예:
암호:
테스트 코드
public class codetest {public static void main (String [] args)은 예외 {string text = "http://www.xxx.com/"; // QR 코드 컨텐츠 // QR 코드 생성 // 디렉토리를 저장하려면 이미지 QR 코드 생성 targetpath = "f :/qrcode/targetimg/" + utils.tostr (); // 디렉토리 생성 UTILS.MAKEDIRS (TargetPath); int begin = 100; // 코드 시작 번호 int end = 101; // 코드 종료 번호 (int i = 시작; i <= end; i ++) {// 날짜로 16 자리 숫자를 생성합니다. // QR 코드 객체를 가져옵니다. BufferedImage image = utils.tobufferedImage (text + "? paycode =" + code, 240,240); // 배경 이미지 + QR 코드 UTILS.MarkImageByCode (이미지, "f : /qrcode/srcimg/srcimg/srcimg/src.png", targetpath + "/" + code + ".png", 340, 160)가있는 스탠딩 카드 사진을 생성합니다. // 스탠딩 카드의 코드 번호를 그림 Utils.PressText (Code, TargetPath + "/" + code + ".png", targetpath + "/" + code + ".png", 390, 417, 0.5f); } // QR 코드 생성}}} 효과:
배치 생성 된 이미지 렌더링은 다음과 같습니다
배치 사진 :
Utils 코드 :
패키지 cn.utils.code; java.awt.alphacomposite import; import java.awt.color; Java.awt.Font 가져 오기; import java.awt.graphics2d; import java.awt.image; Java.awt.RenderingHints 가져 오기; java.awt.image.bufferedimage import; import java.io.file; import java.io.fileoutputStream; import java.io.outputStream; import java.text.decimalformat; import java.text.simpledateformat; import java.util.date; java.util.hashtable import; import javax.imageio.imageio; import com.google.zxing.barcodeformat; import com.google.zxing.encodehinttype; import com.google.zxing.multiformatwriter; import com.google.zxing.common.bitmatrix; /** 도구 수업. */ public acc 개인 정적 플로트 알파 = 1f; / ** * * * @title : TobufferedImage * @description : 텍스트를 QR 코드로 변환 이미지 객체 * @param 텍스트 * QR 코드 내용 * @param width * qr 코드 높이 * @param 높이 * @param width * @param * @param Exception * @return bufferedimage return */ public static extrow (strow), Intstation (bublofferdimage). 높이)은 예외를 던지고 {int black = 0xff000000; int white = 0xffffffff; hashtable <encodehinttype, object> hints = new hashtable <encodehinttype, object> (); hints.put (encodehinttype.character_set, "utf-8"); // 컨텐츠에서 사용하는 문자 세트 인코딩은 hints.put (encodeHintType.Margin, 1); bitmatrix matrix = new multiformatwriter (). encode (텍스트, barcodeformat.qr_code, 너비, 높이, 힌트); BufferedImage image = 새로운 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); }} 반환 이미지; } / ** * * @title : markImageByCode * @Description : 이미지의 지정된 위치에 QR 코드 추가 * @Param IMG * QR 코드 객체 * @param srcimgpath * 배경 이미지 * @param targetpath * target 맵 * @param positionwidth * @param positionheight * @rettion void void type * @ethort void reply * @ethertoun void reply * @param positionwidth *. void MarkImageByCode (이미지 img, 문자열 srcimgpath, 문자열 targetpath, int positionwidth, int positionHeight) {outputStream os = null; try {image srcimg = imageio.read (새 파일 (srcimgpath)); bufferedImage buffimg = new bufferedImage (srcimg.getWidth (null), srcimg.getheight (null), bufferedImage.type_int_rgb); // 1. 브러시 개체를 가져옵니다. graphics2d g = buffimg.creategraphics (); // 2. 라인 세그먼트 G.SetRenderingHint (renderingHints.Key_InterPolation, renderingHints.Value_InterPolation_BiLinear)의 제기 에지 처리를 설정합니다. G.DrawImage (srcimg.getScaledInstance (srcimg.getWidth (null), srcimg.getheight (null), image.scale_smooth), 0, 0, null); g.setcomposite (alphacomposite.getinstance (alphacomposite.src_atop, alpha)); // 3. QR 코드 위치 G.DrawImage (IMG, 위치 위, 위치 하이이트, NULL); g.setcomposite (alphacomposite.getinstance (alphacomposite.src_over)); // 4. 자원 g.dispose ()를 해제합니다. // 5. 이미지 생성 (PNG를 생성하는 것이 좋습니다. imageio.write (buffimg, "png", os); System.out.println ( "QR 코드 이미지 생성 성공"); } catch (예외 e) {e.printstacktrace (); } 마침내 {try {if (null! = os) os.close (); } catch (예외 e) {e.printstacktrace (); }}} /**** @title : pressText* @description : 이미지의 지정된 위치에 텍스트 추가* @param presstext* @param srcimagefile* original image* @param destimagefile* target image* @param x* horizontal coordinate* void type* @param alpha alpha alpha alpha alpha */ public final static void pressText (String pressText, String srcImageFile, String destimageFile, int x, int y, float alpha) {try {file img = new File (srcimageFile); image src = imageio.read (img); int width = src.getWidth (null); int height = src.getheight (null); BufferedImage image = 새로운 BufferedImage (너비, 높이, BufferedImage.type_int_rgb); Graphics2d g = image.creategraphics (); // 텍스트를 제거하기 위해 텍스트를 열기 텍스트 g.setRenderingHint (renderinghints.key_text_antialiasing, renderinghints.value_text_antialias_on); G.DrawImage (SRC, 0, 0, 너비, 높이, 널); // 색상 G.SetColor를 설정합니다 (새 색상 (89, 87, 87)); // font g.setfont 세트 (new font ( "Fangzheng lanting black_gbk", font.bold, 14); g.setcomposite (alphacomposite.getinstance (alphacomposite.src_atop, alpha)); // 첫 번째 매개 변수 -> 설정 내용, 다음 두 매개 변수 -> 이미지 (x, y)의 텍스트 좌표 위치. G.DrawString (pressText, X, y); g.dispose (); imageio.write ((bufferedImage) 이미지, "png", 새 파일 (destimageFile)); // 파일 스트림으로의 출력} catch (예외 e) {e.printstacktrace (); }} // DATE to String/** 형식 날짜를 문자열로 형식, 기본 형식은 yyyy-mm-dd hh : mm : ss입니다. 기본 날짜는 현재 날짜입니다. */ public static string tostr () {return tostr (df_dateTime); } /** 형식 날짜를 문자열로, 형식은 매개 변수 형식으로 지정된 형식이며, 기본 날짜는 현재 날짜이고 형식 값은이 클래스의 상수에서 사용하거나 사용자 정의 할 수 있습니다. */ public static string tostr (문자열 형식) {return tostr (format, new date ()); } /** 형식 날짜를 문자열로 형식, 기본 형식은 yyyy-mm-dd hh : mm : ss입니다. 날짜는 매개 변수 날짜에 지정됩니다. */ public static string tostr (날짜 날짜) {return tostr (df_dateTime, date); } /** DATE를 문자열로 형식으로, 형식은 매개 변수 형식으로 지정되며 날짜는 매개 변수 날짜로 지정됩니다. 형식 값은이 클래스의 상수에서 사용하거나 사용자 정의 할 수 있습니다. */ public static string toStr (문자열 형식, 날짜 날짜) {return new simpledateformat (format) .format (날짜); } public static string formatnumber (int num) {decimalformat df = new Decimalformat ( "000000"); 문자열 str2 = df.format (num); 리턴 str2; } public static string formatnumber (int num) {decimalformat df = new Decimalformat ( "000000"); 문자열 str2 = df.format (num); 리턴 str2; } public static boolean makedirs (String filepath) {file folder = new File (FilePath); return (folder.exists () && folder.isdirectory ())? true : 폴더 .mkdirs (); }} 사용 된 기술 :
1. ZXing 도구를 사용하여 QR 코드를 생성하십시오.
1) 다운로드 주소 : http://repo1.maven.org/maven2/com/google/zxing/javase/3.1.0/
2) .maven 구성
<pectionency> <groupid> com.google.zxing </groupid> <artifactid> core </artifactid> <bersion> 2.2 </version> </fectionency>
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.