当前位置:   article > 正文

uni-app+uview组件上传图片时添加水印并保存到相册,具体样式需自己调整_uview upload 选择多张图片并添加水印

uview upload 选择多张图片并添加水印
  1. <template>
  2. <view>
  3. <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" :maxCount="maxCount"
  4. :previewFullImage="true" @oversize="oversize($event)" multiple :maxSize="15728640">
  5. </u-upload>
  6. <!-- 添加水印虚拟结点 -->
  7. <!-- <view style="width: 0px; height: 0px; overflow: hidden">
  8. <canvas :style="'width: '+canvasWidth+'px; height:'+canvasHeight+'px;left:8888px'" canvas-id="myCanvas"></canvas>
  9. </view> -->
  10. </view>
  11. </template>
  12. <script>
  13. import getCurrentLngAndLat from "@/utils/getAddressLocation.js"
  14. import {
  15. HTTP_URL,
  16. HTTP_TEST_URL,
  17. HTTP_DEV_URL
  18. } from '@/const/host'
  19. export default {
  20. name: "UploadComponent",
  21. props: {
  22. maxCount: {
  23. type: Number,
  24. default: 1
  25. },
  26. name: {
  27. type: String,
  28. required: true
  29. },
  30. editUrl: {
  31. type: Array,
  32. default: () => {
  33. []
  34. }
  35. },
  36. types: {
  37. type: String,
  38. default: 'electronic'
  39. },
  40. },
  41. data() {
  42. return {
  43. fileList: [],
  44. src: '',
  45. canvasWidth: 0,
  46. canvasHeight: 0,
  47. address: '',
  48. lng: null,
  49. lat: null
  50. };
  51. },
  52. mounted() {
  53. // 判断是否存在编辑 URL
  54. if (this.editUrl) {
  55. // 将编辑 URL 添加到 fileList 中
  56. if (this.editUrl[0]?.url === '' || this.editUrl[0]?.url === null) {
  57. this.fileList = []
  58. } else {
  59. this.fileList = this.editUrl
  60. }
  61. };
  62. },
  63. watch: {
  64. editUrl: {
  65. immediate: true,
  66. handler(newVal, oldVal) {
  67. if (this.editUrl[0]?.url === '' || this.editUrl[0]?.url === null) {
  68. this.fileList = []
  69. } else {
  70. this.fileList = this.editUrl
  71. }
  72. }
  73. }
  74. },
  75. methods: {
  76. deletePic(event) {
  77. this.fileList.splice(event.index, 1);
  78. this.$emit("filesSelected", {
  79. name: this.name,
  80. fileList: this.fileList
  81. });
  82. },
  83. oversize(event) {
  84. uni.$showMsg('图片大小超过最大限制', 'none')
  85. },
  86. async afterRead(event) {
  87. const lists = [].concat(event.file);
  88. const fileListLen = this.fileList.length;
  89. for (let i = 0; i < lists.length; i++) {
  90. const item = lists[i]
  91. const results = await this.getCurrentLngAndLats();//获取当前定位
  92. let waterUrl = await this.addWatermark(item.url, address);
  93. this.fileList.push({
  94. ...item,
  95. status: "uploading",
  96. message: "上传中"
  97. });
  98. this.$emit("changLoad", true);
  99. try {
  100. const result = await this.uploadFilePromise(waterUrl,results); //上传图片
  101. await this.saveImage(result); //保存图片
  102. const uploadedItem = Object.assign({}, item, {
  103. status: "success",
  104. message: "",
  105. url: result
  106. });
  107. this.fileList.splice(fileListLen + i, 1, uploadedItem);
  108. this.$emit("changLoad", false);
  109. } catch (error) {
  110. const failedItem = Object.assign({}, item, {
  111. status: "fail",
  112. message: "上传失败"
  113. });
  114. this.fileList.splice(fileListLen + i, 1, failedItem);
  115. }
  116. }
  117. this.$emit("filesSelected", {
  118. name: this.name,
  119. fileList: this.fileList
  120. });
  121. },
  122. uploadFilePromise(url,lngLat) {
  123. console.log(lngLat,'000')
  124. // 初始化请求配置项
  125. let host = "";
  126. let envVs = uni.getAccountInfoSync().miniProgram.envVersion;
  127. if (envVs === 'release') {
  128. host = uni.getStorageSync('normal_url')
  129. } else if (envVs === 'trial') {
  130. host = uni.getStorageSync('exp_url')
  131. } else if (envVs === 'develop') {
  132. host = uni.getStorageSync('test_url')
  133. }
  134. // if (envVs === "release") {
  135. // host = HTTP_URL;
  136. // } else if (envVs === "trial") {
  137. // host = HTTP_TEST_URL;
  138. // } else if (envVs === "develop") {
  139. // host = HTTP_DEV_URL;
  140. // }
  141. return new Promise((resolve, reject) => {
  142. // wx.compressImage({
  143. // src: url,
  144. // quality: 90, // 压缩质量,范围为 0 - 100
  145. // success(res) {
  146. // const compressedFilePath = res.tempFilePath;
  147. uni.uploadFile({
  148. url: host + '/api/saler/v1/hhh', // 仅为示例,非真实的接口地址
  149. filePath: url,
  150. name: 'file',
  151. formData: {
  152. type: this.types,
  153. lat: lngLat.lat,
  154. lng: lngLat.lng,
  155. },
  156. header: {
  157. Authorization: 'Bearer ' + uni.getStorageSync('token')
  158. },
  159. success: async (res) => {
  160. if (res.statusCode === 200) {
  161. let arr = JSON.parse(res?.data);
  162. if (arr?.code == 0) {
  163. uni.$showMsg('上传失败', 'none');
  164. resolve('');
  165. } else {
  166. resolve(arr.data?.url);
  167. }
  168. } else {
  169. uni.$showMsg('上传失败', 'none');
  170. resolve('');
  171. }
  172. }
  173. })
  174. // },
  175. // fail(err) {
  176. // console.error('图片压缩失败:', err);
  177. // }
  178. // })
  179. });
  180. },
  181. //添加水印
  182. async addWatermark(img, address) {
  183. const image = img;
  184. let res1 = await new Promise((resolve, reject) => {
  185. uni.getImageInfo({
  186. src: img,
  187. success: (res) => {
  188. // 设置canvas宽高等于原图片宽高
  189. this.canvasWidth = res.width;
  190. console.log(Math.floor(res.width * 0.4), 'Math.floor(res.width*0.4)')
  191. this.canvasHeight = res.height;
  192. // 创建 canvas 的绘图上下文
  193. const ctx = uni.createCanvasContext('myCanvas', this);
  194. // 绘制图片
  195. ctx.drawImage(image, 0, 0, this.canvasWidth, this.canvasHeight);
  196. // 设置水印颜色大小
  197. ctx.setFillStyle('pink');
  198. ctx.setFontSize(Math.floor(res.width * 0.05));
  199. // 水印文字
  200. let time = new Date().toLocaleString();
  201. // 绘制水印文字
  202. ctx.fillText(time, 10, res.height * 0.75);
  203. // ctx.fillText(address, 10, res.height * 0.7);
  204. this.drawWatermark(ctx, '哈哈哈红红火火恍恍惚惚红红火火恍恍惚惚红红火火恍恍惚惚哈哈哈哈', 10, res.height * 0.85, res.width *
  205. 0.8)
  206. // 画到 canvas 中
  207. ctx.draw(false, () => {
  208. // 将画布转化为图片
  209. uni.canvasToTempFilePath({
  210. canvasId: 'myCanvas',
  211. success: (res) => {
  212. resolve(res.tempFilePath);
  213. },
  214. fail: (err) => {
  215. reject(err);
  216. }
  217. }, this);
  218. });
  219. }
  220. });
  221. });
  222. return (res1);
  223. },
  224. // 绘制水印文字
  225. drawWatermark(ctx, text, x, y, maxWidth) {
  226. let words = text.split('');
  227. let line = '';
  228. for (let n = 0; n < words.length; n++) {
  229. let testLine = line + words[n] + '';
  230. let metrics = ctx.measureText(testLine);
  231. let testWidth = metrics.width;
  232. if (testWidth > maxWidth && n > 0) {
  233. ctx.fillText(line, x, y);
  234. line = words[n] + '';
  235. y += y * 0.08;
  236. console.log(y, 'y')
  237. } else {
  238. line = testLine;
  239. }
  240. }
  241. ctx.fillText(line, x, y);
  242. },
  243. //保存图片
  244. saveImage(path) {
  245. uni.downloadFile({ //下载
  246. url: path,
  247. success: (res) => {
  248. uni.saveImageToPhotosAlbum({
  249. filePath: res.tempFilePath,
  250. success: () => {
  251. uni.$showMsg('保存成功', 'none');
  252. },
  253. // fail: (err) => {
  254. // uni.$showMsg('保存失败', 'none');
  255. // }
  256. })
  257. }
  258. })
  259. },
  260. getCurrentLngAndLats: async () => {
  261. const res = await getCurrentLngAndLat();
  262. return res;
  263. },
  264. }
  265. };
  266. </script>
  267. <style scoped>
  268. </style>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/470916
推荐阅读
相关标签
  

闽ICP备14008679号