Using vCard to scan code and save personal information to address book

1, Function

Using vCard to scan code and save personal information to address book

2, vCard

1. Simple understanding

vCard is the file format standard of electronic business card. It is usually attached to e-mail, but it can also be used in other occasions (such as exchanging with each other on the Internet). vCard can contain information such as name, address information, telephone number, URL, logo, photo, etc.

2. vcard keyword description of address book

Field nameField typefield valueremarks
FNundefinedThis field value defines a Formatted Name and the representation method of daily name.Semantic rules of common names based on X.520
NundefinedThe field value represents the name of a person or object in the form of: [Family Name];[Given Name];[Additional Names];
[Name Prefix];[Name Suffix]
Some field values may have only one ";"
PHOTOGIF,CGM,WMF,BMP,MET,PMB,
DIB,PICT,TIFF,PS,PDF,JPEG,
MPEG,MPEG2,AVI,QTIME
The field value is the image data or the file name where the image data is stored (including the URL path)There is no default field type, so you must specify a field type
BDAYundefinedThe field value is the data of birth date, which can be expressed in two ways:
1) . basic format based on ISO8601: < month >
2) . extended format based on ISO8601: - where year is represented by four characters and month and date are represented by two characters
ADRDOM,INTL(),POSTAL(),PARCEL(),
HOME,WORK()
There are seven fields to represent the value of the address:
[Post Office Address];[Extended Address];
[Street];[Locality];[Region];[Postal code];
[Country]
The first field is based on the X.500 standard, and the other fields are based on the X.520 standard
LABELDOM,INTL(),POSTAL(),PARCEL(),
HOME,WORK()
Field values are a daily way of representing addressesSemantic rules of common names based on X.520
TELPREF,WORK,HOME,VOICE(*),
FAX,MSG,CELL,PAGER,BBS,MODEM,
CAR,ISDN,VIDEO
The field value is based on the telephone number representation method of X.520. This data format cannot be guaranteed to be directly used by the dialer. The specific data format analysis should be solved by the dialer.
EMAILAOL,AppleLink,ATTMail,
CIS,eWorld,INTERNET(*),IBMMail,
MCIMail,POWERSHARE,
PRODIGY,TLX,X400
The field value is the email addressThe second column lists a part of the field type, and there may be other types
EMAILERundefinedThe field value is the name of the email software
TZundefinedThe field value is the time difference (time zone) of a place's time relative to UTC (coordinated universal time). The positive and negative values represent the relative value, the west of UTC is a negative value, and the East is a positive value. The value represents that according to ISO8610 standard, there are two forms:
1),<+/-><hour(two digit)><minute(two digit)>
2),<+/-><hour(two digit)>:<minute(two digit)>
GEOundefinedThe field value represents the geographic location information of longitude and latitude of a place. The north latitude is positive, the south latitude is negative, the east longitude is positive and the west longitude is negative:
 <+/->[longitude value],<+/->[latitude value]
