下面列出了怎么用com.google.zxing.client.j2se.BufferedImageLuminanceSource的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 解析二维码 (ZXing)
*
* @param file 二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 条形码解码
*
* @param imgPath
* @return String
*/
public static String decode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 二维码解码
*
* @param imgPath
* @return String
*/
public static String decode2(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 读取二维码图片
*
* @param path
* @return
* @throws Exception
*/
public static String read(String path) throws Exception {
File file = new File(path);
BufferedImage image;
image = ImageIO.read(file);
if (Objects.isNull(image)) {
throw new RuntimeException("无法读取源文件");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
@SuppressWarnings("rawtypes")
EnumMap<DecodeHintType, String> hints = Maps.newEnumMap(DecodeHintType.class);
//解码设置编码方式为:utf-8
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
/**
* 读取二维码内容
*
* @param filePath 二维码路径
* @return
*/
public static String decodeQR(String filePath) {
String retStr = "";
if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) {
return "图片路径为空!";
}
try {
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap<>();
hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap);
retStr = result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return retStr;
}
/**
* 图片解析
*/
protected ShadowSocksDetailsEntity parseURL(String imgURL) throws IOException, NotFoundException {
Connection.Response resultImageResponse = getConnection(imgURL).execute();
Map<DecodeHintType, Object> hints = new LinkedHashMap<>();
// 解码设置编码方式为:utf-8,
hints.put(DecodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
//优化精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//复杂模式,开启PURE_BARCODE模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
try (BufferedInputStream bytes = resultImageResponse.bodyStream()) {
BufferedImage image = ImageIO.read(bytes);
Binarizer binarizer = new HybridBinarizer(new BufferedImageLuminanceSource(image));
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Result res = new MultiFormatReader().decode(binaryBitmap, hints);
return parseLink(res.toString());
}
}
/**
* 图片解析
*/
protected ShadowSocksDetailsEntity parseImg(String imgURL) throws IOException, NotFoundException {
String str = StringUtils.removeFirst(imgURL, "data:image/png;base64,");
Map<DecodeHintType, Object> hints = new LinkedHashMap<>();
// 解码设置编码方式为:utf-8,
hints.put(DecodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
//优化精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//复杂模式,开启PURE_BARCODE模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
try (ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(str))) {
BufferedImage image = ImageIO.read(bis);
Binarizer binarizer = new HybridBinarizer(new BufferedImageLuminanceSource(image));
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Result res = new MultiFormatReader().decode(binaryBitmap, hints);
return parseLink(res.toString());
}
}
/**
* 读二维码并输出携带的信息
*/
public static void readQrCode(InputStream inputStream) throws IOException {
//从输入流中获取字符串信息
BufferedImage image = ImageIO.read(inputStream);
//将图像转换为二进制位图源
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(bitmap);
} catch (ReaderException e) {
e.printStackTrace();
}
System.out.println(result.getText());
}
/**
* 解析二维码
*
* @param file
* 二维码图片
* @return
* @throws Exception
*/
public static String decode(InputStream in) throws Exception {
BufferedImage image = ImageIO.read(in);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
in.close();
return resultStr;
}
/**
* 条形码解码
*
* @param imgPath
* @return String
*/
public static String decode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 二维码解码
*
* @param imgPath
* @return String
*/
public static String decode2(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Decode all barcodes in the image
*/
private String multiple(BufferedImage img) throws NotFoundException, ChecksumException, FormatException {
long begin = System.currentTimeMillis();
LuminanceSource source = new BufferedImageLuminanceSource(img);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
com.google.zxing.Reader reader = new MultiFormatReader();
MultipleBarcodeReader bcReader = new GenericMultipleBarcodeReader(reader);
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
StringBuilder sb = new StringBuilder();
for (Result result : bcReader.decodeMultiple(bitmap, hints)) {
sb.append(result.getText()).append(" ");
}
SystemProfiling.log(null, System.currentTimeMillis() - begin);
log.trace("multiple.Time: {}", System.currentTimeMillis() - begin);
return sb.toString();
}
public static String decode(BufferedImage image) {
// convert the image to a binary bitmap source
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
// decode the barcode
QRCodeReader reader = new QRCodeReader();
try {
@SuppressWarnings("rawtypes")
Hashtable hints = new Hashtable();
Result result = reader.decode(bitmap, hints);
return result.getText();
} catch (ReaderException e) {
// the data is improperly formatted
}
return "";
}
public static String decode(BufferedImage image) {
// convert the image to a binary bitmap source
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
// decode the barcode
QRCodeReader reader = new QRCodeReader();
try {
@SuppressWarnings("rawtypes")
Hashtable hints = new Hashtable();
Result result = reader.decode(bitmap, hints);
return result.getText();
} catch (ReaderException e) {
// the data is improperly formatted
}
return "";
}
/**
* 生成BinaryBitmap
* @param inputStream 输入流
* @return
* @throws IOException
*/
private static BinaryBitmap createBinaryBitmap(InputStream inputStream) throws IOException {
BufferedImage bufferedImage = ImageIO.read(inputStream);
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
return new BinaryBitmap(binarizer);
}
public static String decode(InputStream in) throws Exception {
BufferedImage image = ImageIO.read(in);
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);// 对图像进行解码
return result.getText();
}
/**
* 解码
*
* @param filePath
* @return
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static String decode(String filePath) throws IOException, NotFoundException {
BufferedImage image = ImageIO.read(new File(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
/**
* 解析 qrcode 图片
*
* @param paramDTO qrcode 参数
* @return
*/
public static String decode(BarcodeParamDTO paramDTO) {
try {
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(paramDTO.getFilepath()));
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
Result result = new MultiFormatReader().decode(bitmap, paramDTO.getDecodeHints());
return result.getText();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String decode(InputStream input)
throws IOException, NotFoundException {
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
new BufferedImageLuminanceSource(
ImageIO.read(input))));
Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap);
return qrCodeResult.getText();
}
@Override
public String read(InputStream inputStream) {
try {
String string = reader.decode(new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(
ImageIO.read(inputStream))))).getText();
inputStream.close();
return string;
} catch (Throwable e) {
logger.warn(e, "读取二维码图片内容时发生异常!");
return null;
}
}
/**
* 解码 QRCode 图片,解析出其内容
*
* @param imageURI QRCode 图片 URI
* @return 解析后的内容
* @throws IOException
*/
public static String decodeQRCodeImage(URI imageURI) throws IOException {
BufferedImage bufferedImage = ImageReader.readImage(imageURI);
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
try {
Result result = reader.decode(bitmap);
return result.getText();
} catch (ReaderException e) {
e.printStackTrace();
}
return "";
}
/**
* Decode only one barcode
*/
@SuppressWarnings("unused")
private String simple(BufferedImage img) throws NotFoundException, ChecksumException, FormatException {
long begin = System.currentTimeMillis();
LuminanceSource source = new BufferedImageLuminanceSource(img);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
com.google.zxing.Reader reader = new MultiFormatReader();
Result result = reader.decode(bitmap);
SystemProfiling.log(null, System.currentTimeMillis() - begin);
log.trace("simple.Time: {}", System.currentTimeMillis() - begin);
return result.getText();
}
/**
* 解析QRCode二维码
*/
@SuppressWarnings("unchecked")
public static void decode(File file) {
try {
BufferedImage image;
try {
image = ImageIO.read(file);
if (image == null) {
System.out.println("Could not decode image");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
@SuppressWarnings("rawtypes")
Hashtable hints = new Hashtable();
//解码设置编码方式为:utf-8
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
System.out.println("解析后内容:" + resultStr);
} catch (IOException ioe) {
System.out.println(ioe.toString());
} catch (ReaderException re) {
System.out.println(re.toString());
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
@Test
public void testQRWorks() throws Exception {
HttpGet getRequest = new HttpGet(httpServerUrl + clientPair.token + "/qr");
String cloneToken;
try (CloseableHttpResponse response = httpclient.execute(getRequest)) {
assertEquals(200, response.getStatusLine().getStatusCode());
assertEquals("image/png", response.getFirstHeader("Content-Type").getValue());
byte[] data = EntityUtils.toByteArray(response.getEntity());
assertNotNull(data);
//get the data from the input stream
BufferedImage image = ImageIO.read(new ByteArrayInputStream(data));
//convert the image to a binary bitmap source
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result result = reader.decode(bitmap);
String resultString = result.getText();
assertTrue(resultString.startsWith("blynk://token/clone/"));
assertTrue(resultString.endsWith("?server=127.0.0.1&port=10443"));
cloneToken = resultString.substring(
resultString.indexOf("blynk://token/clone/") + "blynk://token/clone/".length(),
resultString.indexOf("?server=127.0.0.1&port=10443"));
assertEquals(32, cloneToken.length());
}
clientPair.appClient.send("getProjectByCloneCode " + cloneToken);
DashBoard dashBoard = clientPair.appClient.parseDash(1);
assertEquals("My Dashboard", dashBoard.name);
}
@Override
public void run() {
try {
if (!webCam.isOpen())
webCam.open();
isRunning = true;
Result result;
BufferedImage bufferedImage;
while (isRunning) {
bufferedImage = webCam.getImage();
if (bufferedImage != null) {
WritableImage writableImage = SwingFXUtils.toFXImage(bufferedImage, null);
imageView.setImage(writableImage);
imageView.setRotationAxis(new Point3D(0.0, 1.0, 0.0));
imageView.setRotate(180.0);
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
try {
result = new MultiFormatReader().decode(bitmap);
isRunning = false;
String qrCode = result.getText();
UserThread.execute(() -> resultHandler.accept(qrCode));
} catch (NotFoundException ignore) {
// No qr code in image...
}
}
}
} catch (Throwable t) {
log.error(t.toString());
} finally {
webCam.close();
}
}
private static String getQRCodeImageRawText(Path path) throws IOException, NotFoundException {
Map<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
try(FileInputStream fis = new FileInputStream(path.toFile())) {
BufferedImage bi = ImageIO.read(fis);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bi)));
Result result = new MultiFormatReader().decode(binaryBitmap, hints);
return result.getText();
}
}
public static Result decodeQrCodeFile(String filePath) throws IOException, NotFoundException {
MultiFormatReader formatReader = new MultiFormatReader();
File file = new File(filePath);
BufferedImage image = ImageIO.read(file);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
return formatReader.decode(binaryBitmap, hints);
}
/**
* 读取二维码
* @param file 二维码源
* @throws Exception
*/
private static void readCode(File file) throws Exception{
BufferedImage encodedBufferedImage = ImageIO.read(file) ;
LuminanceSource source = new BufferedImageLuminanceSource(encodedBufferedImage);
Result result = new QRCodeReader().decode(new BinaryBitmap(new HybridBinarizer(source)));
System.out.println(result.getText());
}
private BinaryBitmap readToBitmap(final byte[] imageBytes) throws IOException {
BufferedImage inputImage = ImageIO.read(new ByteArrayInputStream(imageBytes));
BufferedImageLuminanceSource luminanceSource = new BufferedImageLuminanceSource(inputImage);
HybridBinarizer binarizer = new HybridBinarizer(luminanceSource);
return new BinaryBitmap(binarizer);
}
@FXML
@Override
public void startAction() {
if (imageView.getImage() == null) {
return;
}
try {
synchronized (this) {
if (task != null) {
return;
}
task = new SingletonTask<Void>() {
private Result result;
@Override
protected boolean handle() {
try {
LuminanceSource source = new BufferedImageLuminanceSource(
SwingFXUtils.fromFXImage(imageView.getImage(), null));
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
result = new MultiFormatReader().decode(bitmap, hints);
return result != null;
} catch (Exception e) {
error = e.toString();
return false;
}
}
@Override
protected void whenSucceeded() {
String s = "---------" + message("Contents") + "---------\n"
+ result.getText()
+ "\n\n---------" + message("MetaData") + "---------\n"
+ message("Type") + ": "
+ result.getBarcodeFormat().name();
if (result.getResultMetadata() != null) {
for (ResultMetadataType type : result.getResultMetadata().keySet()) {
Object value = result.getResultMetadata().get(type);
switch (type) {
case PDF417_EXTRA_METADATA:
// PDF417ResultMetadata pdf417meta
// = (PDF417ResultMetadata) result.getResultMetadata().get(ResultMetadataType.PDF417_EXTRA_METADATA);
break;
case BYTE_SEGMENTS:
s += "\n" + message("BYTE_SEGMENTS") + ": ";
for (byte[] bytes : (List<byte[]>) value) {
s += ByteTools.bytesToHexFormat(bytes) + " ";
}
break;
default:
s += "\n" + message(type.name()) + ": " + value;
}
}
}
result.getTimestamp();
codeInput.setText(s);
}
};
openHandlingStage(task, Modality.WINDOW_MODAL);
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();
}
} catch (Exception e) {
logger.error(e.toString());
}
}