来源:http://www.open-open.com/lib/view/open1379214678162.html

这里因为找 jar 文件麻烦我就直接把源码给弄过来了

但还是要引入一个jar 

下载地址:http://download.csdn.net/detail/qq_27292113/9742717

package util;import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
import java.util.Random;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 二维码工具类
*
*/
public class ZxingUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int LOGO_WIDTH = 60;
// LOGO高度
private static final int LOGO_HEIGHT = 60;
public static BufferedImage createImage(String content, String logoPath,int size, boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, size, size, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (logoPath == null || "".equals(logoPath)) {
return image;
}
// 插入图片
ZxingUtil.insertImage(image, logoPath, needCompress);
return image;
}
/**
* 插入LOGO
* @param source   二维码图片
* @param logoPath   LOGO图片地址
* @param needCompress  是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
File file = new File(logoPath);
if (!file.exists()) {
throw new Exception("logo file not found.");
}
Image src = ImageIO.read(new File(logoPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > LOGO_WIDTH) {   width = LOGO_WIDTH;       }
if (height > LOGO_HEIGHT) {   height = LOGO_HEIGHT;              }
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 生成二维码(内嵌LOGO)
* 二维码文件名随机,文件名可能会有重复
* @param content   内容
* @param logoPath    LOGO地址
* @param destPath   存放目录
* @param needCompress   是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception {
BufferedImage image = ZxingUtil.createImage(content, logoPath,QRCODE_SIZE, needCompress);
mkdirs(destPath);
String fileName = new Random().nextInt(99999999) + "." + FORMAT.toLowerCase();
ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
return fileName;
}
public static BufferedImage convertBufferedImage(String content, String logoPath,int size, boolean needCompress) throws Exception {
    BufferedImage image = ZxingUtil.createImage(content, logoPath,size,needCompress);
    return image;
}
/**
* 生成二维码(内嵌LOGO)
* 调用者指定二维码文件名
* @param content   内容
* @param logoPath  LOGO地址
* @param destPath   存放目录
* @param fileName   二维码文件名
* @param needCompress   是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception {
BufferedImage image = ZxingUtil.createImage(content, logoPath,QRCODE_SIZE, needCompress);
mkdirs(destPath);
fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length())+ "." + FORMAT.toLowerCase();
ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
return fileName;
}
/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.
* (mkdir如果父目录不存在则会抛出异常)
* @param destPath
*            存放目录
*/
public static void mkdirs(String destPath) {
File file = new File(destPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 解析二维码
* @param file  二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage  image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
Result result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 解析二维码
* @param path   二维码图片地址
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
return ZxingUtil.decode(new File(path));
}
public static void main(String[] args) throws Exception {
String text = "http://www.baidu.com";
//不含Logo
//ZxingUtil.encode(text, null, "e:\\", true);
//含Logo,不指定二维码图片名
//ZxingUtil.encode(text, "e:\\csdn.jpg", "e:\\", true);
//含Logo,指定二维码图片名
ZxingUtil.encode(text, null, "C:\\Users\\Administrator\\Desktop", "qrcode", true);
// 解析二维码
        System.out.println(decode("C:\\Users\\Administrator\\Desktop\\qrcode.jpg"));
}
}
package util;/** Copyright 2009 ZXing authors** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import com.google.zxing.common.BitMatrix;import javax.imageio.ImageIO;
import java.io.File;
import java.io.OutputStream;
import java.io.IOException;
import java.awt.image.BufferedImage;/*** Writes a {@link BitMatrix} to {@link BufferedImage},* file or stream. Provided here instead of core since it depends on* Java SE libraries.** @author Sean Owen*/
public final class MatrixToImageWriter {private static final MatrixToImageConfig DEFAULT_CONFIG = new MatrixToImageConfig();private MatrixToImageWriter() {}/*** Renders a {@link BitMatrix} as an image, where "false" bits are rendered* as white, and "true" bits are rendered as black.*/public static BufferedImage toBufferedImage(BitMatrix matrix) {return toBufferedImage(matrix, DEFAULT_CONFIG);}/*** As {@link #toBufferedImage(BitMatrix)}, but allows customization of the output.*/public static BufferedImage toBufferedImage(BitMatrix matrix, MatrixToImageConfig config) {int width = matrix.getWidth();int height = matrix.getHeight();BufferedImage image = new BufferedImage(width, height, config.getBufferedImageColorModel());int onColor = config.getPixelOnColor();int offColor = config.getPixelOffColor();for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {image.setRGB(x, y, matrix.get(x, y) ? onColor : offColor);}}return image;}/*** Writes a {@link BitMatrix} to a file.** @see #toBufferedImage(BitMatrix)*/public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {writeToFile(matrix, format, file, DEFAULT_CONFIG);}/*** As {@link #writeToFile(BitMatrix, String, File)}, but allows customization of the output.*/public static void writeToFile(BitMatrix matrix, String format, File file, MatrixToImageConfig config) throws IOException {  BufferedImage image = toBufferedImage(matrix, config);if (!ImageIO.write(image, format, file)) {throw new IOException("Could not write an image of format " + format + " to " + file);}}/*** Writes a {@link BitMatrix} to a stream.** @see #toBufferedImage(BitMatrix)*/public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {writeToStream(matrix, format, stream, DEFAULT_CONFIG);}/*** As {@link #writeToStream(BitMatrix, String, OutputStream)}, but allows customization of the output.*/public static void writeToStream(BitMatrix matrix, String format, OutputStream stream, MatrixToImageConfig config) throws IOException {  BufferedImage image = toBufferedImage(matrix, config);if (!ImageIO.write(image, format, stream)) {throw new IOException("Could not write an image of format " + format);}}}
package util;
/* * Copyright 2012 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * *      http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *///package com.google.zxing.client.j2se; import java.awt.image.BufferedImage; /** * Encapsulates custom configuration used in methods of {@link MatrixToImageWriter}. */
public final class MatrixToImageConfig { public static final int BLACK = 0xFF000000; public static final int WHITE = 0xFFFFFFFF; private final int onColor; private final int offColor; /** * Creates a default config with on color {@link #BLACK} and off color {@link #WHITE}, generating normal * black-on-white barcodes. */public MatrixToImageConfig() { this(BLACK, WHITE); } /** * @param onColor pixel on color, specified as an ARGB value as an int * @param offColor pixel off color, specified as an ARGB value as an int */public MatrixToImageConfig(int onColor, int offColor) { this.onColor = onColor; this.offColor = offColor; } public int getPixelOnColor() { return onColor; } public int getPixelOffColor() { return offColor; } int getBufferedImageColorModel() { // Use faster BINARY if colors match default return onColor == BLACK && offColor == WHITE ? BufferedImage.TYPE_BYTE_BINARY : BufferedImage.TYPE_INT_RGB; } }
package util;
/** Copyright 2009 ZXing authors** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import com.google.zxing.LuminanceSource;import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;/*** This LuminanceSource implementation is meant for J2SE clients and our blackbox unit tests.** @author dswitkin@google.com (Daniel Switkin)* @author Sean Owen* @author code@elektrowolle.de (Wolfgang Jung)*/
public final class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image;private final int left;private final int top;public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {super(width, height);int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException("Crop rectangle does not fit within image data.");}// The color of fully-transparent pixels is irrelevant. They are often, technically, fully-transparent// black (0 alpha, and then 0 RGB). They are often used, of course as the "white" area in a// barcode image. Force any such pixel to be white:if (image.getAlphaRaster() != null) {int[] buffer = new int[width];for (int y = top; y < top + height; y++) {image.getRGB(left, y, width, 1, buffer, 0, sourceWidth);boolean rowChanged = false;for (int x = 0; x < width; x++) {if ((buffer[x] & 0xFF000000) == 0) {buffer[x] = 0xFFFFFFFF; // = whiterowChanged = true;}}if (rowChanged) {image.setRGB(left, y, width, 1, buffer, 0, sourceWidth);}}}// Create a grayscale copy, no need to calculate the luminance manuallythis.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);this.image.getGraphics().drawImage(image, 0, 0, null);this.left = left;this.top = top;}@Overridepublic byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException("Requested row is outside the image: " + y);}int width = getWidth();if (row == null || row.length < width) {row = new byte[width];}// The underlying raster of image consists of bytes with the luminance valuesimage.getRaster().getDataElements(left, top + y, width, 1, row);return row;}@Overridepublic byte[] getMatrix() {int width = getWidth();int height = getHeight();int area = width * height;byte[] matrix = new byte[area];// The underlying raster of image consists of area bytes with the luminance valuesimage.getRaster().getDataElements(left, top, width, height, matrix);return matrix;}@Overridepublic boolean isCropSupported() {return true;}@Overridepublic LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);}/*** This is always true, since the image is a gray-scale image.** @return true*/@Overridepublic boolean isRotateSupported() {return true;}@Overridepublic LuminanceSource rotateCounterClockwise() {int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();// Rotate 90 degrees counterclockwise.AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);// Note width/height are flipped since we are rotating 90 degrees.BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);// Draw the original image into rotated, via transformationGraphics2D g = rotatedImage.createGraphics();g.drawImage(image, transform, null);g.dispose();// Maintain the cropped region, but rotate it too.int width = getWidth();return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);}@Overridepublic LuminanceSource rotateCounterClockwise45() {int width = getWidth();int height = getHeight();int oldCenterX = left + width / 2;int oldCenterY = top + height / 2;// Rotate 45 degrees counterclockwise.AffineTransform transform = AffineTransform.getRotateInstance(Math.toRadians(-45.0), oldCenterX, oldCenterY);int sourceDimension = Math.max(image.getWidth(), image.getHeight());BufferedImage rotatedImage = new BufferedImage(sourceDimension, sourceDimension, BufferedImage.TYPE_BYTE_GRAY);// Draw the original image into rotated, via transformationGraphics2D g = rotatedImage.createGraphics();g.drawImage(image, transform, null);g.dispose();int halfDimension = Math.max(width, height) / 2;int newLeft = Math.max(0, oldCenterX - halfDimension);int newTop = Math.max(0, oldCenterY - halfDimension);int newRight = Math.min(sourceDimension - 1, oldCenterX + halfDimension);int newBottom = Math.min(sourceDimension - 1, oldCenterY + halfDimension);return new BufferedImageLuminanceSource(rotatedImage, newLeft, newTop, newRight - newLeft, newBottom - newTop);}}

生成二维码中间放入图片相关推荐

