Zxing图形码生成工具

@param contents
内容
@param barcodeFormat
BarcodeFormat对象
@param format
图片格式，可选[png,jpg,bmp]
@param width
宽
@param height
高
@param margin
边框间距px
@param saveImgFilePath
存储图片的完整位置，包含文件名
@return {boolean}
557247
public static boolean encode(String contents, BarcodeFormat barcodeFormat, Integer margin,
			ErrorCorrectionLevel errorLevel, String format, int width, int height, String saveImgFilePath) {
		Boolean bool = false;
		BufferedImage bufImg;
		Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
		// 指定纠错等级
		hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
		hints.put(EncodeHintType.MARGIN, margin);
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		try {
			// contents = new String(contents.getBytes("UTF-8"), "ISO-8859-1");
			BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, barcodeFormat, width, height, hints);
			MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
			bufImg = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
			bool = writeToFile(bufImg, format, saveImgFilePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bool;
	}
521937
@SneakyThrows
    public static void generateQRCode(final OutputStream stream, final String key,
                                      final int width, final int height) {
        val hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
        hintMap.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
        hintMap.put(EncodeHintType.MARGIN, 2);
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        val qrCodeWriter = new QRCodeWriter();
        val byteMatrix = qrCodeWriter.encode(key, BarcodeFormat.QR_CODE, width, height, hintMap);
        val byteMatrixWidth = byteMatrix.getWidth();
        val image = new BufferedImage(byteMatrixWidth, byteMatrixWidth, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();

        @Cleanup("dispose")
        val graphics = (Graphics2D) image.getGraphics();

        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, byteMatrixWidth, byteMatrixWidth);
        graphics.setColor(Color.BLACK);

        IntStream.range(0, byteMatrixWidth)
            .forEach(i -> IntStream.range(0, byteMatrixWidth)
                .filter(j -> byteMatrix.get(i, j))
                .forEach(j -> graphics.fillRect(i, j, 1, 1)));

        ImageIO.write(image, "png", stream);
    }
1056029
private static void appendEncode( CssFormatter formatter, byte[] bytes ) {
        for( byte b : bytes ) {
            if ((b >= 'a' && b <= 'z' ) || (b >= 'A' && b <= 'Z' ) || (b >= '0' && b <= '9' )) {
                formatter.append( (char )b );
            } else {
                switch( b ) {
                    case '-':
                    case '_':
                    case '*':
                    case '.':
                        formatter.append( (char )b );
                        break;
                    default:
                        formatter.append( '%' );
                        formatter.append( Character.toUpperCase( Character.forDigit((b >> 4) & 0xF, 16) ) );
                        formatter.append( Character.toUpperCase( Character.forDigit(b & 0xF, 16) ) );
                }
            }
        }
    }
808675
function formatLine(startIndex) {
      let result = ' ';

      // Append a hex formatting of |bytes|.
      for (let i = 0; i < kBytesPerLine; ++i) {
        result += ' ';

        // Add a separator every 8 bytes.
        if ((i % 8) === 0) {
          result += ' ';
        }

        // Output hex for the byte, or space if no bytes remain.
        const byteIndex = startIndex + i;
        if (byteIndex < bytes.length) {
          result += byteToPaddedHex(bytes[byteIndex]);
        } else {
          result += '  ';
        }
      }

      result += '   ';

      // Append an ASCII formatting of the bytes, where ASCII codes 32
      // though 126 display the corresponding characters, nulls are
      // represented by spaces, and any other character is represented
      // by a period.
      for (let i = 0; i < kBytesPerLine; ++i) {
        const byteIndex = startIndex + i;
        if (byteIndex >= bytes.length) {
          break;
        }

        const curByte = bytes[byteIndex];

        if (curByte >= 0x20 && curByte <= 0x7E) {
          result += String.fromCharCode(curByte);
        } else if (curByte === 0x00) {
          result += ' ';
        } else {
          result += '.';
        }
      }

      return result;
    }
1197363
private Shape decodeMarkBorder(int width, int height) {
        int left = (width - 3) / 2 - 5;
        int top  = (height - 2) / 2 - 5;

        path.reset();
        path.moveTo(left + 1, top + 0);
        path.lineTo(left + 3, top + 0);
        path.pointAt(left + 4, top + 1);
        path.pointAt(left + 5, top + 2);
        path.pointAt(left + 6, top + 1);
        path.moveTo(left + 7, top + 0);
        path.lineTo(left + 9, top + 0);
        path.pointAt(left + 10, top + 1);
        path.pointAt(left + 9, top + 2);
        path.pointAt(left + 8, top + 3);
        path.moveTo(left + 7, top + 4);
        path.lineTo(left + 7, top + 5);
        path.pointAt(left + 8, top + 6);
        path.pointAt(left + 9, top + 7);
        path.pointAt(left + 10, top + 8);
        path.moveTo(left + 9, top + 9);
        path.lineTo(left + 7, top + 9);
        path.pointAt(left + 6, top + 8);
        path.pointAt(left + 5, top + 7);
        path.pointAt(left + 4, top + 8);
        path.moveTo(left + 3, top + 9);
        path.lineTo(left + 1, top + 9);
        path.pointAt(left + 0, top + 8);
        path.pointAt(left + 1, top + 7);
        path.pointAt(left + 2, top + 6);
        path.moveTo(left + 3, top + 5);
        path.lineTo(left + 3, top + 4);
        path.pointAt(left + 2, top + 3);
        path.pointAt(left + 1, top + 2);
        path.pointAt(left + 0, top + 1);

        return path;
    }
1330778
PdfChunk split(float width) {
        newlineSplit = false;
        if (image != null) {
            if (image.getScaledWidth() > width) {
                PdfChunk pc = new PdfChunk(Chunk.OBJECT_REPLACEMENT_CHARACTER, this);
                value = "";
                attributes = new HashMap();
                image = null;
                font = PdfFont.getDefaultFont();
                return pc;
            }
            else
                return null;
        }
        HyphenationEvent hyphenationEvent = (HyphenationEvent)noStroke.get(Chunk.HYPHENATION);
        int currentPosition = 0;
        int splitPosition = -1;
        float currentWidth = 0;
        
        // loop over all the characters of a string
        // or until the totalWidth is reached
        int lastSpace = -1;
        float lastSpaceWidth = 0;
        int length = value.length();
        char valueArray[] = value.toCharArray();
        char character = 0;
        BaseFont ft = font.getFont();
        boolean surrogate = false;
        if (ft.getFontType() == BaseFont.FONT_TYPE_CJK && ft.getUnicodeEquivalent(' ') != ' ') {
            while (currentPosition < length) {
                // the width of every character is added to the currentWidth
                char cidChar = valueArray[currentPosition];
                character = (char)ft.getUnicodeEquivalent(cidChar);
                // if a newLine or carriageReturn is encountered
                if (character == '\n') {
                    newlineSplit = true;
                    String returnValue = value.substring(currentPosition + 1);
                    value = value.substring(0, currentPosition);
                    if (value.length() < 1) {
                        value = "\u0001";
                    }
                    PdfChunk pc = new PdfChunk(returnValue, this);
                    return pc;
                }
                currentWidth += font.width(cidChar);
                if (character == ' ') {
                    lastSpace = currentPosition + 1;
                    lastSpaceWidth = currentWidth;
                }
                if (currentWidth > width)
                    break;
                // if a split-character is encountered, the splitPosition is altered
                if (splitCharacter.isSplitCharacter(0, currentPosition, length, valueArray, thisChunk))
                    splitPosition = currentPosition + 1;
                currentPosition++;
            }
        }
        else {
            while (currentPosition < length) {
                // the width of every character is added to the currentWidth
                character = valueArray[currentPosition];
                // if a newLine or carriageReturn is encountered
                if (character == '\r' || character == '\n') {
                    newlineSplit = true;
                    int inc = 1;
                    if (character == '\r' && currentPosition + 1 < length && valueArray[currentPosition + 1] == '\n')
                        inc = 2;
                    String returnValue = value.substring(currentPosition + inc);
                    value = value.substring(0, currentPosition);
                    if (value.length() < 1) {
                        value = " ";
                    }
                    PdfChunk pc = new PdfChunk(returnValue, this);
                    return pc;
                }
                surrogate = Utilities.isSurrogatePair(valueArray, currentPosition);
                if (surrogate)
                    currentWidth += font.width(Utilities.convertToUtf32(valueArray[currentPosition], valueArray[currentPosition + 1]));
                else
                    currentWidth += font.width(character);
                if (character == ' ') {
                    lastSpace = currentPosition + 1;
                    lastSpaceWidth = currentWidth;
                }
                if (surrogate)
                    currentPosition++;
                if (currentWidth > width)
                    break;
                // if a split-character is encountered, the splitPosition is altered
                if (splitCharacter.isSplitCharacter(0, currentPosition, length, valueArray, null))
                    splitPosition = currentPosition + 1;
                currentPosition++;
            }
        }
        
        // if all the characters fit in the total width, null is returned (there is no overflow)
        if (currentPosition == length) {
            return null;
        }
        // otherwise, the string has to be truncated
        if (splitPosition < 0) {
            String returnValue = value;
            value = "";
            PdfChunk pc = new PdfChunk(returnValue, this);
            return pc;
        }
        if (lastSpace > splitPosition && splitCharacter.isSplitCharacter(0, 0, 1, singleSpace, null))
            splitPosition = lastSpace;
        if (hyphenationEvent != null && lastSpace >= 0 && lastSpace < currentPosition) {
            int wordIdx = getWord(value, lastSpace);
            if (wordIdx > lastSpace) {
                String pre = hyphenationEvent.getHyphenatedWordPre(value.substring(lastSpace, wordIdx), font.getFont(), font.size(), width - lastSpaceWidth);
                String post = hyphenationEvent.getHyphenatedWordPost();
                if (pre.length() > 0) {
                    String returnValue = post + value.substring(wordIdx);
                    value = trim(value.substring(0, lastSpace) + pre);
                    PdfChunk pc = new PdfChunk(returnValue, this);
                    return pc;
                }
            }
        }
        String returnValue = value.substring(splitPosition);
        value = trim(value.substring(0, splitPosition));
        PdfChunk pc = new PdfChunk(returnValue, this);
        return pc;
    }
506259
function _initialiseFromWireformat(contents) {
        that._packet = {};
        var p = that._packet;

        // duplicate buffer to guard against modification
        var incoming = new Buffer(contents);

        p.PHYPayload = incoming;

        p.MHDR = incoming.slice(0, 1);

        //        var type = p.MHDR._getMType;
        if (that.isJoinRequestMessage()) {
            // NB little-endian buffers!
            p.MACPayload = incoming.slice(1, incoming.length - 4);
            p.MACPayloadWithMIC = incoming.slice(1, incoming.length);
            p.AppEUI = util.reverse(incoming.slice(1, 1 + 8));
            p.DevEUI = util.reverse(incoming.slice(9, 9 + 8));
            p.DevNonce = util.reverse(incoming.slice(17, 17 + 2));
            p.MIC = incoming.slice(incoming.length - 4);
        } else if (that.isJoinAcceptMessage()) {
            p.MACPayload = incoming.slice(1, incoming.length - 4);
            p.MACPayloadWithMIC = incoming.slice(1, incoming.length);
            p.AppNonce = util.reverse(incoming.slice(1, 1 + 3));
            p.NetID = util.reverse(incoming.slice(4, 4 + 3));
            p.DevAddr = util.reverse(incoming.slice(7, 7 + 4));
            p.DLSettings = incoming.slice(11, 11 + 1);
            p.RxDelay = incoming.slice(12, 12 + 1);
            if (incoming.length == 13+16+4) {
                p.CFList = incoming.slice(13, 13+16)
            } else {
                p.CFList = new Buffer(0);
            }
            p.MIC = incoming.slice(incoming.length - 4);
        } else if (that.isDataMessage()) {
            p.MACPayload = incoming.slice(1, incoming.length - 4);
            p.MACPayloadWithMIC = incoming.slice(1, incoming.length);
            p.MIC = incoming.slice(incoming.length - 4);

            p.FCtrl = p.MACPayload.slice(4, 5);
            var FCtrl = p.FCtrl.readInt8(0);
            var FOptsLen = FCtrl & 0x0f;
            p.FOpts = p.MACPayload.slice(7, 7 + FOptsLen);
            var FHDR_length = 7 + FOptsLen;
            p.FHDR = p.MACPayload.slice(0, 0 + FHDR_length); // TODO silence linter
            p.DevAddr = util.reverse(p.FHDR.slice(0, 4)); // NB little-endian buffers!

            p.FCnt = util.reverse(p.FHDR.slice(5, 7)); // NB little-endian buffers!

            // what's left? Either FPort+FRMPayload or nothing.
            if (FHDR_length == p.MACPayload.length) {
                p.FPort = new Buffer(0);
                p.FRMPayload = new Buffer(0);
            } else {
                p.FPort = p.MACPayload.slice(FHDR_length, FHDR_length + 1);
                p.FRMPayload = p.MACPayload.slice(FHDR_length + 1);
            }
        }
    }
1340818
public static String enCodeFileContent(String filePath,String encoding){
		String baseFileContent = "";
		
		File file = new File(filePath);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				LogUtil.writeErrorLog(e.getMessage(), e);
			}
		}
		InputStream in = null;
		try {
			in = new FileInputStream(file);
			int fl = in.available();
			if (null != in) {
				byte[] s = new byte[fl];
				in.read(s, 0, fl);
				// 压缩编码.
				baseFileContent = new String(SecureUtil.base64Encode(SDKUtil.deflater(s)),encoding);
			}
		} catch (Exception e) {
			LogUtil.writeErrorLog(e.getMessage(), e);
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					LogUtil.writeErrorLog(e.getMessage(), e);
				}
			}
		}
		return baseFileContent;
	}
