java利用qrcode.jar進行處理二維碼,生成、解析二維碼
阿新 • • 發佈:2019-02-02
首先,這裡貼出jar。
生成二維碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package
test.weima2;
import
java.awt.Color;
import
java.awt.Graphics2D;
import
java.awt.image.BufferedImage; import
java.io.File;
import
javax.imageio.ImageIO;
import
com.swetake.util.Qrcode;
public
class QRCodeEncoderTest {
public
static void
main(String[] args) throws
Exception {
Qrcode qrcode= new
Qrcode();
qrcode.setQrcodeErrorCorrect( 'M' );
qrcode.setQrcodeEncodeMode( 'B' );
qrcode.setQrcodeVersion( 7 );
String testString =
"我是中國人" ;
byte [] d =testString.getBytes( "GBK" );
BufferedImage bi =
new BufferedImage( 139 ,
139 , BufferedImage.TYPE_INT_RGB);
// createGraphics
Graphics2D g = bi.createGraphics();
// set background
g.setBackground(Color.WHITE);
g.clearRect( 0 ,
0 , 139 ,
139 );
g.setColor(Color.BLACK);
if
(d.length> 0
&& d.length < 123 ){
boolean [][] b = qrcode.calQrcode(d);
for
( int
i= 0 ;i<b.length;i++){
for
( int
j= 0 ;j<b.length;j++){
if
(b[j][i]) {
g.fillRect(j* 3 + 2 ,i* 3 + 2 , 3 , 3 );
}
}
}
}
g.dispose();
bi.flush();
String FilePath= "TestQRCode.png" ;
File f =
new File(FilePath);
ImageIO.write(bi,
"png" , f);
System.out.println( "doned!" );
}
}
|
解析二維碼圖片:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
package
test.weima2;
import
java.awt.image.BufferedImage;
import
java.io.File;
import
java.io.IOException;
import
java.io.UnsupportedEncodingException;
import
javax.imageio.ImageIO;
import
jp.sourceforge.qrcode.QRCodeDecoder;
import
jp.sourceforge.qrcode.data.QRCodeImage;
import
jp.sourceforge.qrcode.exception.DecodingFailedException;
public
class QRCodeDecoderTest {
public
QRCodeDecoderTest() {
}
// ����
public
static void
main(String[] args) {
QRCodeDecoder decoder =
new QRCodeDecoder();
File imageFile =
new File( "TestQRCode.png" );
BufferedImage image =
null ;
try
{
image = ImageIO.read(imageFile);
}
catch (IOException e) {
System.out.println( "Error: " + e.getMessage());
}
try
{
String decodedData =
new String(decoder.decode( new
J2SEImage(image)), "GBK" );
System.out.println(decodedData);
}
catch (DecodingFailedException dfe) {
System.out.println( "Error: "
+ dfe.getMessage());
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
class
J2SEImage implements
QRCodeImage {
BufferedImage image;
public
J2SEImage(BufferedImage image) {
this .image = image;
}
public
int getWidth() {
return
image.getWidth();
}
public
int getHeight() {
return
image.getHeight();
}
public
int getPixel( int
x, int
y) {
return
image.getRGB(x, y);
}
}
|