Ensine você passo a passo usando o Java Design para gerar códigos QR
Na era da Internet das Coisas, os códigos QR são uma coisa muito importante. Agora, não importa o que você seja, você precisa obter um logotipo de código QR. Por medo de ficar desatualizado, você não pode usar o código QR para identificá -lo. Talvez um dia a certidão de nascimento ou o livro de registro doméstico seja identificado com um código QR. Hoje eu estava por um capricho e vi que outros haviam adicionado códigos QR aos seus blogs, e também queria fazer um teste.
É usado principalmente para alcançar dois pontos:
1. Gere um código QR com qualquer texto.
2. Adicione uma imagem no meio do código QR.
1. Trabalho de preparação.
Prepare o pacote Core QR Código 3.0 QR e uma imagem JPG.
Faça o download do pacote de código QR QR.
Primeiro, tenho que baixar o pacote zxing.jar. Estou usando o pacote principal de 3.0 aqui
Endereço para download: Agora ele foi transferido para o Github: https://github.com/zxing/zxing/wiki/Getting-Started-Developing,
Obviamente, você também pode fazer o download do pacote JAR do Maven Repository: http://central.maven.org/maven2/com/google/zxing/core/
2. Programação
1. Inicie o Eclipse, crie um novo projeto Java e encontre o nome do projeto (neste exemplo, nomeie -o qrcodesoft). Clique em Avançar:
2. Importe o pacote zxing.jar. Estou usando o pacote principal do 3.0 aqui: clique em "Adicionar jarro externo (x) ...".
3. Crie duas novas classes, a saber:
BufferImagelumumensource.java
Qrcodeutil.java
Os códigos -chave são: BufferImageluminâncias
BufferImagelumumensource.java Código do programa:
pacote com.yihaomen.barcode; importar java.awt.graphics2d; importar java.awt.geom.affineTransform; importar java.awt.image.bufferImage; importação de impressão final; BufferImagelumumensource (imagem bufferedImage) {this (imagem, 0, 0, image.getwidth (), image.getHeight ());} public bufferImageluminAncesource (bufferImage imagem; largura> fonte de largura || topo+altura> fonte de peso) {tire nova ilegalArgumentException ("retângulo de cultivo não se encaixa nos dados da imagem."); {image.setrgb (x, y, 0xffffff); // = White}}} this.image = new BufferImage (SourceWidth, SourceHeight, bufferImage.type_byte_gray); this.image.getgraphics (). drawImage (image, 0, 0, null); this.left = esquerdo; this.top = top;} public byte [] getHeight ()) {tire nova ilegalArgumentException ("Linha solicitada está fora da imagem:" + y);} int width = getWidth (); if (line == null || line.length <widthathatel) {line = newtyte [width];} image.getRaster (). getMatrix () {int width = getWidth (); int alting = getHeight (); int area = width * altura; byte [] matrix = new byte [área]; image.getRaster (). topo, int largura, int altura) {Retorne o novo bufferImagelumumensource (imagem, this.left + esquerda, this.top + topo, largura, altura);} public boolean isrotatesupportd () {return true;} public luminâncias transform = novo afineTransform (0,0, -1,0, 1,0, 0,0, largura -fonte); tampão giratedImage = new BufferEdImage (fonteHeight, SourceWidth, bufferImage.type_byte_gray); graphics2d g = rotatedImage.creategraphics (); g.drawimage); imageNeNeNeN; getwidth (); retorna new -bufferiMageluminânciasQrcodeutil.java Código do programa:
pacote com.yihaomen.barcode; importar java.awt.basicsTroke; importar java.awt.graphics; importar java.awt.graphics2d; importar java.awt.ImAffEn; java.io.file; importar java.io.OutputStream; importar java.util.hashtable; importar java.util.random; importar javax.imageio.imageio; importhithytempmap.zxing.Barcformat; importância com.google.zxing.binaryMap; com.google.zxing.encodehinttype; importar com.google.zxing.multiformatreader; importar com.google.zxing.multiformatwriter; import com.google.zxing.result; import com.google.zxing.common.bitmatrix; import.google; com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;/** * QR code tool class* */public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "JPG";// QR code size private static final int QRCODE_SIZE = 300;// LOGO width private static final int WIDTH = 60; // Altura do logotipo estático privado estático final int = 60; private estático bufferImage CreateImage (conteúdo da string, string imgpath, boolean NeedCompress) lança exceção {hashtable <EncodeHintType, object> hints = new Hashtable <codehnttype, object> (); hints.put (scodehtyhttyPe. ErrorCorrectionLevel.h); hints.put (codehnttype.character_set, charset); hints.put (codehnttype.margin, 1); bitMatrix bitMatrix = new MultInFalMAtWriter (). bitMatrix.getwidth (); int alting = bitMatrix.getHeight (); bufferImage imagem = new bufferiMage (largura, altura, bufferImage.type_int_rgb); para (int x = 0; x <largura; x ++) {for (int y = 0; y <altura; y ++) {image.setrgb (x, y, bitMatrix.get (x, y)? 0xff000000: 0xfffffff); NeedCompress); retornar imagem;}/** * inserir logotipo * * @param fonte * qr código imagem * @param imgpath * logotipo endereço de imagem * @param necessitchpress * se você deve compactar * @throws excepção */private static void insertImage (arquivo bufferImage, string string, boolean); {System.err.println (""+imgPath+"Este arquivo não existe!"); Return;} imagem src = imageio.read (novo arquivo (imgpath)); int width = src.getwidth (null); int alting = src.geth (null); if (nestompress) {/ compra); > Altura) {altura = altura;} imagem imagem = src.getScalEdInstance (largura, altura, imagem.scale_smooth); tag bufferedimage = new bufferImage (largura, altura, bufferImage.type_int_rgb); graphics g = tag.getraphics (); g.drawimage (image_rgb); graphics g = tag. // desenhe o gráfico reduzido g.dispose (); src = image;} // insira logographics2d graph = fonte.creategraphics (); int x = (qrcode_size - largura)/ 2; int y = (qrcode_size - altura)/ 2; graf.rwimage (sc, x, y, y, y, y) RoundRectangle2d.float (x, y, largura, largura, 6, 6); gráfico.SetStroke (new BasicStroke (3f)); graf.draw (shape); graf.dispose ();}/** * gere o código qr (logotificado) compactar logotipo * @throws exceção */public static void cody (conteúdo da string, string imgpath, string DestPath, boolean NeedCompress) lança exceção {bufferedImage imagem = qrcodeutil.createImage (content, imgpath, needcompress); mkdirs (destath); string = new) Random (). NextInt (999999999)+". (Se o diretório pai não existir, uma exceção será lançada) * @Author Lanyuan * E-mail: [email protected] * @date 2013-12-11 10:16:36 am * @param destath store diretório */public static void mkdirs (string destath) {arquivo de arquivo = // Quando a pasta não existe, o MKDIRS criará automaticamente diretórios de várias camadas, que são diferentes do MKDIR. (MKDIR lançará uma exceção se o diretório pai não existir) se (! file.exists () &&! file.isdirectory ()) {file.mkdirs ();}}/** * gene código qr (logothPath) @) @param content * @param * @param * storerPath * storerPath * @storerPerk String imgpath, string destath) lança exceção {qrcodeutil.encode (content, imgpath, DestPath, false);}/** * gerar código QR * * @param content * @param destath *) endereço de armazenamento * @param needcompress * compressa o logotipo * @throws Exceção */public static sancal {QRCodeUtil.encode(content, null, destPath, needCompress);}/** * Generate QR code* * @param content * Content* @param destPath * Storage address* @throws Exception */public static void encode(String content, String destPath) throws Exception {QRCodeUtil.encode(content, null, destPath, false);}/** * Generate QR code (embedded Logo) * * @param content * content * @param imgpath * endereço do logotipo * @param saída * fluxo de saída * @param NeedCompress * se deve compactar logotipo * @throws exceção */public static void Encode (string content, string imgpath, saída de saída, saída, boolean NeedcomPress) lança a exceção {bufferedimage image = QREPTILTILTILTIL.CROTIL.CRIMAGE, a imagem, a imagem, a saída de string, a saída de saída, a saída de saída, a saída, a saída bolean) lança a exceção {bufferImpath) NeedCompress); imageio.Write (imagem, format_name, saída);}/** * Gere o código QR * * @Param Content * Content * @Param Output Freead * Stream * @Throws Exception */public static void Encode (String Content, saída de saída) lança excepção {qrcodeutil.EnDoDE (conteúdo, null, null, null, null, null, output, output Output) lança excepção {qrcodeutil.EnDoDe (conteúdo, null, null, null, null, null, output, outputpatur) lança excepção {qrcodeUtil.EnDoDe (conteúdo, null, null, null, null, null, null; Imagem * @return * @throws Exceção */public static string decode (arquivo de arquivo) lança a exceção {bufferedImage imagem; imagem = imageio.read (arquivo); if (imagem == null) {return null;} bufferImageLumMancesource Source = newBlueMagEluminaCanche (imagem); resultado; hashtable <decodehInttype, objeto> dicas = novo hashtable <decodehinttype, object> (); hints.put (decodehnttype.character_set, charset); result = result = result *TeRtErt*. @Param Path * Código QR Endereço da imagem * @return * @THOWS Exceção */public static string decode (caminho da string) lança Exceção {return qrcodeutil.decode (new File (caminho);} public static void main (string [] args) lança excepção {string text = "http://www.yihaom" "; "c: /me.jpg", "c:/barcode", true);}}Gerar código QR sem logotipo
O código do programa é o seguinte:
public static void main (string [] args) lança exceção {string text = "http://www.dans88.com.cn"; Qrcodeutil.encode (text, "", "d:/myworkdoc", true);}Execute este método de teste e o código QR gerado não possui um logotipo, o estilo é o seguinte:
Se você estiver interessado, pode digitalizar com seu telefone
Gerar um código QR com um logotipo
Logotipo Você pode usar seu próprio avatar ou uma imagem que você gosta e usar o código a seguir, o código do programa é o seguinte:
public static void main (string [] args) lança exceção {string text = "http://www.dans88.com.cn"; Qrcodeutil.encode (Text, "d: /myworkdoc/my180.jpg", "d:/myworkdoc", true); }A única diferença é que o endereço do logotipo é especificado na base anterior e os arquivos de imagem do disco C são usados aqui.
Digitalize com o seu telefone celular e o texto que você deseja aparecer pode aparecer. Clique para inserir seu próprio site.
O exposto acima é usar o design Java para gerar códigos QR. Amigos interessados podem se referir a ele. Obrigado pelo seu apoio a este site!