197218
private String guessImageFormat(String contentType, String imagePath) throws IOException {

        String format = "png";

        if (contentType == null) {
            contentType = URLConnection.guessContentTypeFromName(imagePath);
        }

        if (contentType != null) {
            format = contentType.replaceFirst("^image/([^;]+)[;]?.*$", "$1");
        }
        else {
            int queryStringIndex = imagePath.indexOf('?');

            if (queryStringIndex != -1) {
                imagePath = imagePath.substring(0, queryStringIndex);
            }

            String[] pathTokens = imagePath.split("\\.");

            if (pathTokens.length > 1) {
                format = pathTokens[pathTokens.length - 1];
            }
        }

        return format;
    }
1203162
function saveContentToFile(filePrefix, content) {
  var dirPath = getWebHookDirectory();
  var filePath = path.join(dirPath, filePrefix + '#' + ASSOCIATION_FILE_NAME);

  // create all directories from file path
  createDirectoriesIfNeeded(dirPath);

  // write content to the file
  try {
    fs.writeFileSync(filePath, JSON.stringify(content, null, 2), 'utf8');
  } catch (err) {
    console.log(err);
  }
}
1064940
private int writePlaintextData(final ByteBuffer src, int len) {
        final int pos = src.position();
        final int limit = src.limit();
        final int sslWrote;

        if (src.isDirect()) {
            sslWrote = SSL.writeToSSL(ssl, bufferAddress(src) + pos, len);
            if (sslWrote > 0) {
                src.position(pos + sslWrote);
            }
        } else {
            ByteBuf buf = alloc.directBuffer(len);
            try {
                src.limit(pos + len);

                buf.setBytes(0, src);
                src.limit(limit);

                sslWrote = SSL.writeToSSL(ssl, memoryAddress(buf), len);
                if (sslWrote > 0) {
                    src.position(pos + sslWrote);
                } else {
                    src.position(pos);
                }
            } finally {
                buf.release();
            }
        }
        return sslWrote;
    }
