H5 拍照上传图片,压缩图片方法 ImageCompressor

2023-12-21 15:42:41

参考文章:js-image-compressor 图片压缩插件-CSDN博客

<!-- //相机 ?//capture:user(前置摄像头)、environment(后置摄像头) -->

? ? ? ? ? <div class="file-box">

? ? ? ? ? ? <span class="btn">拍照压缩上传</span>

? ? ? ? ? ? <input

? ? ? ? ? ? ? class="file-btn"

? ? ? ? ? ? ? type="file"

? ? ? ? ? ? ? id="photo"

? ? ? ? ? ? ? capture="environment"

? ? ? ? ? ? ? accept="image/*"

? ? ? ? ? ? ? name="photo"

? ? ? ? ? ? ? @change="selectPhoto()" />

? ? ? ? ? </div>

样式:

.file-box {

? height: 32px;

? width: 74px;

? display: inline-block;

? position: relative;

? overflow: hidden;

}

.file-btn {

? position: absolute;

? width: 100%;

? height: 100%;

? top: 0;

? left: 0;

? opacity: 0;

}

.btn {

? display: inline-block;

? width: 100%;

? height: 100%;

? text-align: center;

? line-height: 32px;

? border-radius: 3px;

? font-weight: 400;

? font-size: 14px;

? background: #3274f9;

? color: #fff;

}

?<script>

import { getLocation, getDistances } from '../../pub/pub'

import noMessage from '@/components/noMessage.vue'

import ImageCompressor from 'js-image-compressor'