  1. php生成二维码并与背景图片合成

    1. 下载 phpqrcode  PHP QR Code是一个PHP二维码生成类库,利用它可以轻松生成二维码,官网提供了下载和多个演示demo,查看地址:http://phpqrcode.source ...

  2. js前端根据链接生成二维码并转成图片下载

    js前端根据链接生成二维码并转成图片下载 依赖于jquery.jquery.qrcode.min.js 1.html <div class="qrcode"></ ...

  3. Vue生成二维码,自定义插入图片生成logo

    Vue生成二维码,自定义插入图片生成logo vue-qr是一个很棒的制作二维码开源库,github地址:https://github.com/Binaryify/vue-qr 1.安装vue-qr ...

  4. java生成二维码,中间插入图片,以及二维码解析

    在实际的项目中有用到生成二维码的功能,生成的二维码中间可以插入一张图片. 先来效果图 (这是我事先准备了一张图片 a)---- 生成的二维码的效果图 (二维码中间插入的图片就是上面保存的图片a) 好了 ...

  5. vue 前端生成二维码,并转换为图片

    这篇文章主要是分享下自己的收获,也是自己遇到的问题: 前端如何自己生成二维码? 前端如何将生成的二维码转成图片并展示? 如何控制二维码的显隐? 话不多说,直接上干货 base64如何转换成图片 npm ...

  6. jquery.qrcode.js生成二维码插件转成图片格式

    1.qrcode其实是通过使用jQuery实现图形渲染,画图,支持canvas(HTML5)和table两种方式, github源码地址: https://github.com/jeromeetien ...

  7. url地址生成二维码及转换成图片

    写出来的小demo,大概就是这样子. 输入任意网址,生成出二维码.移动端不能直接将canvas生成出来的二维码保存为图片(pc端可以),所以将其直接转换成了图片. demo的代码: <!DOCT ...

  8. C# Qrcode生成二维码支持中文,带图片,带文字

    1.下载Qrcode库源码,下载地址:http://www.codeproject.com/Articles/20574/Open-Source-QRCode-Library 2.打开源码时,部分类库 ...

  9. Qrcode生成二维码支持中文,带图片,带文字

    1.下载Qrcode库源码, 下载地址:http://www.codeproject.com/Articles/20574/Open-Source-QRCode-Library 2.打开源码时, 部分 ...

最新文章

  1. Anaconda:包安装以XGBoost为例
  2. GPU中与CUDA相关的几个概念
  3. 切换ip下的sql server用户权限丢失_Zabbix_server高可用之文件同步
  4. 分布式文件系统—HDFS—入门简介
  5. Data Lake Analytics: 使用DataWorks来调度DLA任务
  6. qdu_ACM集训队3月5号组队训练
  7. Android WebKit
  8. Docker - Docker中搭建MySQL主从
  9. C++没有调用析构函数
  10. 全网最详细 Python如何读取NIFTI格式图像(.nii文件)和 .npy格式文件和pkl标签文件内容
  11. Transformer新内核Synthesizer:低复杂度的attention代替点乘式的注意力机制
  12. java容器类添加元素失败失败_java容器 Set
  13. /dev/hda5在linux中表示什么,linux
  14. GPS经纬度转百度地图经纬度
  15. 中国手机市场调查报告
  16. python聊天小程序支持私聊和多人_Python 使用 django 框架实现多人在线匿名聊天的小程序...
  17. msgbox窗口学习总结窗体复合框
  18. mysql records_MySQL 基本操作 · LYF_Records
  19. 撸吧,你活不到明天了
  20. Linux中常用的几个压缩工具,Linux系统中常用的压缩和解压缩工具

热门文章

  1. error C2665: none of the 2 overloads could convert all the argument types
  2. nyoj--61 传字条(一)(多线程dp)
  3. 什么是严格模式和混杂模式?如何区分?
  4. PDFJS在IE11报Uint8ClampedArray“未定义”
  5. 软件面试体总结待完善
  6. java di是什么_Spring IOC和DI的理解有什么区别
  7. go语言微服务之RPC协议
  8. 益生菌什么时间段吃效果好?益生菌的正确吃法一天吃多少
  9. 基于FPGA的FFT变换
  10. 在anaconda安装python命令_windows上安装Anaconda和python的教程详解