1253572
public static String encode(byte[] bytes, String indentation) {
        int length = bytes.length;
        if (length == 0) return "";  // empty byte array
        String encoded = Base64.encodeBase64String(bytes).replaceAll("\\s", "");  // remove all white space
        StringBuilder result = new StringBuilder();
        if (indentation != null) result.append(indentation);
        result.append(encoded.charAt(0));
        for (int c = 1; c < encoded.length(); c++) {
            if (c % 80 == 0) {
                // format to indented 80 character blocks
                result.append("\n");
                if (indentation != null) result.append(indentation);
            }
            result.append(encoded.charAt(c));
        }
        return result.toString();
    }
812460
public static boolean writeFile(String filePath, String fileContent,
			String encoding) {
		FileOutputStream fout = null;
		FileChannel fcout = null;
		File file = new File(filePath);
		if (file.exists()) {
			file.delete();
		}
		
		try {
			fout = new FileOutputStream(filePath);
			// 获取输出通道
			fcout = fout.getChannel();
			// 创建缓冲区
			// ByteBuffer buffer = ByteBuffer.allocate(1024);
			ByteBuffer buffer = ByteBuffer.wrap(fileContent.getBytes(encoding));
			fcout.write(buffer);
			fout.flush();
		} catch (FileNotFoundException e) {
			LogUtil.writeErrorLog("WriteFile fail", e);
			return false;
		} catch (IOException ex) {
			LogUtil.writeErrorLog("WriteFile fail", ex);
			return false;
		} finally {
			try {
				if (null != fout)
					fout.close();
				if (null != fcout)
					fcout.close();
			} catch (IOException ex) {
				LogUtil.writeErrorLog("Releases any system resources fail", ex);
				return false;
			}
		}
		return true;
	}
