/*** 可预览图片  ++水印   名字 部门  当前时间*/
import React, { Component } from 'react';
import { ImagePicker } from 'antd-mobile';
import { Toast } from '@/pages/project/yjpt/components/PandaToast.jsx'
import envconfig from "@/envconfig/envconfig";
import Carousel, { ModalGateway, Modal } from 'react-images'import './index.less';
import { getUsrInfo } from '@/util/localUitl'
import moment from 'moment';class PicturePreview extends Component {static defaultProps = {label: '',name: '',value: '',placeholder: '',readOnly: 0}state = {isShowModal: false,}toggleModal = () => {this.setState({isShowModal: !this.state.isShowModal,})}mapUrl = (url) => {if(url.includes('base64')) {return url;}return `${envconfig.pandaURL}/cityinterface/rest/services/filedownload.svc/download${url}`;}handleChange = (files, type) => {if(type === 'add') {const len = files.length;const newFile = files[len - 1];
//newFile 就是被上传文件的一些信息  和input 中text=file是一样的道理this.changeFileFormat(newFile)// this.uploadImage(newFile);} else if(type === 'remove') {const { value } = this.props;const urls = value.split(',');const removeUrl = urls.filter(url => !files.find(file => file.url === url));if(removeUrl.length > 0) {this.deleteImage(removeUrl[0]);}}}// 格式转换成base64 添加水印changeFileFormat=(url) =>  {let that=thislet file = url.file;let fileReader = new FileReader();fileReader.onloadend = function () {if (fileReader.readyState == fileReader.DONE) {// console.log(fileReader)that.getBase64Time(fileReader.result).then(res=>{//此时已经完成水印的添加let data=that.base64TOfile(res)that.uploadImage(data)})}};fileReader.readAsDataURL(file);}// to  base64getBase64Time(url){let that =this;return new Promise((resolve, reject)=>{//异步处理let canvas = document.createElement("canvas"),ctx = canvas.getContext("2d"),image = new Image(),fontSize, //水印的大小MAX_WH = 800;//图片的最大宽高比,因为在以上方法中获取的照片size太大,上传时耗时太多所以需要做处理image.crossOrigin = "Anonymous";image.onload = function() {//这里是一个异步,所以获取到的base64文件需要用回调if (image.height>MAX_WH) {image.width *= MAX_WH/image.height;image.height = MAX_WH}if (image.width>MAX_WH) {image.height *= MAX_WH/ image.width;image.width = MAX_WH;}canvas.height = image.height;canvas.width = image.width;ctx.drawImage(image, 0, 0, image.width, image.height);// if(image.width>100 && image.width<500){//     fontSize = '24px'// }else if(image.width>=500 && image.width<1000){//     fontSize = '44px'// }else if(image.width>=1000 && image.width<1500){//     fontSize = '64px'// }ctx.font =`30px Arial`;ctx.fillStyle = "tomato";let time = moment().format('YYYY-MM-DD HH:mm:ss');//获取当前的时间ctx.textAlign = "end";let str = `${time}\n${getUsrInfo().fullName} ${getUsrInfo().depart.name}`;let b = 30;let lineheight = 30;let lines = str.split('\n');for (let j = 0; j<lines.length; j++){ctx.fillText(lines[j], image.width-20, image.height- ((j+1)*lineheight) );}ctx.textBaseline = "middle";// ctx.fillText(time, image.width-20, image.height-20);let dataURL = canvas.toDataURL( "image/png/jpg");if(dataURL) {resolve(dataURL)}else{reject("err")}};image.src = url})}// 再转换成file,用于保存base64TOfile(base64){let that = this;let arr = base64.split(',');let mime = arr[0].match(/:(.*?);/)[1];let bstr = atob(arr[1]); // 解码base-64编码的数据let n = bstr.length; let u8arr = new Uint8Array(n);// 无符号整型数组while(n--){u8arr[n] = bstr.charCodeAt(n);}//转换成file对象let filename = new Date().getTime();let filetest = new File([u8arr], filename, {type:mime})return filetest}// 上传图片uploadImage = async (file) => {const { type } = file;console.log(moment(file.lastModified).format('YYYY-MM-DD HH:mm:ss'))const { upload, value, name, onChange } = this.props;const formData = new FormData();formData.append('filedata', file);const now = +new Date();const imgType = type.split("/")[1] || 'png';const path = `/WebApp/${name}/${now}.${imgType}`;console.log(this.mapUrl(path))const params = {imagePath: path,data: formData}Toast.loading('图片上传中...', 0);try{const res = await upload(params);Toast.hide();if(res.success) {let newVal = '';if(value === '') {newVal = path;} else {newVal = value + ',' + path;}onChange && typeof onChange === 'function' && onChange(name, newVal);}}catch(e){console.log(e)}}
// 删除deleteImage = async (url) => {const { deleteImage, value, onChange, name } = this.props;const params = {imagePath: url};Toast.loading('图片删除中...', 0);const res = await deleteImage(params);Toast.hide();if(res.status) {const urls = value.split(',');const newUrls = urls.filter(u => u !== url);// console.log(urls, newUrls, url);onChange && typeof onChange === 'function' && onChange(name, newUrls.join(','));}}render() {const { isShowModal, } = this.state;const { label = '', name = '', value = '', placeholder = '', readOnly = 0, unit = '', max = 4 } = this.props;const files = value.split(',').filter(url => !!url).map(url => ({url: this.mapUrl(url)}));const views = files.map((item) => {return {src: item.url}})return (<div className={`PicturePreview`}><div className="label" id='label'>{label}</div><ImagePickerfiles={files}onChange={this.handleChange}onImageClick={this.toggleModal}disableDelete={readOnly}selectable={(files.length < max) && !readOnly}/><ModalGateway>{isShowModal ? (<Modal onClose={this.toggleModal}><Carousel views={views} /></Modal>) : null}</ModalGateway></div>);}
}export default PicturePreview;

h5拍照添加水印上传相关推荐

  1. 织梦DEDECMS 整合Kindeditor编辑器美化版nkeditor版可H5多图上传摒弃SWF上传

    织梦插件说明 织梦DEDECMS 整合Kindeditor编辑器美化版nkeditor版可H5多图上传摒弃SWF上传(UTF版) 本修改整合了Kindeditor编辑器美化版 功能: 1.可多图上传( ...

  2. flash在线拍照并上传到后台(servlet)

    一.flash在线拍照并上传到后台(servlet) 第一步:先新建一个ActionScript文件:ShiBieFunction.as 该文件的核心代码如下: =========使用摄像头获取视频流 ...

  3. android 实现自动拍照,android 调用摄像头自动拍照 并上传到YEELINK

    前几天看到yeelink这个网站很感兴趣,注册了个图像传感器,就想着写个程序调用安卓摄像头并上传照片 程序很简单这个还是记录一下 首先是权限,分别是联网,相机,文件读取,照相和自动对焦的权限 然后是代 ...

  4. 摄像头网页服务器,js调用本地摄像头拍照并上传到web服务器

    [实例简介] js调用本地摄像头拍照并上传到web服务器.后台使用java实现图片的接收和存储,上传的图片默认保存到项目下的images文件夹中. [实例截图] [核心代码] MyCamera └── ...

  5. vue H5页面调用手机相机拍照/图库上传

    //html//相机 //capture:user(前置摄像头).environment(后置摄像头) <input type="file" id="photo&q ...

  6. android h5 多图上传源码,JS移动端/H5同时选择多张图片上传并使用canvas压缩图片...

    最近在做一个H5的项目,里边涉及到拍照上传图片的功能以及识别图片的功能,这里对识别图片的功能不做赘述,不属本文范畴.我在做完并上线项目后,同事跟我提了一个要求是可不可以同时选择多张图片上传,我做的时候 ...

  7. 公众号 h5 页面 图片上传 wx.chooseImage使用

    刚开始直接在H5里使用了wx.chooseImage,发现在开发者工具中不断的报错the permission value is offline verifying,慢慢开始搜索才发现在小程序的web ...

  8. h5 实现图片上传 案例

    如何在h5 中实现图片上传 ? (单图片上传) 先写一个按钮 ,通过点击按钮触发文件上传的onclick 事件 <div class="btn" onclick=" ...

  9. HTML5调用本地摄像头画面,拍照,上传服务器

    实现功能和适用业务 采集本地摄像头获取摄像头画面,拍照保存,上传服务器: 前端上传图片处理,展示,缩小,裁剪,上传服务器 实现步骤 调取本地摄像头(getUserMedia)/上传图片,将图片/视频显 ...

最新文章

  1. 简单自学机器学习理论——正则化和偏置方差的权衡 (Part III )
  2. java list 结构_Java中常见数据结构List之ArrayList
  3. http statusCode(状态码)
  4. 昂靠的由来[本博作者爆料]
  5. 开机流程与主引导分区(MBR)——鸟哥私房菜
  6. 使用memcachedclientXmemcached与Spring整合
  7. Spring Boot数据持久化之NamedParameterJdbcTemplate
  8. Mac下compare beyond无限使用
  9. win10字体安装_Win10操作系统下字体的安装教程(非常详细,适合新手DIY)
  10. 全国高等学校非计算机专业计算机水平考试一级,全国高等学校计算机一级考试选择题题库及答案参考...
  11. 计算机开启宏功能吗,如何在excel2016正式版中启用/设置宏功能?
  12. 麒麟桌面系统添加字体
  13. c++中引用、指针、值的区别与用途详解
  14. vue-cli在webpack环境下怎样生成开发环境模板(适合初学者)
  15. python表示差值_Python算法之差值查找-Testfan打卡学测开0116
  16. APICloud和海马玩模拟器结合调试手机页面
  17. C语言入门,编写程序,输出两个整数中的较大值。
  18. GSMA公布2018世界移动大会-上海的最新进展
  19. ROS学习记录(二)阿克曼转向车运动学模型及在gazebo中搭建仿真环境
  20. 推荐系统[四]:精排-详解排序算法LTR (Learning to Rank): poitwise, pairwise, listwise相关评价指标,超详细知识指南。

热门文章

  1. JIURL键盘驱动 3
  2. html 阅读swf,网页嵌入式 HTML5+Flash(swf) 视频播放器
  3. Using PyTorch Version of YOLOV3/TinyYOLOV3
  4. pandownload使用cookie登录
  5. intval的绕过和chr的利用
  6. Openstack租户(项目)、用户、角色的概念与管理
  7. pa皮安级电流检测电路
  8. (转)卡马克卷轴算法研究
  9. windows系统下多个程序窗口快速切换的方法
  10. maven项目配置阿里云镜像下载jar包