export default {

? components: { noMessage },

? data() {

? ? return {

? ? ? isLoading: false,

? ? ? isShowType: false,

? ? ? checkedValue: false,

? ? ? showPopToast: false,

? ? ? scanFlag: false,

? ? ? messageValue: '',

? ? ? textValue: '',

? ? ? currentType: '请选择',

? ? ? columnsType: [],

? ? ? currentData: {},

? ? ? stationName: '',

? ? ? lat: '',

? ? ? lng: '',

? ? ? fileList: [],

? ? ? timer: null,

? ? ? firstStatus: false,

? ? ? secondStatus: false,

? ? ? currentPageData: {

? ? ? ? firstStatus: false,

? ? ? ? secondStatus: false,

? ? ? ? stationImg: ''

? ? ? },

? ? ? actions: [

? ? ? ? {

? ? ? ? ? name: '拍照',

? ? ? ? ? id: 0

? ? ? ? },

? ? ? ? {

? ? ? ? ? name: '相册选图',

? ? ? ? ? id: 1

? ? ? ? }

? ? ? ]

? ? }

? },

? created() {

? ? this.getType()

? ? this.getLocationEvent() // 获取定位

? ? //console.log(getDistances(第一点的纬度, 第一点的经度, 第二点的纬度, 第二点的经度))

? ? // console.log(777, getDistances(23.048884, 113.760234, 23.02067, 113.75179))

? ? // let distance = getDistances(23.048884, 113.760234, 23.02067, 113.75179)

? ? // console.log('根据经纬度计算距离==', distance, distance.km, distance.m)

? },

? mounted() {

? ? this.currentData = JSON.parse(this.$route.query.data)

? ? // this.stationName = this.currentData.stationName

? ? // console.log('this.currentData==', this.currentData)

? ? if (this.currentData.taskId) {

? ? ? this.getStation_survey()

? ? }

? },

? methods: {

? ? changeValue(val) {

? ? ? this.checkedValue = val

? ? },

? ? getType() {

? ? ? let params = {

? ? ? ? typeName: 'towerPoleType' // 塔桅类型

? ? ? }

? ? ? this.$Api.type(params).then(res => {

? ? ? ? this.columnsType = res.data.data.map(v => v.label)

? ? ? })

? ? },

? ? onConfirmType(value) {

? ? ? this.isShowType = false

? ? ? this.currentType = value

? ? },

? ? // 基站签到查询接口

? ? getStation_survey() {

? ? ? let params = {

? ? ? ? taskId: this.currentData.taskId

? ? ? }

? ? ? this.$Api.station_survey(params).then(res => {

? ? ? ? this.currentPageData = res.data.data

? ? ? ? this.stationName = this.currentPageData.stationName

? ? ? ? if (this.currentPageData.latitude) {

? ? ? ? ? this.lat = this.currentPageData.latitude

? ? ? ? ? this.lng = this.currentPageData.longitude

? ? ? ? }

? ? ? })

? ? },

? ? // 勘测完成

? ? doComplete() {

? ? ? if (this.checkedValue && !this.textValue) {

? ? ? ? return this.$Toast('请填写原因说明!')

? ? ? }

? ? ? let params = {

? ? ? ? taskId: this.currentData.taskId,

? ? ? ? // stationImg: this.currentPageData.stationImg,

? ? ? ? towerPoleType: this.currentType, // 塔桅类型

? ? ? ? problemDescription: this.messageValue, // 问题描述

? ? ? ? unableSurvey: this.checkedValue, // 是否无法勘站

? ? ? ? unableSurveyReason: this.textValue // 无法勘站原因说明

? ? ? }

? ? ? if ((this.currentPageData.firstStatus && this.currentPageData.secondStatus) || this.checkedValue) {

? ? ? ? this.$Api.station_survey_submit(params).then(res => {

? ? ? ? ? this.$router.push({ path: '/home' })

? ? ? ? })

? ? ? } else {

? ? ? ? this.$Toast('请完成勘测再点击或选择无法勘站!')

? ? ? }

? ? },

? ? // 天馈勘察

? ? goMeasureTian() {

? ? ? this.$router.push({ path: '/measureTian', query: { id: this.currentData.taskId } })

? ? },

? ? //获取定位

? ? async getLocationEvent() {

? ? ? let _this = this

? ? ? await getLocation(function (longitude, latitude) {

? ? ? ? // this.$Toast.success('位置更新成功')

? ? ? ? window.sessionStorage.setItem('longitude', longitude)

? ? ? ? window.sessionStorage.setItem('latitude', latitude)

? ? ? ? _this.lat = latitude + 0

? ? ? ? _this.lng = longitude + 0

? ? ? ? console.log('当前位置经纬度==', _this.lat, _this.lng)

? ? ? })

? ? },

? ? clickUpload() {

? ? ? this.fileList = [] // 重置上传文件,默认取第一个

? ? },

? ? // 基站签到--拍照

? ? async afterRead(file) {

? ? ? await this.getLocationEvent() // 获取定位

? ? ? //console.log(getDistances(第一点的纬度, 第一点的经度, 第二点的纬度, 第二点的经度))

? ? ? // let distance = getDistances(23.048884, 113.760234, 23.02067, 113.75179)

? ? ? let distance = getDistances(this.currentData.latitude, this.currentData.longitude, this.lat, this.lng)

? ? ? // 大于500米范围的不允许签到

? ? ? if (distance.m < 500) {

? ? ? ? this.showPopToast = true

? ? ? } else {

? ? ? ? let formData = new FormData()

? ? ? ? // formData.append('file', file.file)

? ? ? ? formData.append('file', file)

? ? ? ? formData.append('stationCode', this.currentData.stationCode)

? ? ? ? await this.$Api

? ? ? ? ? .photo_upload(formData)

? ? ? ? ? .then(async res => {

? ? ? ? ? ? if (res.data.code == 200) {

? ? ? ? ? ? ? this.currentPageData.firstStatus = true // 第一步成功后

? ? ? ? ? ? ? this.currentPageData.stationImg = res.data.data

? ? ? ? ? ? ? let params = {

? ? ? ? ? ? ? ? taskId: this.currentData.taskId, //工单号

? ? ? ? ? ? ? ? imgPath: res.data.data, //图片路径

? ? ? ? ? ? ? ? stationCode: this.currentData.stationCode, //站号

? ? ? ? ? ? ? ? longitude: this.lng, //经度

? ? ? ? ? ? ? ? latitude: this.lat //纬度

? ? ? ? ? ? ? }

? ? ? ? ? ? ? await this.$Api

? ? ? ? ? ? ? ? .sign_in(params)

? ? ? ? ? ? ? ? .then(resp => {

? ? ? ? ? ? ? ? ? if (resp.data.code == 200) {

? ? ? ? ? ? ? ? ? ? this.$Toast.success('签到成功')

? ? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? this.$Toast('签到失败')

? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? })

? ? ? ? ? ? ? ? .catch(() => {

? ? ? ? ? ? ? ? ? this.$Toast('签到失败')

? ? ? ? ? ? ? ? })

? ? ? ? ? ? } else {

? ? ? ? ? ? ? this.$Toast('拍照上传失败!')

? ? ? ? ? ? }

? ? ? ? ? })

? ? ? ? ? .catch(() => {

? ? ? ? ? ? this.$Toast('拍照上传失败!')

? ? ? ? ? })

? ? ? }

? ? },

? ? selectPhoto() {

? ? ? let _this = this

? ? ? let file = document.getElementById('photo').files[0]

? ? ? let content = null

? ? ? let readfile = new FileReader()

? ? ? if (file != undefined) {

? ? ? ? // console.log('===',file.size/1024);

? ? ? ? // 如果图片大于1兆,就进行压缩

? ? ? ? if(file.size/1024 > 1024) {

? ? ? ? ? // 压缩图片

? ? ? ? ? _this.compressionImage(file)

? ? ? ? } else {

? ? ? ? ? // 不压缩

? ? ? ? ? content = readfile.readAsDataURL(file, 'UTF-8')

? ? ? ? ? readfile.onload = function (event) {

? ? ? ? ? ? content = event.target.result

? ? ? ? ? ? // 将Blod 格式转为file文件格式传给后端接口

? ? ? ? ? ? let blod = _this.base64ToFile(content, new Date().getTime() + '.png')

? ? ? ? ? ? _this.afterRead(blod)

? ? ? ? ? }

? ? ? ? }

? ? ? ? readfile.onerror = function (event) {

? ? ? ? ? console.log('err')

? ? ? ? }

? ? ? } else {

? ? ? ? console.log('未拍照')

? ? ? }

? ? },

? ? //转为文件

? ? base64ToFile(urlData, fileName) {

? ? ? let arr = urlData.split(',')

? ? ? let mime = arr[0].match(/:(.*?);/)[1]

? ? ? let bytes = atob(arr[1])

? ? ? let n = bytes.length

? ? ? let ia = new Uint8Array(n)

? ? ? while (n--) {

? ? ? ? ia[n] = bytes.charCodeAt(n)

? ? ? }

? ? ? return new File([ia], fileName, { type: mime })

? ? },

? ? // 计算base64编码图片大小

? ? getBase64ImageSize(base64) {

? ? ? const indexBase64 = base64.indexOf('base64,')

? ? ? if (indexBase64 < 0) return -1

? ? ? const str = base64.substr(indexBase64 + 6)

? ? ? // 大小单位:字节

? ? ? return (str.length * 0.75).toFixed(2)

? ? },

? ? // 压缩图片

? ? compressionImage(file) {

? ? ? let _this = this

? ? ? let content = null

? ? ? let readfile = new FileReader()

? ? ? return new Promise((resolve, reject) => {

? ? ? ? // eslint-disable-next-line no-new

? ? ? ? new ImageCompressor({

? ? ? ? ? file: file,

? ? ? ? ? quality: 0.8,

? ? ? ? ? maxWidth: 88,

? ? ? ? ? maxHeight: 88,

? ? ? ? ? redressOrientation: false,

? ? ? ? ? // 压缩前回调

? ? ? ? ? beforeCompress: function (result) {

? ? ? ? ? ? console.log('压缩之前图片尺寸大小: ', result.size)

? ? ? ? ? ? console.log('mime 类型: ', result.type)

? ? ? ? ? },

? ? ? ? ? success: function (result) {

? ? ? ? ? ? console.log('压缩之后图片尺寸大小: ', result.size, result)

? ? ? ? ? ? console.log('mime 类型: ', result.type)

? ? ? ? ? ? console.log('实际压缩率: ', (((file.size - result.size) / file.size) * 100).toFixed(2) + '%')

? ? ? ? ? ? content = readfile.readAsDataURL(result, 'UTF-8')

? ? ? ? ? ? readfile.onload = function (event) {

? ? ? ? ? ? ? content = event.target.result

? ? ? ? ? ? ? let blod = _this.base64ToFile(content, new Date().getTime() + '.png')

? ? ? ? ? ? ? _this.afterRead(blod)

? ? ? ? ? ? }

? ? ? ? ? ? resolve(result)

? ? ? ? ? },

? ? ? ? ? error(e) {

? ? ? ? ? ? reject(e)

? ? ? ? ? }

? ? ? ? })

? ? ? })

? ? },

? ? // 下拉刷新

? ? onRefresh() {

? ? ? this.timer = setTimeout(() => {

? ? ? ? this.$Toast('刷新成功')

? ? ? ? this.isLoading = false

? ? ? ? this.getStation_survey()

? ? ? ? this.getLocationEvent() // 获取定位

? ? ? }, 1000)

? ? }

? },

? beforeDestroy() {

? ? this.timer && clearTimeout(this.timer)

? }

}

</script>

文章来源:https://blog.csdn.net/wwf1225/article/details/135130899
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。