TITLEundefinedThe field value represents the name of a head
ROLEundefinedThe field value represents a person's occupation name or role or other business type, which is defined based on X.520 business type.
LOGOGIF,CGM,WMF,BMP,MET,PMB,
DIB,PICT,TIFF,PDF,PS,JPEG,
MPEG,MPEG2,AVI,QTIME
The field value represents an image or portrait of a certain identityThere is no default field type, so you must specify a field type
AGENTundefinedThe field value represents the information of another person related to the person defined by the vCard object (such as administrator, assistant, secretary, etc.). The field value is a complete vCard data package
ORGundefinedThe field value represents an organization name, based on the X.520 standard:
[Organization Name];[Organization Unit]
[;additional Organizational Unit;...]
NOTEundefinedThe field value is the remarks or prompt information related to this vCard object, which is based on the X.520 standard
REVundefinedThe field value represents the last update time of this vCard object. The time adopts the time representation method in the schedule, based on ISO8601 standard:
1),<year(four digits)><month(two digits)><day(two digits)>T<hour(two digits)><minitue(two digits)><second(two digits)>[time zone]
2),<year(four digits)>-<month(two digits)>-<day(two digits)>T<hour(two digits)>:<minitue(two digits)>:<second(two digits)>[time zone]
SOUNDWAVE,PCM,AIFFThe field value represents the sound data of the pronunciation related to the vCard object. If the field is not grouped with other fields, the field represents the pronunciation of the FN field value. The field value can be the sound data of the second system or the pronunciation method represented by other words.There is no default field type. When no field type is specified, the field value is the file or word representing the pronunciation method
URLundefinedThe field value represents the Uniform Resource Locator, which is defined based on IETF RFC 1738.
UIDundefinedThe field value represents the GUID number of this vCard object or the URL address where this vCard object will be updated
VERSIONundefinedThe field value represents the version number of this vCard objectThis field is required and optional in earlier versions
KEYX509,PGPThis field value represents the encryption key. The default format is clear textThere is no default field type. The field type must be defined
X-undefinedThis field value is user-definedThe field parameter value is selected by the user

Note: 1. The field type followed by "*" indicates that it is the default field type;
2. If the field value is marked with " For value classification, the value itself also contains " Or "\ r\n", you must escape and use ";" accordingly And "\" CRCF to escape
PS: the content comes from the network. In this case, only part of the practice has been done. Those interested can practice by themselves

3. Sample vCard file containing personal information

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import  ssl
ssl._create_default_https_context = ssl._create_unverified_context

2, Realize

1. Required jar package

2. QR code processing tools

TwoDimensionCodeImage.java

package util;

import java.awt.image.BufferedImage;

import jp.sourceforge.qrcode.data.QRCodeImage;

public class TwoDimensionCodeImage implements QRCodeImage {

	BufferedImage bufImg;

	public TwoDimensionCodeImage(BufferedImage bufImg) {
		this.bufImg = bufImg;
	}

	@Override
	public int getHeight() {
		return bufImg.getHeight();
	}

	@Override
	public int getPixel(int x, int y) {
		return bufImg.getRGB(x, y);
	}

	@Override
	public int getWidth() {
		return bufImg.getWidth();
	}

}

TwoDimensionCode.java

package util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;

import com.swetake.util.Qrcode;

public class TwoDimensionCode {

	/**
	 * Generate QR code image
	 * 
	 * @param content
	 *            Store content
	 * @param imgPath
	 *            Picture path
	 */
	public static void encoderQRCode(String content, String imgPath) {
		encoderQRCode(content, imgPath, "png", 2);
	}

	/**
	 * Generate QR code image
	 * 
	 * @param content
	 *            Store content
	 * @param output
	 *            Output stream
	 */
	public static void encoderQRCode(String content, OutputStream output) {
		encoderQRCode(content, output, "png", 2);
	}

	/**
	 * Generate QR code image
	 * 
	 * @param content
	 *            Store content
	 * @param imgPath
	 *            Picture path
	 * @param imgType
	 *            Picture type
	 */
	public static void encoderQRCode(String content, String imgPath,
			String imgType) {
		encoderQRCode(content, imgPath, imgType, 2);
	}

	/**
	 * Generate QR code image
	 * 
	 * @param content
	 *            Store content
	 * @param output
	 *            Output stream
	 * @param imgType
	 *            Picture type
	 */
	public static void encoderQRCode(String content, OutputStream output,
			String imgType) {
		encoderQRCode(content, output, imgType, 2);
	}

