App上传多张照片加水印,会出现有个别图片被拉升或者被裁剪,怎么处理
<template>
<view>
<view :class="!flag ? '' :'loop-img-box'" v-for="(photo,index) in photoData" :key='photo'>
<image :class="!flag? 'img-list':'preview-loop-pic'" :src="photo" @tap='previewPhoto(photoData,index)' mode="aspectFill">image>
<view v-if="num > 1" class="q-image-remover" :data-idx="index" data-typ="box" @click="btnDeleteImg(index)">
<image :class="!flag ? 'delete delete-aa' : 'bxdelete delete'" src="@/static/delete_1.jpg" mode="widthFix">image>
view>
<image :class="!flag ? 'img' : 'add-gray-img'" @tap='chooth(num)' :src="src" mode="aspectFit" v-if="photoData.length > image>
<canvas :style="`width:${sWidth}px; height:${sHeight}px;`" canvas-id="imgCanvas" id="imgCanvas">canvas>
view>
template>
<script>
import req from '@/common/request.js';
export default {
data() {
return {
flagC: false,
photoData: this.photoList,
photoArray: [],
// photoArray: [],
// canvasWidth: '',
// canvasHeight: '',
sWidth:'',
sHeight:'',
photoIndex: 0,
scId:this.scList,
Arr:[],
imgList:[],
// src1:this.src
}
},
props:['num','typeimg','photoList','scList','src','flag'],
onShow() {
// console.log(this.src);
},
methods: {
chooth(num){
// console.log(this.photoData.length);
// console.log(num);
this.Arr = []
var number = this.num - this.photoData.length
var my = this
var array = []
my.photoArray = []
my.File = []
uni.chooseImage({
count: number, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
success: function (res) {
//图片数组
// console.log(res);
let tempFilePath = res.tempFilePaths;
let num1 = 0
let inter = setInterval(()=>{
my.setimg(tempFilePath[num1],res.tempFilePaths.length)
// console.log(num1);
// console.log(res.tempFilePaths.length);
num1++;
if(num1 == tempFilePath.length){
// console.log('111');
num1 = 0;
clearInterval(inter);
return;
}
},700)
}
});
},
//图片上传
tpsc(tps){
// console.log(tps);
var url =req.HttpHost + '/portal.php?resid=fileUpload.uploader';
var sc=new Array(tps.length);
this.digui(0,tps,url,sc);
},
//异步递归
digui(index,arr,url,sc){
// console.log(index,arr.length)
if(index == arr.length){
uni.hideLoading();
// console.log(this.scId);
this.$emit('tijiaoImg',this.scId,this.typeimg)
return;
}
var my=this;
uni.uploadFile({
url: url,
filePath: arr[index],
name: 'file',
success: (uploadFileRes) => {
var res = JSON.parse(uploadFileRes.data);
sc[index]=res.data.id;
if(index ==(arr.length -1)){
// my.scId = sc
// console.log(sc);
sc.forEach(item =>{
my.scId.push(item)
})
}
index++;
// console.log(index);
my.digui(index,arr,url,sc);
},
fail: (res) => {
// console.log(res)
}
})
},
translateapp(img, scale,callback){
var my = this
plus.io.resolveLocalFileSystemURL(img, (entry) => { //通过URL参数获取目录对象或文件对象
entry.file((file) => { // 可通过entry对象操作图片
// console.log(file);
// console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
if (file.size > 1200 * 1024) { // 如果大于250Kb进行压缩
// console.log('11----');
plus.zip.compressImage({ // 5+ plus.zip.compressImage 了解一下,有详细的示例
src: img, //src: 压缩原始图片的路径
dst: img.replace('.png', 'yasuo.png').replace('.PNG',
'yasuo.PNG').replace('.jpg', 'yasuo.jpg')
.replace('.JPG', 'yasuo.JPG'),
width: '40%', //dst: (String 类型 )压缩转换目标图片的路径,这里先在后面原始名后面加一个yasuo区分一下
height: '40%', //width,height: (String 类型 )缩放图片的宽度,高度
quality: scale, //quality: (Number 类型 )压缩图片的质量
overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
// format:'jpg' //format: (String 类型 )压缩转换后的图片格式
}, (event) => {
// console.log(event.target);
callback(event.target);
}, function(err) {
console.log('Resolve file URL failed: ' + err.message);
});
} else {
callback(img);
// console.log('222');
}
})
}, (e) => { // 返回错误信息
// console.log('Resolve file URL failed: ' + e.message);
})
// console.log(my.File);
},
setimg(e,num){
uni.showLoading({
title: '上传中...',
mask:true,
})
let name = getApp().globalData.ryinfo.qymc
let that = this;
// let ctx = uni.createCanvasContext('myCanvas',this);
that.imgList = []
// that.Arr = []
uni.getSystemInfo({//获取设备信息
success: info => {
uni.getImageInfo({//获取图片信息
src:e,
success: async (res) => {
//设备宽
const sWidth = info.windowWidth || 375;
//按图片长宽比,算出高度
let sHeight = sWidth / (res.width / res.height);
sHeight=Number(sHeight.toFixed(0));
//赋值给canvas
that.sWidth=sWidth;
that.sHeight=sHeight;
await that.sleep(200)
const ctx = uni.createCanvasContext('imgCanvas');
ctx.fillRect(0, 0, sWidth, sHeight);
ctx.font = 'normal bold 15px Source Han Sans CN';
//将图片src放到cancas内
// if(devBgImg.complete) { // 如果图片已经存在于浏览器缓存,直接调用回调函数
// ctx.drawImage(res.path, 0, 0, res.width,res.height,0,0,sWidth, sHeight);
// return; // 直接返回,不用再处理onload事件
// }
// devBgImg.onload=function(){
// ctx.drawImage(res.path, 0, 0, res.width,res.height,0,0,sWidth, sHeight);
// };
ctx.drawImage(res.path, 0, 0, res.width,res.height,0,0,sWidth, sHeight);
if(res.width < 700){
// console.log('111');
ctx.setFontSize(30);
}else if(res.width < 300){
// console.log('222');
ctx.setFontSize(5);
}else{
// console.log('333');
ctx.setFontSize(40);
}
//处理图片
ctx.rotate(45 * Math.PI / 180);
for (let j = 1; j < 6; j++) { //用for循环达到重复输出文字的效果,这个for循环代表纵向循环
ctx.beginPath();
// ctx.setFontSize(50);
ctx.setFillStyle("rgba(150, 150, 150, 0.3)");
ctx.fillText(name, 0, 150 * j);
for (let i = 1; i < 6; i++) { //这个for循环代表横向循环,
ctx.beginPath();
// ctx.setFontSize(50);
ctx.setFillStyle("rgba(150, 150, 150, 0.3)");
ctx.fillText(name, 650 * i, 180 * j);
}
} //两个for循环的配合,使得文字充满斜对角线的左下部分
// 对斜对角线以右部分进行文字的填充逻辑同上
for (let j = 0; j < 6; j++) {
ctx.beginPath();
// ctx.setFontSize(50);
ctx.setFillStyle("rgba(150, 150, 150, 0.3)");
ctx.fillText(name,0, -150 * j);
for (let i = 1; i < 6; i++) {
ctx.beginPath();
// ctx.setFontSize(50);
ctx.setFillStyle("rgba(150, 150, 150, 0.3)");
ctx.fillText(name, 650 * i, -180 * j);
}
}
ctx.rotate(-45 * Math.PI / 180);
//导出图片
that.$nextTick(() => {
ctx.draw(false, async() => {
await that.sleep(500)
uni.canvasToTempFilePath({ //将画布中内容转成图片,即水印与图片合成
canvasId: 'imgCanvas',
success: (res) => {
// console.log(res);
that.Arr.push(res.tempFilePath)
// that.photoData.push(res.tempFilePath)
// console.log(num);
// console.log(that.Arr.length);
if(num == that.Arr.length){
console.log('添加图片');
let Arr1 = []
for (var i = 0; i < that.Arr.length; i++) {
that.translateapp(that.Arr[i], 80, imgUrl => {
// console.log(imgUrl);
that.photoData.push(imgUrl)
Arr1.push(imgUrl)
})
}
setTimeout(function() {
that.tpsc(Arr1)
}, 600);
}
}
},this)
});
})
}
})
}
})
},
sleep(millisecond) {
return new Promise((resolve) => {
setTimeout(resolve, millisecond)
})
},
// 预览图片
previewPhoto(arr,index) {
uni.previewImage({
current:index, //预览图片的下标
urls:arr, //预览图片的地址,必须要数组形式,如果不是数组形式就转换成数组形式就可以
// loop:true,
})
// this.$forceUpdate()this
},
// 删除照片
btnDeleteImg(index){
var my = this
my.photoData.splice(index, 1);
my.Arr.splice(index, 1);
// console.log(my.photoData);
my.$set(my.photoData)
my.scId.splice(index, 1);
my.$set(my.scId)
// my.$forceUpdate()
my.$emit('tijiaoImg',my.scId,my.typeimg)
},
}
}
script>
<style>
.loop-img-box {
width: 100rpx;
height: 64rpx;
position: relative;
margin-left: 24rpx;
margin-bottom: 16rpx;
}
uni-view{
display: inline-block !important;
}
.preview-loop-pic {
width: 100rpx;
height: 64rpx;
}
.img-list{
/* position: relative; */
padding: 20rpx ;
width: 160rpx !important;
height: 110rpx !important;
/* vertical-align: bottom; */
}
.add-gray-img {
width: 48rpx;
height: 48rpx;
}
.delete-aa{
/* position: absolute !important; */
top: -120rpx;
right: 24rpx;
}
.bxdelete{
top: -50rpx;
right: 10rpx;
}
.img{
width: 160rpx;height: 110rpx;padding: 20rpx;
}
/* .content {
padding: 20upx;
} */
.photo,
.photo image {
display: inline-block;
width: 220upx;
height: 220upx;
}
.btnAddPhoto {
width: 220upx;
height: 220upx;
border: dashed 1px #aaa;
display: flex;
justify-content: center;
align-items: center;
font-size: 50upx;
}
canvas {
border: solid 1px gray;
position: absolute;
left: 5000upx;
}
style>
出现图片被拉升或者被裁剪的原因可能是因为图片的尺寸不一致,或者图片的比例与容器的比例不一致。为了解决这个问题,可以尝试以下几种方法:
统一图片尺寸:将所有图片的尺寸调整为相同的大小,可以使用第三方库或者自己编写代码实现。
调整容器大小:将容器的大小调整为适合所有图片的比例,这样可以避免图片被拉伸或者裁剪。
使用裁剪工具:如果图片的比例与容器的比例不一致,可以使用裁剪工具将图片裁剪成适合容器的比例。
使用缩放工具:如果图片的尺寸过大或者过小,可以使用缩放工具将图片缩放到适当的大小。