/** * Reads image from file and returns its BitMatrix. This function * will return null whenever the resource file cannot be found or read. * * @param resourceName * @return * @throws IOException if resourceName cannot be opened. * @throws NotFoundException */ public static BitMatrix readQRImage (String resourceName) throws IOException { BitMatrix img = null; // Look for resource in classpath URL resource = UtilsTest.class.getClassLoader().getResource(resourceName); if (resource != null) { try { // Convert BufferedImage to BitMatrix img = toBitMatrix(ImageReader.readImage(resource.toURI())); } catch (URISyntaxException e) { throw new AssertionError("Malformed URL: " + resource.toString()); } } return img; }
private static void parse() throws IOException, NotFoundException, ChecksumException, FormatException { BufferedImage image = ImageReader.readImage(Paths.get("d:/qr.png").toUri()); LuminanceSource source = new BufferedImageLuminanceSource(image); Binarizer bin = new HybridBinarizer(source); BinaryBitmap bitmap = new BinaryBitmap(bin); Result result = new QRCodeReader().decode(bitmap); System.out.println(result.toString()); }
/** * 解码 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 ""; }
/** * 加载二维码图片得到Result对象 * @param file 二维码文件 * @return * @throws IOException */ public static Result loadResult(File file) throws IOException { BufferedImage bi = ImageReader.readImage(file); return loadResult(bi); }
/** * 加载二维码图片,得到内容 * @param file 二维码图片文件 * @return * @throws IOException */ public static String loadContent(File file) throws IOException { BufferedImage bi = ImageReader.readImage(file); return loadContent(bi); }