原有的上传加水印方式,赶着上需求,最后测出个兼容问题
UploadImg_new.js ,上传组件 请注意,小程序需要引入微信的绘图插件
/**
* (多)图片上传方法(该方法接受一个options)
* @url: string,上传的路径(非必传))
* @count: number,允许单次上传的数量(非必传:1-9)
* @fn: function,操作本地图片路径的回调函数(非必传)
* failCallback:function,某张照片上传失败的回调函数(非必传)
* @storageName: string上传成功之后的缓存的name值(非必传)
* @formData: object,上传时携带的额外参数(非必传)
*/
//这是腾讯位置授权
// var QQMapWX = require('./qqmap-wx-jssdk.min.js');
// var qqmapsdk;
// let qqmapsdk = new QQMapWX({
// key: '2WXBZ-TU7KU-363VM-24TQS-NZ2K5-YBF5H' //这里自己的key秘钥进行填充,开通位置后可查看
// });
// console.log('QQMapWX===', QQMapWX)
import nowTimeStr from "./GetNowTimeStr.js";
const uploadImgew = options => {
let imgChange = options.imgChange //图片变化回调
let uploadId = options.uploadId
let url = options.url
// let qqmapsdk = options.qqmapsdk
let imgType = options.imgType
let that = options.that
let ctxObj = wx.createCanvasContext(options.myCanvas, that)
let picArr = []
let sourType = options.sourType
let myCanvas = options.myCanvas
let setWidth = ''
let setHeight = '500' //默认500
let address = ""
let succImgList = [] //上传成功的图片
let errImgList = [] //上传失败的图片
return new Promise((resolve, reject) => {
//获取经纬度
photoOrcamera_2(sourType)
function photoOrcamera_2(sourType) { //点击图片
// 上传图片先授权位置
// 调取经纬度---改用高德地图
// wx.getLocation({
// type: 'gcj02',
// success: (res) => {
// let location = {
// latitude: res.latitude,
// longitude: res.longitude
// }
// that.selectImgFun(obj,sourType)
//获取详细地址
if (sourType == 'camera') { //相机需要添加水印
getLocal(location, sourType)
} else {
selectImgFun(sourType)
}
// },
// fail: (e) => {
// wx.showToast({
// title: "相机拍照请先授权获取地理位置!",
// icon: 'none',
// duration: 2500
// })
// }
// })
}
// 显示位置
function getLocal(location, sourType) { //传经纬度
let that = this;
// console.log('qqmapsdk', qqmapsdk)
// qqmapsdk.reverseGeocoder({//弃用小程序位置服务
// location: {
// latitude: location.latitude,
// longitude: location.longitude
// },
// success: function (res) {
const app = getApp() //改用高德地图的
// address = res.result.address //地址
address = app.globalData.address + app.globalData.applyReport.streetName
console.log('详细地址',address)
selectImgFun(sourType)
return
//---------------------------------------
// },
// fail: function (res) {
// wx.showToast({
// title: "获取地理位置失败,请重试!",
// icon: 'none',
// duration: 2500
// })
// },
// complete: function (res) {}
// });
}
// 选择图片
function selectImgFun(sourType) {
let ctx = ctxObj
wx.chooseImage({
count: 5,
sizeType: ['original', 'compressed'],
// sourceType: ['album', 'camera'],
sourceType: sourType ? [sourType] : ['album', 'camera'],
success: async (res) => {
wx.showLoading({
title: '上传中...',
mask: true
})
if (sourType == 'camera') { //相机需要加水印
console.log('66666')
for (let i = 0; i < res.tempFilePaths.length; i++) {
let tempFilePath = res.tempFilePaths[i]
console.log('777')
let obj = await addWatermarkFun(tempFilePath, res.tempFilePaths) //单张图片
console.log('777',obj)
if (obj.id) { //有id则成功
console.log('888')
succImgList.push(obj)
} else {
console.log('999')
errImgList.push(obj)
}
}
}else{
for (let i = 0; i < res.tempFilePaths.length; i++) {
let tempFilePath = res.tempFilePaths[i]
let res2 = await uploadFun(tempFilePath)
let obj = {
path: tempFilePath,
id: res2.data ? res2.data : null,
type: imgType,
key: 9999 + Math.floor((Math.random() * 9999999999999))
}
if (obj.id) { //有id则成功
succImgList.push(obj)
} else {
errImgList.push(obj)
}
}
}
let resultData = { //组装最终的数据
code: 200,
succImgList: succImgList,
errImgList: errImgList,
setWidth: setWidth, //图片宽度
setHeight: setHeight //图片高度
}
resolve(resultData)
},
})
}
//获取图片--添加水印
function addWatermarkFun(tempFilePath, imgArr) {
return new Promise((resolve, reject) => {
// 新增图片添加水印后再上传至后台
let createTime = nowTimeStr() //当前时间,我这里封装了公共方法,你可以自己写
//获取图片基本信息
let ctx = ctxObj
console.log('1111',createTime)
wx.getImageInfo({
src: tempFilePath,
success: function (res) {
var width = res.width
var height = res.height
var realRatio = width / height
//获取屏幕宽度
let screenWidth = wx.getSystemInfoSync().windowWidth
//处理一下图片的宽高的比例
width = screenWidth
height = screenWidth / realRatio
if (height > 350) {
setWidth = width
setHeight = parseInt(screenWidth / realRatio)
} else if (height <= 200) {
setWidth = width
setHeight = 200
} else if (200 < height <= 300) {
setWidth = width
setHeight = 250
} else if (300 < height <= 350) {
setWidth = width
setHeight = 320
}
console.log('8-97')
console.log('图片宽高',width, setHeight)
imgChange({width:width,setHeight:setHeight})
ctx.drawImage(res.path, 0, 0, width, setHeight)
// ctx.rotate(Math.PI / 180); //旋转
for (let j = 1; j < 2; j++) {
ctx.beginPath()
ctx.setFontSize(9)
ctx.setFillStyle('red')
ctx.translate(10, 40);
ctx.fillText(address, 0, setHeight - 50)
}
for (let j = 0; j < 1; j++) {
ctx.beginPath()
ctx.setFontSize(9)
ctx.setFillStyle('red')
ctx.fillText(createTime, 0, setHeight - 70)
}
console.log('8-9743333',ctx)
setTimeout(function () { // 发现苹果15.4版本下 苹果12 会间歇不进ctx.draw回调。初始的时候会有问题。暂时延迟处理解决
ctx.draw(false, ()=> {
console.log('0000001')
wx.canvasToTempFilePath({
canvasId: 'myCanvas',
success: async (res) => {
console.log('000000',res)
let imgeList = picArr.concat(res.tempFilePath); //图片显示的url,
picArr = imgeList
setWidth = width
setHeight = parseInt(screenWidth / realRatio)
// 画好照片后传给后台
// let params = {
// fileUrl: res.tempFilePath, //画好后的图片,一张一张的上传
// latitude: latitude,
// longitude: longitude,
// address: that.data.addRess
// }
// console.log('params', params)
let res2 = await uploadFun(res.tempFilePath)
let obj = {
path: res.tempFilePath,
id: res2.data ? res2.data : null,
type: imgType,
key: 9999 + Math.floor((Math.random() * 9999999999999))
}
console.log('000000',obj)
resolve(obj)
},
fail: (e) => {
console.log('上传失败',e)
}
}, that)
})
}, 1000)
},
fail: function (res) {
console.log('错了')
}
})
// 新增图片添加水印后再上传至后台结束
// 是否获取地址 tempFilePaths为照片url
})
}
function uploadFun(tempFilePath) {
return new Promise((resolve, reject) => {
let that = this
let formData = {
damageDate: nowTimeStr(),
type: '1',
node: imgType, //现场损失照片和视频到查勘照片中
// id: app.globalData.id
id: uploadId //上传id
}
wx.uploadFile({
url: getApp().globalData.baseUrl + url, //地址
filePath: tempFilePath,
name: 'file', //文件对应的 key,开发者在服务端可以通过这个 key 获取文件的二进制内容
formData: formData,
header: {
'content-type': 'multipart/form-data'
},
success(res) {
let data = JSON.parse(res.data);
resolve(data)
},
fail: function (err) {
resolve(null)
// wx.hideLoading();
// wx.showToast({
// title: "上传接口调用失败",
// icon: 'none',
// duration: 2500
// })
// if (failCallback) failCallback(val)
}
})
})
}
})
}
export default uploadImgew;
js 页面调用
// 上传获取位置 S
var ctx = wx.createCanvasContext('myCanvas', this)
this.setData({
ctx: ctx
})
let res = await uploadImgew(data)
<canvas class='left-hidden' style="width: 100%; height: {{setHeight}}px;" canvas-id="myCanvas"></canvas>
发现苹果的15.4 系统 第一次操作的时候不会走ctx.draw 回调函数。 猜测是出发绘图方式写法的兼容问题,或是不严谨问题。因为急着上线,使用延迟包含处理,可以暂时解决
|