1276676
private static ImageFormat getWebpFormat(final byte[] imageHeaderBytes, final int headerSize) {
    Preconditions.checkArgument(WebpSupportStatus.isWebpHeader(imageHeaderBytes, 0, headerSize));
    if (WebpSupportStatus.isSimpleWebpHeader(imageHeaderBytes, 0)) {
      return DefaultImageFormats.WEBP_SIMPLE;
    }

    if (WebpSupportStatus.isLosslessWebpHeader(imageHeaderBytes, 0)) {
      return DefaultImageFormats.WEBP_LOSSLESS;
    }

    if (WebpSupportStatus.isExtendedWebpHeader(imageHeaderBytes, 0, headerSize)) {
      if (WebpSupportStatus.isAnimatedWebpHeader(imageHeaderBytes, 0)) {
        return DefaultImageFormats.WEBP_ANIMATED;
      }
      if (WebpSupportStatus.isExtendedWebpHeaderWithAlpha(imageHeaderBytes, 0)) {
        return DefaultImageFormats.WEBP_EXTENDED_WITH_ALPHA;
      }
      return DefaultImageFormats.WEBP_EXTENDED;
    }

    return ImageFormat.UNKNOWN;
  }
1254445
public static void imgCompressByWH(String srcFile, String desFile, int width, int height, Float quality) {
        ImgCompressUtils.imgCompressByWH(srcFile, desFile, width, height, quality, false);
    }
