Commit 3886925f authored by 沈翠玲's avatar 沈翠玲

测试原生蓝牙打印

parent f6caae8c
/**
* html+ 串口蓝牙操作
* 2021.04.23 uni-app版本
* @auth boolTrue
*/
/**
* 初始化参数
*/
//#ifdef APP-PLUS
let BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
let Intent = plus.android.importClass("android.content.Intent");
let IntentFilter = plus.android.importClass("android.content.IntentFilter");
let BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
let UUID = plus.android.importClass("java.util.UUID");
let Toast = plus.android.importClass("android.widget.Toast");
//连接串口设备的 UUID
let MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
let invoke = plus.android.invoke;
let btAdapter = BluetoothAdapter.getDefaultAdapter();
let activity = plus.android.runtimeMainActivity();
let btSocket = null;
let btInStream = null;
let btOutStream = null;
let setIntervalId = 0;
let btFindReceiver = null; //蓝牙搜索广播接收器
let btStatusReceiver = null; //蓝牙状态监听广播
//#endif
/**
* 构造对象
*/
var blueToothTool = {
state : {
bluetoothEnable: false, //蓝牙是否开启
bluetoothState: "", //当前蓝牙状态
discoveryDeviceState: false, //是否正在搜索蓝牙设备
readThreadState: false, //数据读取线程状态
},
options : {
/**
* 监听蓝牙状态回调
* @param {String} state
*/
listenBTStatusCallback: function(state) {},
/**
* 搜索到新的蓝牙设备回调
* @param {Device} newDevice
*/
discoveryDeviceCallback: function(newDevice) {},
/**
* 蓝牙搜索完成回调
*/
discoveryFinishedCallback: function() {},
/**
* 接收到数据回调
* @param {Array} dataByteArr
*/
readDataCallback: function(dataByteArr) {},
/**
* 蓝牙连接中断回调
* @param {Exception} e
*/
connExceptionCallback: function(e) {}
},
init(setOptions) {
Object.assign(this.options, setOptions);
this.state.bluetoothEnable = this.getBluetoothStatus();
this.listenBluetoothStatus();
},
shortToast(msg) {
Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
},
/**
* 是否支持蓝牙
* @return {boolean}
*/
isSupportBluetooth() {
if(btAdapter != null) {
return true;
}
return false;
},
/**
* 获取蓝牙的状态
* @return {boolean} 是否已开启
*/
getBluetoothStatus() {
if(btAdapter != null) {
return btAdapter.isEnabled();
}
return false;
},
/**
* 打开蓝牙
* @param activity
* @param requestCode
*/
turnOnBluetooth() {
if(btAdapter == null) {
shortToast("没有蓝牙");
return;
}
if(!btAdapter.isEnabled()) {
if(activity == null) {
shortToast("未获取到activity");
return;
} else {
let intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
let requestCode = 1;
activity.startActivityForResult(intent, requestCode);
return;
}
} else {
shortToast("蓝牙已经打开");
}
},
/**
* 关闭蓝牙
*/
turnOffBluetooth() {
if(btAdapter != null && btAdapter.isEnabled()) {
btAdapter.disable();
}
if(btFindReceiver != null) {
try {
activity.unregisterReceiver(btFindReceiver);
} catch(e) {
}
btFindReceiver = null;
}
this.state.bluetoothEnable = false;
this.cancelDiscovery();
closeBtSocket();
if(btAdapter != null && btAdapter.isEnabled()) {
btAdapter.disable();
shortToast("蓝牙关闭成功");
} else {
shortToast("蓝牙已经关闭");
}
},
/**
* 获取已经配对的设备
* @return {Array} connetedDevices
*/
getPairedDevices() {
let pairedDevices = [];
//蓝牙连接android原生对象,是一个set集合
let pairedDevicesAndroid = null;
if(btAdapter != null && btAdapter.isEnabled()) {
pairedDevicesAndroid = btAdapter.getBondedDevices();
} else {
shortToast("蓝牙未开启");
}
if(!pairedDevicesAndroid) {
return pairedDevices;
}
//遍历连接设备的set集合,转换为js数组
let it = invoke(pairedDevicesAndroid, "iterator");
while(invoke(it, "hasNext")) {
let device = invoke(it, "next");
pairedDevices.push({
"name": invoke(device, "getName"),
"address": invoke(device, "getAddress")
});
}
return pairedDevices;
},
/**
* 发现设备
*/
discoveryNewDevice() {
if(btFindReceiver != null) {
try {
activity.unregisterReceiver(btFindReceiver);
} catch(e) {
console.error(e);
}
btFindReceiver = null;
this.cancelDiscovery();
}
let Build = plus.android.importClass("android.os.Build");
//6.0以后的如果需要利用本机查找周围的wifi和蓝牙设备, 申请权限
if(Build.VERSION.SDK_INT >= 6.0){
}
let options = this.options
btFindReceiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
"onReceive": function(context, intent) {
plus.android.importClass(context);
plus.android.importClass(intent);
let action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND == action) { // 找到设备
let device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
let newDevice = {
"name": plus.android.invoke(device, "getName"),
"address": plus.android.invoke(device, "getAddress")
}
options.discoveryDeviceCallback && options.discoveryDeviceCallback(newDevice);
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) { // 搜索完成
cancelDiscovery();
options.discoveryFinishedCallback && options.discoveryFinishedCallback();
}
}
});
let filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
activity.registerReceiver(btFindReceiver, filter);
btAdapter.startDiscovery(); //开启搜索
this.state.discoveryDeviceState = true;
},
/**
* 蓝牙状态监听
* @param {Activity} activity
*/
listenBluetoothStatus() {
if(btStatusReceiver != null) {
try {
activity.unregisterReceiver(btStatusReceiver);
} catch(e) {
console.error(e);
}
btStatusReceiver = null;
}
btStatusReceiver = plus.android.implements("io.dcloud.android.content.BroadcastReceiver", {
"onReceive": (context, intent)=> {
plus.android.importClass(context);
plus.android.importClass(intent);
let action = intent.getAction();
switch(action) {
case BluetoothAdapter.ACTION_STATE_CHANGED:
let blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
let stateStr = "";
switch(blueState) {
case BluetoothAdapter.STATE_TURNING_ON:
stateStr = "STATE_TURNING_ON";
break;
case BluetoothAdapter.STATE_ON:
this.state.bluetoothEnable = true;
stateStr = "STATE_ON";
break;
case BluetoothAdapter.STATE_TURNING_OFF:
stateStr = "STATE_TURNING_OFF";
break;
case BluetoothAdapter.STATE_OFF:
stateStr = "STATE_OFF";
this.state.bluetoothEnable = false;
break;
}
this.state.bluetoothState = stateStr;
this.options.listenBTStatusCallback && this.options.listenBTStatusCallback(stateStr);
break;
}
}
});
let filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
activity.registerReceiver(btStatusReceiver, filter);
// 首次连接 状态回调
if(this.state.bluetoothEnable) {
this.options.listenBTStatusCallback && this.options.listenBTStatusCallback('STATE_ON');
}
},
/**
* 根据蓝牙地址,连接设备
* @param {Stirng} address
* @return {Boolean}
*/
connDevice(address, callback) {
let InputStream = plus.android.importClass("java.io.InputStream");
let OutputStream = plus.android.importClass("java.io.OutputStream");
let BluetoothSocket = plus.android.importClass("android.bluetooth.BluetoothSocket");
this.cancelDiscovery();
if(btSocket != null) {
this.closeBtSocket();
}
this.state.readThreadState = false;
try {
let device = invoke(btAdapter, "getRemoteDevice", address);
btSocket = invoke(device, "createRfcommSocketToServiceRecord", MY_UUID);
} catch(e) {
console.error(e);
shortToast("连接失败,获取Socket失败!");
callback(false)
return false;
}
try {
invoke(btSocket, "connect");
this.readData(); //读数据
this.shortToast("连接成功");
callback(true)
} catch(e) {
console.error(e);
this.shortToast("连接失败");
callback(false)
try {
btSocket.close();
btSocket = null;
} catch(e1) {
console.error(e1);
}
return false;
}
return true;
},
/**
* 断开连接设备
* @param {Object} address
* @return {Boolean}
*/
disConnDevice() {
if(btSocket != null) {
this.closeBtSocket();
}
this.state.readThreadState = false;
this.shortToast("断开连接成功");
},
/**
* 断开连接设备
* @param {Object} address
* @return {Boolean}
*/
closeBtSocket() {
this.state.readThreadState = false;
if(!btSocket) {
return;
}
try {
btSocket.close();
} catch(e) {
console.error(e);
btSocket = null;
}
},
/**
* 取消发现
*/
cancelDiscovery() {
if(btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
if(btFindReceiver != null) {
activity.unregisterReceiver(btFindReceiver);
btFindReceiver = null;
}
this.state.discoveryDeviceState = false;
},
/**
* 读取数据
* @param {Object} activity
* @param {Function} callback
* @return {Boolean}
*/
readData() {
if(!btSocket) {
this.shortToast("请先连接蓝牙设备!");
return false;
}
try {
btInStream = invoke(btSocket, "getInputStream");
btOutStream = invoke(btSocket, "getOutputStream");
} catch(e) {
console.error(e);
this.shortToast("创建输入输出流失败!");
this.closeBtSocket();
return false;
}
this.read();
this.state.readThreadState = true;
return true;
},
/**
* 模拟java多线程读取数据
*/
read() {
console.log('dsfsd')
let setTimeCount = 0;
clearInterval(setIntervalId);
setIntervalId = setInterval(()=> {
setTimeCount++;
if(this.state.readThreadState) {
let t = new Date().getTime();
//心跳检测
if(setTimeCount % 20 == 0) {
try {
btOutStream.write([0b00]);
} catch(e) {
this.state.readThreadState = false;
this.options.connExceptionCallback && this.options.connExceptionCallback(e);
}
}
let dataArr = [];
while(invoke(btInStream, "available") !== 0) {
let data = invoke(btInStream, "read");
dataArr.push(data);
let ct = new Date().getTime();
if(ct - t > 20) {
break;
}
}
if(dataArr.length > 0) {
this.options.readDataCallback && this.options.readDataCallback(dataArr);
}
}
}, 40);
},
/**
* 发送数据
* @param {String} dataStr
* @return {Boolean}
*/
sendData(dataStr) {
if(!btOutStream) {
this.shortToast("创建输出流失败!");
return;
}
let bytes = invoke(dataStr, 'getBytes', 'gbk');
try {
btOutStream.write(bytes);
} catch(e) {
return false;
}
return true;
},
sendByteData(byteData) {
if(!btOutStream) {
this.shortToast("创建输出流失败!");
return;
}
try {
btOutStream.write(byteData);
} catch(e) {
return false;
}
return true;
}
}
module.exports = blueToothTool
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
var tsc = require('./tsc.js')
import bluetoothTool from './BluetoothTool.js'
export default {
data () {
return {
devices: [],
currDev: null,
connId: '',
first:true,
tableDomId: '',
tableImgPath: '',
canvasWidth: 800,
canvasHeight: 600
}
},
created () {
//#ifdef APP-PLUS
// 蓝牙
bluetoothTool.init({
listenBTStatusCallback: (state)=> {
// if(state == 'STATE_ON') {
// let lastBleAddress = uni.getStorageSync('lastBleAddress')
// if(lastBleAddress) {
// uni.showLoading({
// title: '正在连接...'
// })
// console.log(lastBleAddress)
// bluetoothTool.connDevice(lastBleAddress,(result)=>{
// uni.hideLoading()
// uni.showToast({
// title: result?'连接成功!':'连接失败...'
// });
// })
// }
// }
},
discoveryDeviceCallback: this.onDevice,
discoveryFinishedCallback: function() {
console.log('搜索到的设备', that.devices)
},
readDataCallback: function(dataByteArr) {
/* if(that.receiveDataArr.length >= 200) {
that.receiveDataArr = [];
}
that.receiveDataArr.push.apply(that.receiveDataArr, dataByteArr); */
},
connExceptionCallback: function(e) {
console.log(e);
that.msg = "设备连接失败";
}
});
this.searchBle()
//#endif
},
computed: {
},
methods: {
searchBle() {
var that = this
console.log("initBule")
// 使用openBluetoothAdapter 接口,免去主动申请权限的麻烦
uni.openBluetoothAdapter({
success(res) {
this.devices = []
console.log("打开 蓝牙模块,开始搜索模式...")
console.log(res)
bluetoothTool.discoveryNewDevice();
//that.onDevice()
}
})
},
onDevice(newDevice){
console.log("监听寻找到新设备的事件---------------")
console.log(newDevice)
if(newDevice.name && newDevice.name != 'null') {
this.devices.push({
name: newDevice.name,
address: newDevice.address
})
if (newDevice.name === 'CT-428D' && this.first) {
this.onConn(newDevice)
this.first = false
}
}
},
onConn(item) {
console.log("连接蓝牙---------------" + item.address)
/* uni.showLoading({
title: '连接中',
mask: false
}); */
bluetoothTool.connDevice(item.address,(result)=>{
if(result) {
uni.setStorageSync('lastBleAddress', item.address)
}
console.log('连接结果:',result)
});
},
print (filePath) {
const firstCanvas = uni.createCanvasContext('firstCanvas', this);
const that = this
uni.getImageInfo({
src: filePath,
success(res) {
that.canvasWidth = 800
that.canvasHeight = 640
console.log(res, that.canvasWidth, that.canvasHeight)
firstCanvas.drawImage(filePath, 0, 0, that.canvasWidth, that.canvasHeight);
firstCanvas.draw();
that.$nextTick(() => { //获取画布像素数据
uni.canvasGetImageData({
canvasId: 'firstCanvas',
x: 0,
y: 0,
width: that.canvasWidth,
height: that.canvasHeight,
success: (res)=> {
var command = tsc.jpPrinter.createNew()
command.init()
command.setSize(100, 80)
command.setGap(2)
command.setCls()
command.setBitmap2(0, 0, 0, res)
command.setPagePrint()
console.log('数据发送: \n',command.getRawData())
let data = command.getData()
console.log('data', data)
bluetoothTool.sendByteData(data)
console.log('发送完毕')
},
fail: function(res) {
console.log(res)
}
})
})
},
fail(res) {
console.log(res)
}
})
},
}
}
\ No newline at end of file
/**
* tsc 命令打印工具类
* 2021.04.26 uni-app版本
* @auth boolTrue
*/
var encode = require("./encoding.js");
var jpPrinter = {
createNew: function() {
var jpPrinter = {};
var data = "";
var command = []
var rawCommand = ''
jpPrinter.name = "标签模式";
jpPrinter.init = function() {};
jpPrinter.addCommand = function(content) { //将指令转成数组装起
//#ifdef MP-WEIXIN
var code = new encode.TextEncoder(
'gb18030', {
NONSTANDARD_allowLegacyEncoding: true
}).encode(content)
for (var i = 0; i < code.length; ++i) {
command.push(code[i])
}
//#endif
//#ifdef APP-PLUS
let byteCommand = plus.android.invoke(content, 'getBytes', 'gb18030');
for (var i = 0; i < byteCommand.length; ++i) {
command.push(byteCommand[i])
}
//#endif
//console.log('command--:',command)
rawCommand += content
}
function intToByte(i) {
// 此处关键 -- android是java平台 byte数值范围是 [-128, 127]
// 因为java平台的byte类型是有符号的 最高位表示符号,所以数值范围固定
// 而图片计算出来的是数值是 0 -255 属于int类型
// 所以把int 转换成byte类型
//#ifdef APP-PLUS
var b = i & 0xFF;
var c = 0;
if (b >= 128) {
c = b % 128;
c = -1 * (128 - c);
} else {
c = b;
}
return c
//#endif
// 而微信小程序不需要,因为小程序api接收的是 无符号8位
//#ifdef MP-WEIXIN
return i
//#endif
}
jpPrinter.setSize = function(pageWidght, pageHeight) { //设置页面大小
data = "SIZE " + pageWidght.toString() + " mm" + "," + pageHeight.toString() + " mm" + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setSpeed = function(printSpeed) { //设置打印机速度
data = "SPEED " + printSpeed.toString() + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setDensity = function(printDensity) { //设置打印机浓度
data = "DENSITY " + printDensity.toString() + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setGap = function(printGap) { //传感器
data = "GAP " + printGap.toString() + " mm\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setCountry = function(country) { //选择国际字符集
/*
001:USA
002:French
003:Latin America
034:Spanish
039:Italian
044:United Kingdom
046:Swedish
047:Norwegian
049:German
*/
data = "COUNTRY " + country + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setCodepage = function(codepage) { //选择国际代码页
/*
8-bit codepage 字符集代表
437:United States
850:Multilingual
852:Slavic
860:Portuguese
863:Canadian/French
865:Nordic
Windows code page
1250:Central Europe
1252:Latin I
1253:Greek
1254:Turkish
以下代码页仅限于 12×24 dot 英数字体
WestEurope:WestEurope
Greek:Greek
Hebrew:Hebrew
EastEurope:EastEurope
Iran:Iran
IranII:IranII
Latvian:Latvian
Arabic:Arabic
Vietnam:Vietnam
Uygur:Uygur
Thai:Thai
1252:Latin I
1257:WPC1257
1251:WPC1251
866:Cyrillic
858:PC858
747:PC747
864:PC864
1001:PC100
*/
data = "CODEPAGE " + codepage + "\r\n";
jpPrinter.addCommand(data)
}
jpPrinter.setCls = function() { //清除打印机缓存
data = "CLS" + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setFeed = function(feed) { //将纸向前推出n
data = "FEED " + feed + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setBackFeed = function(backup) { //将纸向后回拉n
data = "BACKFEED " + backup + "\r\n";
jpPrinter.addCommand(data)
}
jpPrinter.setDirection = function(direction) { //设置打印方向,参考编程手册
data = "DIRECTION " + direction + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setReference = function(x, y) { //设置坐标原点,与打印方向有关
data = "REFERENCE " + x + "," + y + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setFromfeed = function() { //根据Size进一张标签纸
data = "FORMFEED \r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setHome = function() { //根据Size找到下一张标签纸的位置
data = "HOME \r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setSound = function(level, interval) { //控制蜂鸣器
data = "SOUND " + level + "," + interval + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setLimitfeed = function(limit) { // 检测垂直间距
data = "LIMITFEED " + limit + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setBar = function(x, y, width, height) { //绘制线条
data = "BAR " + x + "," + y + "," + width + "," + height + "\r\n"
jpPrinter.addCommand(data)
};
jpPrinter.setBox = function(x_start, y_start, x_end, y_end, thickness) { //绘制方框
data = "BOX " + x_start + "," + y_start + "," + x_end + "," + y_end + "," + thickness + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setErase = function(x_start, y_start, x_width, y_height) { //清除指定区域的数据
data = "ERASE " + x_start + "," + y_start + "," + x_width + "," + y_height + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setReverse = function(x_start, y_start, x_width, y_height) { //将指定的区域反相打印
data = "REVERSE " + x_start + "," + y_start + "," + x_width + "," + y_height + "\r\n";
jpPrinter.addCommand(data)
};
jpPrinter.setText = function(x, y, font, x_, y_, str) { //打印文字
data = "TEXT " + x + "," + y + ",\"" + font + "\"," + 0 + "," + x_ + "," + y_ + "," + "\"" +
str + "\"\r\n"
jpPrinter.addCommand(data)
};
jpPrinter.setQR = function(x, y, level, width, mode, content) { //打印二维码
data = "QRCODE " + x + "," + y + "," + level + "," + width + "," + mode + "," + 0 + ",\"" +
content + "\"\r\n"
jpPrinter.addCommand(data)
};
jpPrinter.setBar = function(x, y, codetype, height, readable, narrow, wide, content) { //打印条形码
data = "BARCODE " + x + "," + y + ",\"" + codetype + "\"," + height + "," + readable + "," + 0 +
"," + narrow + "," + wide + ",\"" + content + "\"\r\n"
jpPrinter.addCommand(data)
};
// 固定灰度阈值(128以上的都看作白色)
jpPrinter.setBitmap = function(x, y, mode, res) { //添加图片,res为画布参数
var width = parseInt((res.width) / 8 * 8 / 8)
var height = res.height
var imgWidth = res.width
var time = 1;
var temp = res.data.length - width * 32;
var pointList = []
var resultData = []
console.log(width + "--" + height)
data = "BITMAP " + x + "," + y + "," + width + "," + height + "," + mode + ","
jpPrinter.addCommand(data)
//console.log(res.data)
console.log('---以上是原始数据---')
//for循环顺序不要错了,外层遍历高度,内层遍历宽度,因为横向每8个像素点组成一个字节
for (var y = 0; y < height; y++) {
for (var x = 0; x < imgWidth; x++) {
let r = res.data[(y * imgWidth + x) * 4];
let g = res.data[(y * imgWidth + x) * 4 + 1];
let b = res.data[(y * imgWidth + x) * 4 + 2];
let a = res.data[(y * imgWidth + x) * 4 + 3]
//console.log(`当前${y}行${x}列像素,rgba值:(${r},${g},${b},${a})`)
// 像素灰度值
let grayColor = r * 0.299 + g * 0.587 + b * 0.114
//灰度值大于128位
//1不打印, 0打印 (参考:佳博标签打印机编程手册tspl)
if (grayColor > 128) {
pointList.push(1)
} else {
pointList.push(0)
}
}
}
//console.log(pointList)
for (var i = 0; i < pointList.length; i += 8) {
var p = pointList[i] * 128 + pointList[i + 1] * 64 + pointList[i + 2] * 32 + pointList[i +
3] * 16 + pointList[i + 4] * 8 + pointList[i + 5] * 4 + pointList[i + 6] * 2 +
pointList[i + 7]
resultData.push(p)
}
console.log('最终数据:')
//console.log(resultData)
for (var i = 0; i < resultData.length; ++i) {
command.push(intToByte(resultData[i]))
}
}
jpPrinter.setBitmap2 = function(x, y, mode, res) { //添加图片,res为画布参数
var w = res.width
var width = parseInt((res.width + 7) / 8 * 8 / 8)
var height = res.height;
console.log(width + "--" + height)
data = "BITMAP " + x + "," + y + "," + width + "," + height + "," + mode + ","
jpPrinter.addCommand(data)
var r = []
var bits = new Uint8Array(height * width);
for (y = 0; y < height; y++) {
for (x = 0; x < w; x++) {
let r = res.data[(y * w + x) * 4];
let g = res.data[(y * w + x) * 4 + 1];
let b = res.data[(y * w + x) * 4 + 2];
let a = res.data[(y * w + x) * 4 + 3]
var color = ((a & 0xFF) << 24) | ((r & 0xFF) << 16) | ((g & 0xFF) << 8) | ((b & 0xFF) <<
0);
if ((color & 0xFF) > 128) {
bits[parseInt(y * width + x / 8)] |= (0x80 >> (x % 8));
}
}
}
for (var i = 0; i < bits.length; i++) {
//command.push((~bits[i]) & 0xFF);
command.push(intToByte(bits[i]));
//r.push((~bits[i]) & 0xFF);
}
}
// 平均灰度阈值(先计算平均灰度,然后大于平均灰度的都算作白色)
jpPrinter.setBitmap3 = function(x, y, mode, res) { //添加图片,res为画布参数
var width = parseInt((res.width) / 8 * 8 / 8)
var height = res.height
var imgWidth = res.width
var time = 1;
var temp = res.data.length - width * 32;
var pointList = []
var resultData = []
console.log(width + "--" + height)
data = "BITMAP " + x + "," + y + "," + width + "," + height + "," + mode + ","
jpPrinter.addCommand(data)
//console.log(res.data)
console.log('---以上是原始数据---')
let sumRed = 0,
sumGreen = 0,
sumBlue = 0;
let total = height * imgWidth;
let pix = res.data;
for (var i = 0; i < pix.length; i += 4) {
sumRed += pix[i]
sumGreen += pix[i + 1]
sumBlue += pix[i + 2]
}
let avgRed = parseInt(sumRed / total);
let avgGreen = parseInt(sumGreen / total);
let avgBlue = parseInt(sumBlue / total);
let avgGrayColor = avgRed * 0.299 + avgGreen * 0.587 + avgBlue * 0.114
//for循环顺序不要错了,外层遍历高度,内层遍历宽度,因为横向每8个像素点组成一个字节
for (var y = 0; y < height; y++) {
for (var x = 0; x < imgWidth; x++) {
let r = res.data[(y * imgWidth + x) * 4];
let g = res.data[(y * imgWidth + x) * 4 + 1];
let b = res.data[(y * imgWidth + x) * 4 + 2];
let a = res.data[(y * imgWidth + x) * 4 + 3]
// 像素灰度值
let grayColor = r * 0.299 + g * 0.587 + b * 0.114
//灰度值大于128位
//1不打印, 0打印 (参考:佳博标签打印机编程手册tspl)
if (grayColor > avgGrayColor) {
pointList.push(1)
} else {
pointList.push(0)
}
}
}
//console.log(pointList)
for (var i = 0; i < pointList.length; i += 8) {
var p = pointList[i] * 128 + pointList[i + 1] * 64 + pointList[i + 2] * 32 + pointList[i +
3] * 16 + pointList[i + 4] * 8 + pointList[i + 5] * 4 + pointList[i + 6] * 2 +
pointList[i + 7]
resultData.push(p)
}
console.log('最终数据:')
//console.log(resultData)
for (var i = 0; i < resultData.length; ++i) {
command.push(intToByte(resultData[i]))
}
}
jpPrinter.RawCommand = function(data) {
jpPrinter.addCommand(data)
}
jpPrinter.setPagePrint = function() { //打印页面
data = "PRINT 1,1\r\n"
jpPrinter.addCommand(data)
};
//获取打印数据
jpPrinter.getData = function() {
return command;
};
jpPrinter.getRawData = function() {
return rawCommand;
};
jpPrinter.clearCommand = function() {
rawCommand = ''
};
return jpPrinter;
}
};
module.exports.jpPrinter = jpPrinter;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment