package cn.com.utils; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Component; import org.springframework.util.Base64Utils; import java.io.File; import java.io.FileInputStream; import java.nio.file.Path; import java.util.HashMap; import java.util.Map; public class BarUtils { /** * Draw barcode * * @Param Content To generate content contained in the bar code * @Return returns generated bitmap strip * / public static File createBarcode (String Content) throws Exception { Final int width = 180 [ ; Final int height = 50 ; Final String the format = "PNG" ; // Configure parameters Map <EncodeHintType , Object> = hints new new the HashMap <> (); hints.put (EncodeHintType.CHARACTER_SET, "UTF-. 8" ); // fault tolerance level H Pick highest level hints.put (EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); Writer MultiFormatWriter = new new MultiFormatWriter (); // converts the image data, using the order matrix conversion parameters are: encoded content, coding type, generating a picture width, picture height generated, setting parameters BitMatrix bitMatrix = writer.encode (Content, BarcodeFormat. CODE_128, width, height, hints) ; Path file = File.createTempFile("message_barcode_",".png").toPath(); MatrixToImageWriter.writeToPath(bitMatrix, format, file); return file.toFile(); } /** * Draw barcode * * @Param file to be encoded file * @Return string after base64 encoded return * / public static String encodeImage (File File) throws Exception { FileInputStream fileInputStream = FileUtils.openInputStream(file); byte[] buffer = new byte[(int) file.length()]; fileInputStream.read(buffer); fileInputStream.close(); return Base64Utils.encodeToString(buffer); } }
Barcode generating tools