149743
function(stream) {
			var pngMagicNum = "\211PNG\r\n\032\n",
				jpgMagicNum = "\377\330",
				gifMagicNum = "GIF8",
				pos = 0,
				nextByte = function() {
					return stream.charCodeAt(pos++);
				};
		
			if (stream.substr(0, 8) === pngMagicNum) {
				// PNG. Easy peasy.
				pos = stream.indexOf('IHDR') + 4;
			
				return {
					width:  (nextByte() << 24) | (nextByte() << 16) | (nextByte() <<  8) | nextByte(),
					height: (nextByte() << 24) | (nextByte() << 16) | (nextByte() <<  8) | nextByte()
				};
			
			} else if (stream.substr(0, 4) === gifMagicNum) {
				pos = 6;
			
				return {
					width:  nextByte() | (nextByte() << 8),
					height: nextByte() | (nextByte() << 8)
				};
			
			} else if (stream.substr(0, 2) === jpgMagicNum) {
				pos = 2;
			
				var l = stream.length;
				while (pos < l) {
					if (nextByte() != 0xFF) return;
				
					var marker = nextByte();
					if (marker == 0xDA) break;
				
					var size = (nextByte() << 8) | nextByte();
				
					if (marker >= 0xC0 && marker <= 0xCF && !(marker & 0x4) && !(marker & 0x8)) {
						pos += 1;
						return {
							height: (nextByte() << 8) | nextByte(),
							width: (nextByte() << 8) | nextByte()
						};
				
					} else {
						pos += size - 2;
					}
				}
			}
		}
911574
public String uploadImage(byte[] image, byte[] watermark, String ext, Map<String, String> metaInfo, float opacity, int pos, int margin) {
        String path = "";
        TrackerServer trackerServer = null;
        StorageClient1 storageClient1 = null;
        ByteArrayOutputStream thumbOs = new ByteArrayOutputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            trackerServer = fastDfsClientPool.borrowObject();
            storageClient1 = new StorageClient1(trackerServer, null);
            NameValuePair data[] = null;
            if (Lang.isNotEmpty(metaInfo)) {
                data = new NameValuePair[metaInfo.size()];
                int index = 0;
                for (Map.Entry<String, String> entry : metaInfo.entrySet()) {
                    data[index] = new NameValuePair(entry.getKey(), entry.getValue());
                    index++;
                }
            }
            //保存原图
            path = storageClient1.uploadFile1(image, ext, data);
            //保存水印图 作为原图的salve file
            BufferedImage bufferedImage = Images.addWatermark(image, watermark, opacity, pos, margin);
            Images.write(bufferedImage, ext, os);
            storageClient1.uploadFile1(path, IMAGE_WATERMARK_SUFFIX, os.toByteArray(), ext, data);
            //保存缩略图
            BufferedImage read = Images.read(image);
            BufferedImage bufferedImageThumb = Images.zoomScale(read, IMAGE_THUMB_WIDTH, IMAGE_THUMB_HEIGHT);
            Images.write(bufferedImageThumb, ext, thumbOs);
            storageClient1.uploadFile1(path, IMAGE_THUMB_SUFFIX, thumbOs.toByteArray(), ext, data);

        } catch (Exception e) {
            throw Lang.makeThrow("[FastdfsService] upload images error : %s", e.getMessage());
        } finally {
            Streams.safeClose(os);
            Streams.safeClose(thumbOs);
            try {
                if (trackerServer != null)
                    fastDfsClientPool.returnObject(trackerServer);
                storageClient1 = null;
            } catch (Exception e) {
                log.error(e);
            }
        }
        return path;
    }