cropper.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. // pages/piano/cropper/cropper.js
  2. const { BtCmd } = require('../../../devices/bluetooth/bt_cmd');
  3. import eventBus from '../../../utils/eventBus'
  4. import { EnumCmdEvent, CmdEvent } from '../../../devices/cmd_key_event';
  5. import routeUtil from '../../../utils/routeUtil';
  6. const { BtHelper } = require('../../../devices/bt_helper');
  7. const { uploadImage } = require('../../../request/imageRequest');
  8. Page({
  9. /**
  10. * 页面的初始数据
  11. */
  12. data: {
  13. navbarData: {
  14. showCapsule: 1, //是否显示左上角图标 1表示显示 0表示不显示
  15. title: '壁纸设置', //导航栏 中间的标题
  16. callback: true,
  17. },
  18. src: "",
  19. width: 320,//宽度
  20. height: 320,//高度
  21. showProgress: false,
  22. _chunks: [],
  23. progress: 0,
  24. _timer: null,
  25. // 裁剪后的图片地址
  26. _imgUrl: null,
  27. _imgMD5: null,
  28. _imgIndex: null,
  29. // 从上级界面过来的图片地址,也是要返回去的地址
  30. _imgTopPic: null,
  31. _imgNext: 0,
  32. max_scale: 2,
  33. _hasPermission: false,
  34. _hasShowModal: false,
  35. _deviceId: null,
  36. wallpaper: {},
  37. },
  38. cropper: null,
  39. callback() {
  40. let that = this
  41. if (this.data._chunks.length > 0) {
  42. wx.showModal({
  43. title: '保存壁纸中,确定要中断退出吗?',
  44. content: '',
  45. complete: (res) => {
  46. if (res.confirm) {
  47. that.endImage(2)
  48. wx.navigateBack({
  49. delta: 1,
  50. })
  51. }
  52. }
  53. })
  54. } else {
  55. wx.navigateBack({
  56. delta: 1,
  57. })
  58. }
  59. },
  60. cropperload(e) {
  61. console.log('cropper加载完成');
  62. },
  63. upload() {
  64. let that = this;
  65. wx.chooseMedia({
  66. count: 1,
  67. mediaType: ['image'],
  68. sourceType: ['album'],
  69. success(res) {
  70. wx.showLoading({
  71. title: '加载中',
  72. })
  73. const tempFilePaths = res.tempFiles[0].tempFilePath;
  74. that.cropper.imgReset();
  75. that.setData({
  76. src: tempFilePaths
  77. });
  78. // todo 测试用
  79. // that.testUpload(tempFilePaths)
  80. }, fail(err2) {
  81. console.log(err2)
  82. }
  83. })
  84. },
  85. testUpload(url) {
  86. let _this = this
  87. // 读取裁剪的jpg图片
  88. const fs = wx.getFileSystemManager();
  89. fs.readFile({
  90. filePath: url,
  91. encoding: '', // 不指定编码以获取原始二进制数据
  92. success: (obj) => {
  93. console.log("加载文件成功:", obj.data.byteLength, obj.data.length)
  94. fs.getFileInfo({
  95. "filePath": url, "digestAlgorithm": "md5", success: (res) => {
  96. console.log("md5:", res)
  97. _this.data._imgMD5 = res.digest
  98. _this.data._imgIndex = 0
  99. console.log("加载文件成功:", obj.data.byteLength, obj.data.length, obj.getFileInfo)
  100. let binData = obj.data;
  101. // let myMd5 = _this.getImgMd5(binData)
  102. // let my2Md5 = _this.getImg2Md5(binData)
  103. // let my3Md5 = _this.getImg3Md5(binData)
  104. wx.setClipboardData({
  105. data: res.digest,
  106. fail: (err) => {
  107. console.error('setClipboardData失败:', err);
  108. },
  109. success: (res) => {
  110. console.log('setClipboardData成功:', res);
  111. },
  112. })
  113. _this.sliceDataIntoChunks(binData, 64);
  114. console.log("加载文件成功2:", binData.byteLength, binData.length)
  115. _this.data._imageBufferLength = binData.byteLength ?? binData.length
  116. wx.hideLoading();
  117. wx.showLoading({
  118. title: '开始传输壁纸',
  119. })
  120. console.log("md5 2:", _this.data._imgMD5)
  121. _this.startImage()
  122. }, fail: (err) => {
  123. console.error('getFileInfo失败:', err);
  124. },
  125. })
  126. },
  127. fail: (err) => {
  128. console.error('读取 .bin 文件失败2:', err);
  129. },
  130. });
  131. // 651kb的
  132. // _this.downloadAndSaveFile("https://music-play.oss-cn-shenzhen.aliyuncs.com/backOss/file/8770a6097d9940b59032d099b2fdde3b.bin");
  133. },
  134. loadimage(e) {
  135. wx.hideLoading();
  136. console.log('加载壁纸', e.detail.path);
  137. this.data._imgTopPic = e.detail.path
  138. // this.cropper.imgReset();
  139. },
  140. clickcut(e) {
  141. console.log("clickcut:", e.detail);
  142. //壁纸预览
  143. wx.previewImage({
  144. current: e.detail.url,
  145. urls: [e.detail.url]
  146. })
  147. },
  148. cancel() {
  149. wx.navigateBack({
  150. delta: -1
  151. })
  152. },
  153. async _uploadImgIOS(url) {
  154. let _this = this;
  155. let res = await uploadImage(url);
  156. // 服务器的走下载图片
  157. _this.data._imgTopPic = res.data;
  158. console.log("添加图片2,", _this.data._imgTopPic.length)
  159. console.log("IOS的走下载图片", res)
  160. _this._downloadAndSaveFile(_this.data._imgTopPic)
  161. },
  162. _uploadImage(url) {
  163. const fs = wx.getFileSystemManager();
  164. let _this = this;
  165. // app.globalData.imgSrc = obj.url;
  166. console.log("裁剪壁纸:", url);
  167. _this.data._imgUrl = url
  168. fs.readFile({
  169. filePath: _this.data._imgUrl,
  170. encoding: '', // 不指定编码以获取原始二进制数据
  171. success: (obj) => {
  172. console.log("加载文件成功:", obj.data.byteLength, obj.data.length)
  173. fs.getFileInfo({
  174. "filePath": _this.data._imgUrl, "digestAlgorithm": "md5", success: (res2) => {
  175. console.log("md5:", res2)
  176. _this.data._imgMD5 = res2.digest
  177. _this.data._imgIndex = 0
  178. console.log("加载文件成功:", obj.data.byteLength, obj.data.length, obj.getFileInfo)
  179. let binData = obj.data;
  180. // let myMd5 = _this.getImgMd5(binData)
  181. // let my2Md5 = _this.getImg2Md5(binData)
  182. // let my3Md5 = _this.getImg3Md5(binData)
  183. // todo 测试用
  184. // wx.setClipboardData({
  185. // data: res2.digest,
  186. // })
  187. _this.sliceDataIntoChunks(binData, 64);
  188. console.log("加载文件成功2:", binData.byteLength, binData.length)
  189. _this.data._imageBufferLength = binData.byteLength ?? binData.length
  190. wx.hideLoading();
  191. wx.showLoading({
  192. title: '开始传输壁纸',
  193. })
  194. console.log("md5 2:", _this.data._imgMD5)
  195. _this.startImage()
  196. }, fail: (err) => {
  197. console.error('getFileInfo失败:', err);
  198. },
  199. })
  200. },
  201. fail: (err) => {
  202. wx.hideLoading()
  203. wx.showToast({
  204. title: '读取该图片失败',
  205. })
  206. console.error('读取 .bin 文件失败:', err);
  207. },
  208. });
  209. },
  210. submit() {
  211. let _this = this
  212. // if (_this.data._chunks.length > 0) {
  213. // return;
  214. // }
  215. let _imgTopPic = _this.data._imgTopPic ?? ""
  216. console.log("长度:", _imgTopPic, _imgTopPic.length)
  217. if (_imgTopPic.length == 0) {
  218. wx.showToast({
  219. title: '壁纸不能为空',
  220. icon: "none"
  221. })
  222. return
  223. }
  224. if (_imgTopPic.startsWith("http")) {
  225. // 服务器的走下载图片
  226. console.log("服务器的走下载图片", _this.data._imgTopPic)
  227. _this._downloadAndSaveFile(_this.data._imgTopPic)
  228. return;
  229. }
  230. const res = wx.getSystemInfoSync(); // 获取系统信息
  231. /// android ios
  232. const platform = res.platform; // 获取平台类型
  233. wx.showLoading({
  234. title: '壁纸裁剪中',
  235. })
  236. // 读取裁剪的jpg图片
  237. this.cropper.getImg((res) => {
  238. if (platform === 'ios') {
  239. _this._uploadImgIOS(res.url)
  240. } else {
  241. _this.data._imgTopPic = res.url
  242. _this._uploadImage(res.url)
  243. }
  244. });
  245. },
  246. _downloadAndSaveFile(url) {
  247. let _this = this
  248. // 下载文件
  249. wx.downloadFile({
  250. url: url,
  251. success: function (res) {
  252. if (res.statusCode === 200) {
  253. const tempFilePath = res.tempFilePath;
  254. _this.data._imgTopPic = url
  255. _this._uploadImage(tempFilePath)
  256. } else {
  257. wx.showToast({
  258. title: '下载图片失败',
  259. icon: 'error'
  260. });
  261. }
  262. },
  263. fail: function (err) {
  264. console.error('下载文件失败', err);
  265. wx.showToast({
  266. title: '下载失败',
  267. icon: 'error'
  268. });
  269. }
  270. });
  271. },
  272. checkAndRequestImagePermission: function () {
  273. const _this = this;
  274. // 检查用户是否已经授权访问相册
  275. wx.getSetting({
  276. success(res) {
  277. if (!res.authSetting['scope.writePhotosAlbum']) {
  278. // 用户未授权访问相册,请求用户授权
  279. wx.authorize({
  280. scope: 'scope.writePhotosAlbum',
  281. success() {
  282. // 用户同意授权
  283. console.log('用户已授权访问相册1');
  284. _this.upload()
  285. // 可以在这里执行访问相册的操作
  286. },
  287. fail() {
  288. // 用户拒绝授权
  289. console.log('用户拒绝授权访问相册');
  290. wx.showModal({
  291. title: '提示',
  292. content: '您拒绝了访问相册的权限,无法上传壁纸',
  293. showCancel: false,
  294. success(res) {
  295. if (res.confirm) {
  296. // 跳转到设置页面
  297. wx.openSetting({
  298. success(settingRes) {
  299. if (settingRes.authSetting['scope.writePhotosAlbum']) {
  300. console.log('用户已在设置中开启访问相册的权限');
  301. // 可以在这里执行访问相册的操作
  302. _this.upload(); //上传壁纸
  303. } else {
  304. console.log('用户仍未授权访问相册');
  305. }
  306. }
  307. });
  308. }
  309. }
  310. });
  311. }
  312. });
  313. } else {
  314. // 用户已授权访问相册
  315. console.log('用户已授权访问相册2');
  316. // 可以在这里执行访问相册的操作
  317. _this.upload()
  318. }
  319. }
  320. });
  321. },
  322. async startImage() {
  323. console.log("开始发送壁纸数据: 0x78",)
  324. BtHelper.sendCallBack(BtCmd.wallPaper(1), function (res) {
  325. if (!res) {
  326. wx.hideLoading()
  327. wx.setTimeout(function () {
  328. wx.showToast({
  329. title: '发送失败',
  330. icon: 'error',
  331. duration: 2000
  332. })
  333. }, 100)
  334. }
  335. });
  336. },
  337. sliceDataIntoChunks(data, chunkSize) {
  338. let buffer = data;
  339. console.log("发送壁纸数据:", buffer.byteLength, buffer.length)
  340. let total = buffer.byteLength || buffer.length
  341. const chunks = [];
  342. // for (let i = 0; i < data.length; i += chunkSize) {
  343. for (let i = 0; i < total; i += chunkSize) {
  344. const chunk = buffer.slice(i, i + chunkSize);
  345. chunks.push(chunk);
  346. }
  347. // const sliceSize = chunkSize / 2; // 每个 RGB565 占 2 字节
  348. // const chunks = [];
  349. // for (let i = 0; i < total; i += sliceSize) {
  350. // chunks.push(buffer.slice(i, i + sliceSize));
  351. // }
  352. this.data._chunks = chunks;
  353. },
  354. // getImgMd5(buffer) {
  355. // let md5ctx = js_md5.md5_init();
  356. // js_md5.md5_update(md5ctx, buffer, buffer.byteLength ?? buffer.length);
  357. // let result = js_md5.md5_final(md5ctx);
  358. // let md5 = js_md5.md5_encode_hex(result, 16);
  359. // console.log("result:", md5, result);
  360. // return md5
  361. // },
  362. sendImageMD5() {
  363. // let lengthCode = this.data._chunks.length
  364. // console.log("发送壁纸MD5 1:", lengthCode, this.data._imgMD5)
  365. let value = BtCmd.sendWiFiInfo("99", this.data._imgMD5)
  366. // console.log("发送壁纸MD5 2:", value)
  367. BtHelper.sendCallBack(BtCmd.wallPaperMD5(value), function (res) {
  368. if (!res) {
  369. wx.hideLoading()
  370. wx.showToast({
  371. title: '发送图片失败',
  372. icon: 'error'
  373. })
  374. }
  375. });
  376. },
  377. // 切分高位和低位
  378. splitHighLowBytes(value) {
  379. let highByte = (value >> 8) & 0xFF;
  380. let lowByte = value & 0xFF;
  381. return { highByte, lowByte };
  382. },
  383. async sendImage() {
  384. let _this = this
  385. let index = _this.data._imgIndex
  386. wx.hideLoading()
  387. let chunks = _this.data._chunks
  388. let total = _this.data._imageBufferLength;
  389. let btHelper = BtHelper.getInstance();
  390. // let i = 0;
  391. // _this.data._timer = setInterval(async () => {
  392. if (index > chunks.length - 1) {
  393. // wx.showModal({
  394. // title: '壁纸上传完成md5:' + _this.data._imgMD5,
  395. // content: '最终发送数据大小:' + _this.data._imgNext + ',总大小:' + total + '',
  396. // showCancel: false,
  397. // success(res) {
  398. // }
  399. // })
  400. _this.endImage(0)
  401. return;
  402. }
  403. const chunk = chunks[index];
  404. _this.data._imgNext += (chunk.byteLength ?? chunk.length);
  405. // console.log("发送壁纸数据1:", index, ":", _this.data._imgNext, ":", chunk.length, ":", chunk.byteLength, ":", total, chunks.length)
  406. _this.data._imgIndex += 1;
  407. let res = await btHelper.wallPaperSyncData(chunk);
  408. // let res = true;
  409. // btHelper.wallPaperData(chunk);
  410. if (!res) {
  411. wx.showModal({
  412. title: '壁纸上传失败',
  413. showCancel: false
  414. })
  415. _this.endImage(2)
  416. return
  417. }
  418. _this.updateProgress(_this.data._imgNext, total);
  419. // }, 30);
  420. },
  421. async delay(ms) {
  422. return new Promise(resolve => setTimeout(resolve, ms));
  423. },
  424. endImage(value) {
  425. let _this = this
  426. console.log("结束壁纸上传:", value)
  427. if (_this.data._timer) {
  428. clearInterval(_this.data._timer)
  429. _this.data._timer = null
  430. }
  431. _this.setData({
  432. progress: 0,
  433. showProgress: false
  434. })
  435. _this.data._chunks = []
  436. _this.data._imgNext = 0
  437. _this.data._imgMD5 = null
  438. _this.data._imgIndex = 0
  439. BtHelper.getInstance().wallPaper(value);
  440. },
  441. startProgress() {
  442. this.setData({
  443. progress: 0,
  444. showProgress: true
  445. })
  446. },
  447. updateProgress(chunk, total) {
  448. let progress = parseFloat((chunk / total * 100).toFixed(2));
  449. let _this = this
  450. if (chunk >= total) {
  451. _this.setData({
  452. progress: 100,
  453. showCropImg: false
  454. });
  455. } else {
  456. _this.setData({
  457. progress: progress,
  458. });
  459. }
  460. },
  461. successSend() {
  462. let _this = this
  463. wx.showModal({
  464. title: '保存壁纸成功',
  465. showCancel: false,
  466. success(res) {
  467. if (res.confirm) {
  468. const pages = getCurrentPages();
  469. // 获取上一级页面实例
  470. const prevPage = pages[pages.length - 2];
  471. // 传递参数
  472. prevPage.updateTopImg(_this.data._imgTopPic)
  473. wx.navigateBack({
  474. delta: 1,
  475. })
  476. }
  477. }
  478. })
  479. },
  480. failSend(showToast) {
  481. console.log('failSend')
  482. let _this = this
  483. _this.data._chunks = []
  484. _this.data._imgMD5 = null
  485. _this.data._imgIndex = 0
  486. _this.data._imgNext = 0
  487. wx.hideLoading()
  488. if (showToast) {
  489. wx.showToast({
  490. title: '发送图片失败',
  491. icon: 'error'
  492. })
  493. }
  494. _this.setData({
  495. progress: 0,
  496. showProgress: false,
  497. showCropImg: false
  498. });
  499. },
  500. hasImage(image) {
  501. let that = this;
  502. that.cropper.imgReset();
  503. // 有图片的进制缩放
  504. that.setData({
  505. src: image.pic,
  506. max_scale: 1,
  507. });
  508. that.data._imgTopPic = image.pic
  509. console.log("有图片", image.pic, that.data._imgTopPic.length)
  510. },
  511. disconnectDevCallback() {
  512. routeUtil.goBackHomePage()
  513. // 设备断开连接回调,请重新连接设备
  514. },
  515. /**
  516. * 生命周期函数--监听页面加载
  517. */
  518. onLoad(options) {
  519. let _this = this;
  520. this.cropper = this.selectComponent("#image-cropper");
  521. this.cropper.imgReset();
  522. let image = options.param
  523. let json = JSON.parse(image)
  524. console.log("裁剪页:", json)
  525. let topImg = json.topImg ?? {}
  526. let deviceId = json.deviceId ?? "";
  527. _this.data._deviceId = deviceId
  528. if (topImg.pic) {
  529. this.hasImage(topImg)
  530. } else {
  531. console.log("没有图片")
  532. this.checkAndRequestImagePermission()
  533. }
  534. // this.setData({
  535. // scr:json,
  536. // })
  537. eventBus.addNotification(CmdEvent.eventName, function (event) {
  538. let name = event.cmdEvent;
  539. let value = event.wallpaper;
  540. let kind = event.heiJiaoKind;
  541. // console.log("裁剪页:", name, value, kind)
  542. switch (name) {
  543. case EnumCmdEvent.onoffline:
  544. wx.hideLoading();
  545. break;
  546. case EnumCmdEvent.wallpaper:
  547. //0x78
  548. // 小程序:0x78, 1。 开启壁纸
  549. // 黑胶回:0x78, 2, 1 ,1。 0x78, 2, 0, 2 。 1成功,2失败
  550. // 小程序:0x80, [参考wifi指令], [0x22,总长度,0x33,包长,包数,0x44,md5长,md5]
  551. // 黑胶回:0x80, 1, 1。 0x80, 0, 2。 1成功,2失败
  552. // 小程序:0x79, 数据长度,数据
  553. // 黑胶回:0x79, 1, 1 。0x79, 0, 2 。 1成功,2失败
  554. // 小程序:0x78, 0。结束了
  555. // 黑胶回:0x78, 2, 0, 1 。 0x78, 2, 0, 3 。 0流程成功,3流程失败
  556. // 小程序: 0x78, 2。异常结束
  557. if (value === 1 && kind == 1) {
  558. // 开始校验md5
  559. _this.sendImageMD5()
  560. // _this.sendImage()
  561. _this.startProgress()
  562. } else if (value === 0 && (kind == 2 || kind == 3)) {
  563. // 发送失败
  564. _this.failSend(true)
  565. } else if (value === 0 && kind == 1) {
  566. // 发送完成
  567. _this.successSend()
  568. } else {
  569. // 发送失败
  570. _this.failSend(true)
  571. }
  572. break;
  573. case EnumCmdEvent.wallPaperMD5:
  574. // 0x80
  575. console.log("开始发送MD5回复", kind, value)
  576. // 收到回复md5,开始发送图片的第一片
  577. if (kind == 1 && value === 1) {
  578. _this.data._imgIndex = 0
  579. _this.sendImage(_this.data._imgIndex)
  580. } else if (kind == 0 && value === 3) {
  581. _this.failSend(false)
  582. wx.showModal({
  583. title: '发送图片失败,请重启设备再试试吧',
  584. showCancel: false,
  585. success: function (res) {
  586. if (res.confirm) {
  587. console.log('用户点击确定')
  588. }
  589. }
  590. })
  591. } else {
  592. _this.failSend(true)
  593. }
  594. break;
  595. case EnumCmdEvent.wallPaperData:
  596. // 0x79
  597. // 收到回复md5,开始发送图片后面N片
  598. if (kind == 1 && value === 1) {
  599. _this.sendImage(_this.data._imgIndex)
  600. } else {
  601. _this.failSend(true)
  602. }
  603. break;
  604. default:
  605. break;
  606. }
  607. }, this)
  608. },
  609. /**
  610. * 生命周期函数--监听页面初次渲染完成
  611. */
  612. onReady() {
  613. },
  614. /**
  615. * 生命周期函数--监听页面显示
  616. */
  617. onShow() {
  618. },
  619. /**
  620. * 生命周期函数--监听页面隐藏
  621. */
  622. onHide() {
  623. },
  624. /**
  625. * 生命周期函数--监听页面卸载
  626. */
  627. onUnload() {
  628. eventBus.removeNotification(CmdEvent.eventName, this);
  629. },
  630. /**
  631. * 页面相关事件处理函数--监听用户下拉动作
  632. */
  633. onPullDownRefresh() {
  634. },
  635. /**
  636. * 页面上拉触底事件的处理函数
  637. */
  638. onReachBottom() {
  639. },
  640. /**
  641. * 用户点击右上角分享
  642. */
  643. onShareAppMessage() {
  644. }
  645. })