h5原生. 自己写了个工具类:
package com.comtop.msp.cas.server.utils;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import com.comtop.msp.open.qiniu.UploadUtils;
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;
public class ImgUtil {
private static final String TEMP = "/temp";
public static String mergeImg(String tempPath,String requestPath,String userId) {
String codeUrl = null;
int width = 100;
int height = 100;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
String mergePath = tempPath + File.separator + TEMP + "/merge.png";
// 内容所使用编码
hints.put(EncodeHintType.MARGIN, 0);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 生成二维码
BitMatrix bitMatrix;
try {
bitMatrix = new MultiFormatWriter().encode(requestPath+"/userShare/register/goRegister/"+userId, BarcodeFormat.QR_CODE, width, height, hints);
File fileDir = new File(tempPath + TEMP);
if (!fileDir.exists()) {
fileDir.mkdir();
}
File file = new File(tempPath + File.separator + TEMP + "/qrcode.png");
file.createNewFile();
MatrixToImageWriter.writeToFile(bitMatrix, "PNG", file);
bitMatrix.clear();
InputStream imagein = new FileInputStream(tempPath + "/WEB-INF/classes/include/image/a.png");
InputStream imagein2 = new FileInputStream(file);
BufferedImage image = ImageIO.read(imagein);
BufferedImage image2 = ImageIO.read(imagein2);
Graphics g = image.getGraphics();
g.drawImage(image2, 210, 435, 100, 100, null);
OutputStream outImage = new FileOutputStream(mergePath);
ImageIO.write(image, "PNG", outImage);
codeUrl = UploadUtils.upload(toByteArray2(mergePath));
imagein.close();
imagein2.close();
image.flush();
image2.flush();
outImage.close();
File delFile = new File(mergePath);
delFile.delete();
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
return codeUrl;
}
public static byte[] toByteArray2(String filename) throws IOException {
File f = new File(filename);
if (!f.exists()) {
throw new FileNotFoundException(filename);
}
FileChannel channel = null;
FileInputStream fs = null;
try {
fs = new FileInputStream(f);
channel = fs.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
// System.out.println("reading");
}
return byteBuffer.array();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}