	/**
	 * Generate QR code image
	 * 
	 * @param content
	 *            Store content
	 * @param imgPath
	 *            Picture path
	 * @param imgType
	 *            Picture type
	 * @param size
	 *            QR code size
	 */
	public static void encoderQRCode(String content, String imgPath,
			String imgType, int size) {
		try {
			BufferedImage bufImg = qRCodeCommon(content, imgType, size);

			File imgFile = new File(imgPath);
			// Generate QR code image
			ImageIO.write(bufImg, imgType, imgFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Generate QR code image
	 * 
	 * @param content
	 *            Store content
	 * @param output
	 *            Output stream
	 * @param imgType
	 *            Picture type
	 * @param size
	 *            QR code size
	 */
	public static void encoderQRCode(String content, OutputStream output,
			String imgType, int size) {
		try {
			BufferedImage bufImg = qRCodeCommon(content, imgType, size);
			// Generate QR code image
			ImageIO.write(bufImg, imgType, output);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Public method for generating QR code pictures
	 * 
	 * @param content
	 *            Store content
	 * @param imgType
	 *            Picture type
	 * @param size
	 *            QR code size
	 * @return
	 */
	private static BufferedImage qRCodeCommon(String content, String imgType,
			int size) {
		BufferedImage bufImg = null;
		size = 14;
		try {
			Qrcode qrcodeHandler = new Qrcode();
			// Set the error correction rate of QR code. L(7%), M(15%), Q(25%) and H(30%) can be selected. The higher the error correction rate, the less information can be stored, but the smaller the requirements for the clarity of QR code
			qrcodeHandler.setQrcodeErrorCorrect('M');
			qrcodeHandler.setQrcodeEncodeMode('B');
			// Set the QR code size, with the value range of 1-40. The larger the value, the larger the size, and the larger the information that can be stored
			qrcodeHandler.setQrcodeVersion(size);
			// Get the byte array of content and set the encoding format
			byte[] contentBytes = content.getBytes("utf-8");
			// Picture size
			// int imgSize = 67 + 12 * (size - 1);
			int imgSize = 67 + 12 * (size - 1);

			// System.out.println(imgSize);

			bufImg = new BufferedImage(imgSize, imgSize,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D gs = bufImg.createGraphics();
			// Set background color
			gs.setBackground(Color.WHITE);
			gs.clearRect(0, 0, imgSize, imgSize);

			// Set image color > Black
			gs.setColor(Color.BLACK);
			// Set the offset. Failure to set it may cause parsing errors
			int pixoff = 2;
			// Output > QR code
			if (contentBytes.length > 0 && contentBytes.length < 800) {

				boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
				for (int i = 0; i < codeOut.length; i++) {
					for (int j = 0; j < codeOut.length; j++) {
						if (codeOut[j][i]) {
							gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
						}
					}
				}
			} else {
				throw new Exception("QRCode content bytes length = "
						+ contentBytes.length + " not in [0, 800].");
			}
			gs.dispose();
			bufImg.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bufImg;
	}

	/**
	 * Parse QR code
	 * 
	 * @param imgPath
	 *            Picture path
	 * @return
	 */
	public static String decoderQRCode(String imgPath) throws Exception {
		// QRCode QR code image file
		File imageFile = new File(imgPath);
		BufferedImage bufImg = null;
		String content = null;
		try {
			bufImg = ImageIO.read(imageFile);
			QRCodeDecoder decoder = new QRCodeDecoder();
			content = new String(decoder.decode(new TwoDimensionCodeImage(
					bufImg)), "utf-8");
		} catch (IOException e) {
			// System.out.println("Error: " + e.getMessage());
			// e.printStackTrace();
		} catch (DecodingFailedException dfe) {
			// System.out.println("Error: " + dfe.getMessage());
			// dfe.printStackTrace();
		}
		return content;
	}

	/**
	 * Parse QR code
	 * 
	 * @param input
	 *            Input stream
	 * @return
	 */
	public static String decoderQRCode(InputStream input) {
		BufferedImage bufImg = null;
		String content = null;
		try {
			bufImg = ImageIO.read(input);
			QRCodeDecoder decoder = new QRCodeDecoder();
			content = new String(decoder.decode(new TwoDimensionCodeImage(
					bufImg)), "utf-8");
		} catch (IOException e) {
			System.out.println("Error: " + e.getMessage());
			e.printStackTrace();
		} catch (DecodingFailedException dfe) {
			System.out.println("Error: " + dfe.getMessage());
			dfe.printStackTrace();
		}
		return content;
	}

}

3. Exception handling

Exceptions.java

package util;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.http.HttpServletRequest;

/**
 * About the tool class of exception
 */
public class Exceptions {

	/**
	 * Convert CheckedException to UncheckedException
	 */
	public static RuntimeException unchecked(Exception e) {
		if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		} else {
			return new RuntimeException(e);
		}
	}

	/**
	 * Convert ErrorStack to String
	 */
	public static String getStackTraceAsString(Throwable e) {
		if (e == null) {
			return "";
		}
		StringWriter stringWriter = new StringWriter();
		e.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

	/**
	 * Judge whether the exception is caused by some underlying exception
	 */
	public static boolean isCausedBy(Exception ex,
			Class<? extends Exception>... causeExceptionClasses) {
		Throwable cause = ex.getCause();
		while (cause != null) {
			for (Class<? extends Exception> causeClass : causeExceptionClasses) {
				if (causeClass.isInstance(cause)) {
					return true;
				}
			}
			cause = cause.getCause();
		}
		return false;
	}

	/**
	 * Get exception class in request
	 * 
	 * @param request
	 * @return
	 */
	public static Throwable getThrowable(HttpServletRequest request) {
		Throwable ex = null;
		if (request.getAttribute("exception") != null) {
			ex = (Throwable) request.getAttribute("exception");
		} else if (request.getAttribute("javax.servlet.error.exception") != null) {
			ex = (Throwable) request
					.getAttribute("javax.servlet.error.exception");
		}
		return ex;
	}

}

4. Entity class

Person.java

package test;

/**
 * Personal information entity class
 */
public class Person {
	// It is only used to demonstrate the effect, and do not tangle with details (such as field type, rationality, etc.)
	private String name; // full name
	private String position; // position
	private String department; // department
	private String phone; // Telephone
	private String email; // mailbox
	private String address; // address
	private String url; // Official website

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPosition() {
		return position;
	}

	public void setPosition(String position) {
		this.position = position;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

}

5. Function realization class

StaffMain.java

package test;

import java.io.IOException;

import util.TwoDimensionCode;

public class StaffMain {
	public static void main(String[] args) throws IOException {

		Person person = new Person();
		person.setName("Li Si");
		person.setDepartment("Sales Department");
		person.setPosition("Sales Director");
		person.setPhone("18888888888");
		person.setEmail("xxx@163.com");
		person.setAddress("Beijing XX area XX large building XX layer XXX room");
		person.setUrl("www.xxxxxxxxx.cn");
		// Generate user QR code
		String realPath = "L:/qrcode/";
		String name = person.getName() + ".png"; // Picture name of QR code
		String filePath = realPath + name; // QR code path
		String content = "BEGIN:VCARD\r\nVERSION:3.0";
		content += "\r\nN:" + person.getName();
		content += "\r\nTEL:" + person.getPhone();
		content += "\r\nEMAIL;TYPE=WORK:" + person.getEmail();
		content += "\r\nORG:" + person.getPosition();
		content += "\r\nTITLE:" + person.getDepartment();
		content += "\r\nADR;TYPE=WORK:" + person.getAddress();
		content += "\r\nEND:VCARD";
		System.out.println(content);
		TwoDimensionCode.encoderQRCode(content, filePath, "png");// Execute QR code generation
	}
}

6. Console

7. Implementation effect

8. QR code scanning

summary

At this point, the function has been realized. The full version of the code can be downloaded. If it is inconvenient to download, leave the private message in the email and reply after seeing it.

Keywords: Java

Added by basheer12m on Thu, 10 Feb 2022 13:51:28 +0200