由於某些原因需要做一堆二維碼
需求:
- 需求生成帶鏈接的url
- 每個鏈接具有相同的請求頭和唯一的特徵值
- 批量寫入本地
實現
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.junit.Test;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
public class QRDomain {
@Test
public void create() throws WriterException, IOException{
/**
* 定義基本參數
*/
String imagePath = "d://qrs//";
String imageName = null;
int width = 100;
int height = 100;
String format = "jpg";
String contents = "http://localhost:8080/WebQR/CommonServlet?method=query&code=";
// System.out.println(content);
/**
* 位圖矩陣
*/
for(int i = 100 ; i < 150 ; i++){
String str = "1A"+getTime()+getUid();
System.out.println("str : " + str +" : " + str.length());
imageName = ""+i+".jpg";
Map<EncodeHintType , Object> hints = new HashMap<EncodeHintType , Object>();
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents+str, BarcodeFormat.QR_CODE, width, height ,hints);
Path path = FileSystems.getDefault().getPath(imagePath, imageName);
MatrixToImageWriter.writeToPath(bitMatrix, format, path);
}
System.out.println("over");
}
@Test
public void decode(){
// System.out.println(getUid());
String file = "D://qrs//46.jpg";
BufferedImage image;
try {
image = ImageIO.read(new File(file));
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 對圖像進行解碼
System.out.println("encode: " + result.getBarcodeFormat());
System.out.println(new Timestamp(result.getTimestamp()) );
System.out.println(result.getText());
System.out.println(result.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
private String getTime(){
String str = "170220";
return str;
}
private String getUid(){
String id = UUID.randomUUID().toString();
id = id.replaceAll("-", "");
return id.substring(0, 8);
}
}
測試 和 解析
測試成功
項目依賴
需要zxing-core和zxing-javase點擊我下載