【源码】二维码透明底和去除白边功能

2024-04-28 21:58

本文主要是介绍【源码】二维码透明底和去除白边功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

布局(activity.xml)、权限(AndroidManifest.xml)和 MainActivity.java(基本一致) 跟先前的源码一致这里就不重复了,需要可以参考先前的。

飞机票:【源码】二维码生成及美化

MakeQRCodeUtil.java

package com.showimage.start.showimage;import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import java.util.HashMap;/*** Created on 2016/2/24.* 生成二维码的工具类*/
public class MakeQRCodeUtil {/*** 转换位图** @param matrix  原图* @param alpha 透明度 0 透明 1半透明 2不透明* @return*/private static Bitmap bitMatrix2Bitmap(BitMatrix matrix, int alpha) {int WIDTH = matrix.getWidth();int HEIGHT = matrix.getHeight();int[] pixels = new int[WIDTH * HEIGHT];for (int y = 0; y < WIDTH; y++) {for (int x = 0; x < HEIGHT; x++) {int color;switch (alpha){case 0:color = 0x00FFFFFF;break;case 1:color = 0x80FFFFFF;break;default:color = 0xFFFFFFFF;break;}if (matrix.get(x, y)) {// 有内容的部分,颜色设置为黑色,当然这里可以自己修改成喜欢的颜色color = 0xFF000000;}pixels[x + (y * WIDTH)] = color;}}Bitmap bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888);bitmap.setPixels(pixels, 0, WIDTH, 0, 0, WIDTH, HEIGHT);return bitmap;}/*** 设置透明度** @param alpha    透明度* @return Paint    画笔*/private static Paint setAlpha(int alpha) {// 建立Paint 物件Paint vPaint = new Paint();vPaint .setStyle( Paint.Style.STROKE );   //空心vPaint .setAlpha(alpha);   //0—255return vPaint;}/*** 设置透明度** @param alpha    透明度  1 不透明 0 半透明* @return Paint    画笔*/private static Paint selectAlpha(int alpha) {if(alpha == 0){return setAlpha(75);}else{return setAlpha(255);}}/*** 添加logo** @param src 原图* @param logo logo图* @return 效果图*/private static Bitmap addLogo(Bitmap src, Bitmap logo) {if (logo == null) {return src;}// 获取图片的宽高int srcWidth = src.getWidth();int srcHeight = src.getHeight();int logoWidth = logo.getWidth();int logoHeight = logo.getHeight();if (logoWidth == 0 || logoHeight == 0) {return src;}// logo大小为二维码整体大小的1/5float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);try {Canvas canvas = new Canvas(bitmap);canvas.drawBitmap(src, 0, 0, null);canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);canvas.save(Canvas.ALL_SAVE_FLAG);canvas.restore();} catch (Exception e) {bitmap = null;e.getStackTrace();}return bitmap;}/*** 从资源文件中获取图片** @param context    上下文* @param drawableId 资源文件id* @return*/public static Bitmap gainBitmap(Context context, int drawableId) {Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),drawableId);return bmp;}/*** 在图片右下角添加水印** @param srcBMP  原图* @param markBMP 水印图片* @return 合成水印后的图片*/public static Bitmap composeWatermark(Bitmap srcBMP, Bitmap markBMP) {if (srcBMP == null) {return null;}// 创建一个新的和SRC长度宽度一样的位图Bitmap newb = Bitmap.createBitmap(srcBMP.getWidth(),srcBMP.getHeight(), Bitmap.Config.ARGB_8888);//获取透明度Paint vPaint = selectAlpha(0);Canvas cv = new Canvas(newb);// 在 0,0坐标开始画入原图cv.drawBitmap(srcBMP, 0, 0, null);// 在原图的右下角画入水印cv.drawBitmap(markBMP, srcBMP.getWidth() - markBMP.getWidth() * 3 / 5,srcBMP.getHeight() * 3 / 7, vPaint);// 保存cv.save(Canvas.ALL_SAVE_FLAG);// 存储cv.restore();return newb;}/*** 给二维码图片加背景** @param foreground 原图* @param background 背景图* @return 效果图*/public static Bitmap addBackground(Bitmap foreground, Bitmap background) {int bgWidth = background.getWidth();int bgHeight = background.getHeight();int fgWidth = foreground.getWidth();int fgHeight = foreground.getHeight();Bitmap newmap = Bitmap.createBitmap(bgWidth, bgHeight, Bitmap.Config.ARGB_8888);Canvas canvas = new Canvas(newmap);canvas.drawBitmap(background, 0, 0, null);canvas.drawBitmap(foreground, (bgWidth - fgWidth) / 2,(bgHeight - fgHeight) * 2 / 5 + 70, null);canvas.save(Canvas.ALL_SAVE_FLAG);canvas.restore();return newmap;}/*** 生成带logo的二维码** @param logo logo图* @param content   内容* @param width 宽度* @param height 高度* @param alpha 透明度* @param isEdge 去白边    true 去除 false 保留* @return 二维码*/public static Bitmap generateQRCode(Bitmap logo, String content, int width, int height, int alpha, boolean isEdge) {return  addLogo(generateQRCode(content, width, height,alpha,isEdge), logo);}/*** 生成不带logo的二维码** @param content 内容* @param width 宽度* @param height 高度* @param alpha 透明度* @param isEdge 去白边    true 去除 false 保留* @return 二维码*/public static Bitmap generateQRCode(String content, int width, int height, int alpha, boolean isEdge) {try {HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();// 设置编码方式utf-8hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置二维码的纠错级别为hhints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);BitMatrix matrix;if(isEdge){matrix = new QRCodeWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);}else{matrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);}return bitMatrix2Bitmap(matrix, alpha);} catch (WriterException e) {e.printStackTrace();}return null;}/*** 添加文字** @param bmpSrc 二维码图* @param text 文字* @return 效果图*/public static Bitmap addTextToBitmap(Bitmap bmpSrc, String text) {int srcWidth = bmpSrc.getWidth();int srcHeight = bmpSrc.getHeight();// 先计算text所需要的heightint textSize = 20;int padding = 3;int textLinePadding = 1;// 每行的文字int perLineWords = (srcWidth - 2 * padding) / textSize;int lineNum = text.length() / perLineWords;lineNum = text.length() % perLineWords == 0 ? lineNum : lineNum + 1;int textTotalHeight = lineNum * (textSize + textLinePadding) + 2 * padding;Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight + textTotalHeight,Bitmap.Config.ARGB_8888);try {Canvas canvas = new Canvas(bitmap);canvas.drawColor(Color.WHITE);canvas.drawBitmap(bmpSrc, 0, 0, null);Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);paint.setColor(Color.BLACK);paint.setTextSize(textSize);String lineText;for (int i = 0, startY = srcHeight + textSize, start, end; i < lineNum; i++) {start = i * perLineWords;end = start + perLineWords;lineText = text.substring(start, end > text.length() ? text.length() : end);canvas.drawText(lineText, padding, startY, paint);startY += textSize + textLinePadding;}canvas.save(Canvas.ALL_SAVE_FLAG);canvas.restore();} catch (Exception e) {bitmap = null;e.getStackTrace();}return bitmap;}
}

QRCodeWriter.java

package com.showimage.start.showimage;/*** Created by twk on 2019/6/25.*/import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;import java.util.Map;public final class QRCodeWriter implements Writer {private static final int QUIET_ZONE_SIZE = 4;public QRCodeWriter() {}public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) throws WriterException {return this.encode(contents, format, width, height, (Map)null);}public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException {if(contents.length() == 0) {throw new IllegalArgumentException("Found empty contents");} else if(format != BarcodeFormat.QR_CODE) {throw new IllegalArgumentException("Can only encode QR_CODE, but got " + format);} else if(width >= 0 && height >= 0) {ErrorCorrectionLevel errorCorrectionLevel = ErrorCorrectionLevel.L;if(hints != null) {ErrorCorrectionLevel code = (ErrorCorrectionLevel)hints.get(EncodeHintType.ERROR_CORRECTION);if(code != null) {errorCorrectionLevel = code;}}QRCode code1 = new QRCode();Encoder.encode(contents, errorCorrectionLevel, hints, code1);return renderResult(code1, width, height);} else {throw new IllegalArgumentException("Requested dimensions are too small: " + width + 'x' + height);}}private static BitMatrix renderResult(QRCode code, int width, int height) {ByteMatrix input = code.getMatrix();if (input == null) {throw new IllegalStateException();}int inputWidth = input.getWidth();int inputHeight = input.getHeight();// 依据用户的输入宽高,计算最后的输出宽高int outputWidth = Math.max(width, inputWidth);int outputHeight = Math.max(height, inputHeight);//计算缩放比例int multiple = Math.min(outputWidth / inputWidth, outputHeight / inputHeight);//重新写一次outputWidth和inputHeightoutputWidth = multiple * inputWidth;outputHeight = multiple * inputHeight;
//        Log.d(TAG, "renderResult: outputWidth " +outputWidth +" outputHeight "+outputHeight);
//        Log.d(TAG, "renderResult: inputHeight " +inputWidth +" inputHeight "+inputHeight);
//        Log.d(TAG, "renderResult: multiple " + multiple);BitMatrix output = new BitMatrix(outputWidth, outputHeight);int inputY = 0;// 嵌套循环,将ByteMatrix的内容计算padding后转换成BitMatrixfor (int outputY = 0; inputY < inputHeight; outputY += multiple) {int inputX = 0;for (int outputX = 0; inputX < inputWidth; outputX += multiple) {if (input.get(inputX, inputY) == 1) {output.setRegion(outputX, outputY, multiple, multiple);}inputX++;}inputY++;}return output;}
}

以上就是全部源码,如果有调试问题,欢迎留言告知,如果对你有帮助,请给我个赞,谢谢!!

这篇关于【源码】二维码透明底和去除白边功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/944360

相关文章

Qt使用QSqlDatabase连接MySQL实现增删改查功能

《Qt使用QSqlDatabase连接MySQL实现增删改查功能》这篇文章主要为大家详细介绍了Qt如何使用QSqlDatabase连接MySQL实现增删改查功能,文中的示例代码讲解详细,感兴趣的小伙伴... 目录一、创建数据表二、连接mysql数据库三、封装成一个完整的轻量级 ORM 风格类3.1 表结构

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

Golang如何用gorm实现分页的功能

《Golang如何用gorm实现分页的功能》:本文主要介绍Golang如何用gorm实现分页的功能方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录背景go库下载初始化数据【1】建表【2】插入数据【3】查看数据4、代码示例【1】gorm结构体定义【2】分页结构体

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

苹果macOS 26 Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色

《苹果macOS26Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色》在整体系统设计方面,macOS26采用了全新的玻璃质感视觉风格,应用于Dock栏、应用图标以及桌面小部件等多个界面... 科技媒体 MACRumors 昨日(6 月 13 日)发布博文,报道称在 macOS 26 Tahoe 中

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.