Java合成图片及文字--Graphics2D
生活随笔
收集整理的這篇文章主要介紹了
Java合成图片及文字--Graphics2D
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ? ?
版權聲明 :
本文為博主原創文章,如需轉載,請注明出處(https://blog.csdn.net/F1004145107/article/details/84317601)
? ? ? ? ? 本文包含倆部分,使用的是 java.awt.Graphics2D?類
? ? ? ? ? 1.生成二維碼(彩色二維碼,去白邊)
? ? ? ? ? 2.將二維碼、文字合成到圖片上面
? ? ? ? ? 代碼的邏輯都在注釋里面了,如果有不懂的可以私信我,代碼中的圖片可以做測試,鏈接均可用
public static void main(String[] args) {java.awt.Font font = new java.awt.Font("宋體", java.awt.Font.BOLD, 36);// 添加字體的屬性設置InputStream is = null;try {// 圖片1BufferedImage backImg = ImageIO.read(new URL("http://wisezhe.oss-cn-beijing.aliyuncs.com/18-11-21/87298612.jpg"));// 圖片2String urlStr = "http://wisezhe.oss-cn-beijing.aliyuncs.com/18-11-21/59672258.jpg";URL url = new URL(urlStr);// 打開連接URLConnection con = url.openConnection();// 設置請求超時為5scon.setConnectTimeout(5 * 1000);// 輸入流is = con.getInputStream();BufferedImage imageLocal = ImageIO.read(is);// 加載用戶的二維碼BufferedImage imageCode = ImageIO.read(new URL(getQrCode()));// 創建模板Graphics2D g = imageLocal.createGraphics();g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// 在模板上添加用戶二維碼(地址,左邊距,上邊距,圖片寬度,圖片高度),值都為像素g.drawImage(imageCode, 474, 42, 170, 170, null);g.setFont(font);// 設置刷子顏色g.setColor(new java.awt.Color(148, 134, 118));// 添加文字g.drawString("我是wise", 60, 129);// 完成模板修改g.dispose();// 合成圖片imageLocal = PictureUtils.mergeImage(backImg, imageLocal, false, 0, 0);// 將圖片直接生成到桌面File file = new File("C:\\Users\\Administrator\\Desktop\\test.jpg");ImageIO.write(imageLocal, "jpg", file);// 如果圖片需要返回使用下列代碼即可,上傳圖片并且返回圖片url // ByteArrayOutputStream outPutStream =3 new ByteArrayOutputStream(); // ImageIO.write(imageLocal, "jpg", outPutStream); // String s = UploadUtils.submitImage(id + ".jpg", outPutStream.toByteArray()); // String key = ""; // BaseUpImageEntity baseUpImageEntity = JacksonUtil.readValue(s, BaseUpImageEntity.class); // if (baseUpImageEntity != null && "0".equals(baseUpImageEntity.getHead().getRspStatusCode())) { // key = baseUpImageEntity.getBody().getUrl(); // }} catch (IOException e) {e.printStackTrace();} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 生成用戶二維碼** @author wise* @return java.lang.String*/private static String getQrCode() {// 跳轉鏈接String content = "https://www.google.com/";ByteArrayOutputStream baos = null;String url = "";try {baos = new ByteArrayOutputStream();MultiFormatWriter multiFormatWriter = new MultiFormatWriter();Map hints = new HashMap();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints);// 去掉二維碼的白邊bitMatrix = updateBit(bitMatrix, 0);// 生成彩色二維碼BufferedImage bufferedImage = toBufferedImage(bitMatrix);ByteArrayOutputStream outPutStream = new ByteArrayOutputStream();ImageIO.write(bufferedImage, "jpg", outPutStream);String json = UploadUtils.submitImage("xxxxxx.jpg", outPutStream.toByteArray());// 如不需生成彩色二維碼直接使用下面被注釋掉的代碼即可 // MatrixToImageWriter.writeToStream(bitMatrix, "jpg", baos); // String json = UploadUtils.submitImage(id + uid + ".jpg", baos.toByteArray());BaseUpImageEntity baseUpImageEntity = JacksonUtil.readValue(json, BaseUpImageEntity.class);if (baseUpImageEntity != null && "0".equals(baseUpImageEntity.getHead().getRspStatusCode())) {url = baseUpImageEntity.getBody().getUrl();}return url;} catch (Exception e) {e.printStackTrace();} finally {try {if (baos != null) {baos.close();}} catch (IOException e) {e.printStackTrace();}}return null;}/*** 去掉二維碼的白邊* * @author wise* @param matrix* @return com.google.zxing.common.BitMatrix*/public static BitMatrix updateBit(BitMatrix matrix, int margin) {int tempM = margin * 2;// 獲取二維碼圖案的屬性int[] rec = matrix.getEnclosingRectangle();int resWidth = rec[2] + tempM;int resHeight = rec[3] + tempM;// 按照自定義邊框生成新的BitMatrixBitMatrix resMatrix = new BitMatrix(resWidth, resHeight);resMatrix.clear();// 循環,將二維碼圖案繪制到新的bitMatrix中for (int i = margin; i < resWidth - margin; i++) {for (int j = margin; j < resHeight - margin; j++) {if (matrix.get(i - margin + rec[0], j - margin + rec[1])) {resMatrix.set(i, j);}}}return resMatrix;}/** * 生成彩色二維碼* * @author wise* @param matrix* @return java.awt.image.BufferedImage*/public static BufferedImage toBufferedImage(BitMatrix matrix) {// 背景顏色 RGB:242,241,236Integer backColor = 0xF2F1EC;//十六進制// 二維碼顏色 RGB:148,134,118Integer qrCodeColor = 0x948676;//int width = matrix.getWidth();int height = matrix.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, matrix.get(x, y) ? qrCodeColor : backColor);}}return image;}? ? ? ? ?倆張圖片進行合成的工具類源碼
package com.shengya.service.utils;import javax.imageio.ImageIO; import javax.imageio.stream.ImageOutputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*;/*** @author wise*/ public class PictureUtils {/*** @param fileUrl 文件絕對路徑或相對路徑* @return 讀取到的緩存圖像* @throws IOException 路徑錯誤或者不存在該文件時拋出IO異常*/public static BufferedImage getBufferedImage(String fileUrl) throws IOException {File f = new File(fileUrl);return ImageIO.read(f);}/*** @param savedImg 待保存的圖像* @param saveDir 保存的目錄* @param fileName 保存的文件名,必須帶后綴,比如 "beauty.jpg"* @param format 文件格式:jpg、png或者bmp* @return*/public static boolean saveImage(BufferedImage savedImg, String saveDir, String fileName, String format) {boolean flag = false;// 先檢查保存的圖片格式是否正確String[] legalFormats = {"jpg", "JPG", "png", "PNG", "bmp", "BMP"};int i = 0;for (i = 0; i < legalFormats.length; i++) {if (format.equals(legalFormats[i])) {break;}}if (i == legalFormats.length) { // 圖片格式不支持System.out.println("不是保存所支持的圖片格式!");return false;}// 再檢查文件后綴和保存的格式是否一致String postfix = fileName.substring(fileName.lastIndexOf('.') + 1);if (!postfix.equalsIgnoreCase(format)) {System.out.println("待保存文件后綴和保存的格式不一致!");return false;}String fileUrl = saveDir + fileName;File file = new File(fileUrl);try {flag = ImageIO.write(savedImg, format, file);} catch (IOException e) {e.printStackTrace();}return flag;}/*** 待合并的兩張圖必須滿足這樣的前提,如果水平方向合并,則高度必須相等;如果是垂直方向合并,寬度必須相等。* mergeImage方法不做判斷,自己判斷。** @param img1 待合并的第一張圖* @param img2 帶合并的第二張圖* @param isHorizontal 為true時表示水平方向合并,為false時表示垂直方向合并* @return 返回合并后的BufferedImage對象* @throws IOException*/public static BufferedImage mergeImage(BufferedImage img1, BufferedImage img2, boolean isHorizontal, int startX, int startY) throws IOException {int w1 = img1.getWidth();int h1 = img1.getHeight();int w2 = img2.getWidth();int h2 = img2.getHeight();// 從圖片中讀取RGBint[] ImageArrayOne = new int[w1 * h1];ImageArrayOne = img1.getRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 逐行掃描圖像中各個像素的RGB到數組中int[] ImageArrayTwo = new int[w2 * h2];ImageArrayTwo = img2.getRGB(0, 0, w2, h2, ImageArrayTwo, 0, w2);// 生成新圖片BufferedImage DestImage = null;if (isHorizontal) { // 水平方向合并DestImage = new BufferedImage(w1, h1, BufferedImage.TYPE_INT_RGB);DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 設置上半部分或左半部分的RGBDestImage.setRGB(startX, startY, w2, h2, ImageArrayTwo, 0, w2); // 設置下半部分的RGB} else { // 垂直方向合并DestImage = new BufferedImage(w1, h1 + h2, BufferedImage.TYPE_INT_RGB);DestImage.setRGB(0, 0, w1, h1, ImageArrayOne, 0, w1); // 設置上半部分或左半部分的RGBDestImage.setRGB(0, h1, w2, h2, ImageArrayTwo, 0, w2); // 設置下半部分的RGB}return DestImage;}}? ?在只用工具類時可能會報java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!異常,原因是倆張圖片的尺寸問題,如果進行垂直合成就必須保證倆張圖片的寬度像素是一樣,水平合成需保證高度像素是一樣
總結
以上是生活随笔為你收集整理的Java合成图片及文字--Graphics2D的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 项目交付二三事
- 下一篇: 如何提供BlackBerry程序的OTA