提交 5fd63f26 authored 作者: 钟是志's avatar 钟是志

增加图片压缩功能

上级 a71787f7
import React from 'react'; import React from 'react';
import { Upload, message } from 'antd'; import {Upload, message} from 'antd';
import config from '@/webPublic/one_stop_public/config'; import config from '@/webPublic/one_stop_public/config';
import {zipImage} from "@/webPublic/zyd_public/utils/handlePhoto";
export default class ImgUploadCom extends React.Component { export default class ImgUploadCom extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
const value = props.value; const value = props.value;
this.state = { this.state = {
url: value, url: value,
}; };
} }
triggerChange = changedValue => {
// Should provide an event to pass value to Form.
const onChange = this.props.onChange;
if (onChange) {
onChange(changedValue);
}
};
componentWillReceiveProps(nextProps) {
// Should be a controlled component.
if ('value' in nextProps) {
const value = nextProps.value;
this.setState({url: value});
}
}
changeUrl = (info, key) => {
if (info.file.status === 'done') {
message.success(`图片上传成功`);
triggerChange = (changedValue) => { if (!('value' in this.props)) {
// Should provide an event to pass value to Form. this.setState({url: info.file.response});
const onChange = this.props.onChange; }
if (onChange) { this.triggerChange(info.file.response);
onChange(changedValue); } else if (info.file.status === 'error') {
} message.error(`图片上传失败`);
}; }
componentWillReceiveProps(nextProps) { };
// Should be a controlled component. changePos = obj => {
if ('value' in nextProps) { if (!('value' in this.props)) {
const value = nextProps.value; this.setState({...obj});
this.setState({ url: value }); }
} this.triggerChange({...obj});
} };
changeUrl = (info, key) => {
if (info.file.status === 'done') {
message.success(`图片上传成功`);
if (!('value' in this.props)) { render() {
this.setState({ url: info.file.response }); const {json, disabled} = this.props;
} const {url} = this.state;
this.triggerChange(info.file.response); return (
} else if (info.file.status === 'error') { <Upload.Dragger
message.error(`图片上传失败`); disabled={disabled}
} accept={'image/*'}
}; url={url}
changePos = (obj) => { beforeUpload={(file) => {
if (!('value' in this.props)) { return zipImage(file, 4); // 图片压缩函数. 超过fileSizeLimitMb兆的图片 直接压缩成原来的 30% 如果后续有其他需求考虑 做成全局配置项 配置可以压缩的图片的范围
this.setState({ ...obj }); }}
} showUploadList={false}
this.triggerChange({ ...obj }); name="file"
}; action={config.uploadUrl}
render() { onChange={this.changeUrl}
const { json, disabled } = this.props; multiple={false}
const { url } = this.state; style={{padding: 0}}
return ( >
<Upload.Dragger {url ? (
disabled={disabled} <img src={config.httpServer + url} style={{height: json.height, width: json.width}}/>
accept={'image/*'} ) : (
url={url} <div style={{height: json.height, width: json.width}}/>
showUploadList={false} )}
name="file" </Upload.Dragger>
action={config.uploadUrl} );
onChange={this.changeUrl} }
multiple={false}
style={{ padding: 0 }}>
{url ? (
<img src={config.httpServer + url} style={{ height: json.height, width: json.width }} />
) : (
<div style={{ height: json.height, width: json.width }} />
)}
</Upload.Dragger>
);
}
} }
import React, { useState } from 'react'; import React, { useState } from 'react';
import { isJSON } from '@/webPublic/one_stop_public/copy'; import { isJSON } from '@/webPublic/one_stop_public/copy';
/*** /***
* 处理铜川学生头像颠倒的bug * 处理铜川学生头像颠倒的bug
* */ * */
...@@ -14,7 +13,7 @@ export default function HandlePhoto({ urlObj, style, ...props }) { ...@@ -14,7 +13,7 @@ export default function HandlePhoto({ urlObj, style, ...props }) {
} }
const [needTransForm, setTransform] = useState(false); const [needTransForm, setTransform] = useState(false);
if (url) { if (url) {
getIsNeedTransform(url).then((res) => { getIsNeedTransform(url).then(res => {
if (res) { if (res) {
setTransform(true); setTransform(true);
} }
...@@ -75,11 +74,7 @@ export function getIsNeedTransform(url) { ...@@ -75,11 +74,7 @@ export function getIsNeedTransform(url) {
* */ * */
export function getFileInfo(fileJsonStr) { export function getFileInfo(fileJsonStr) {
if (!fileJsonStr || !isJSON(fileJsonStr)) { if (!fileJsonStr || !isJSON(fileJsonStr)) {
if ( if (fileJsonStr && fileJsonStr.indexOf('http') <= -1 && fileJsonStr.length > 10) {
fileJsonStr &&
fileJsonStr.indexOf('http') <= -1 &&
fileJsonStr.length > 10
) {
// 拼一站式的 图片路径 可能需要修改 // 拼一站式的 图片路径 可能需要修改
const prefix = window.specialImportantSystemConfig && window.specialImportantSystemConfig.dfs; const prefix = window.specialImportantSystemConfig && window.specialImportantSystemConfig.dfs;
return { return {
...@@ -123,3 +118,60 @@ export function getFileInfo(fileJsonStr) { ...@@ -123,3 +118,60 @@ export function getFileInfo(fileJsonStr) {
} }
} }
} }
/**
* 图片压缩函数
* 返回一个promise resolve 新的文件
* */
export const zipImage = (file, fileSizeLimitMb = 3) => {
let fileSizeMb = file.size / 1024 / 1024;
console.log(fileSizeMb);
let fileName = file.name;
if (fileSizeMb < fileSizeLimitMb) {
// 1MB 以下的图片不需要压缩。
return new Promise((resolve, reject) => {
resolve(file)
});
}
let reader = new FileReader();
reader.readAsDataURL(file);
return new Promise((resolve, reject) => {
reader.onload = e => {
//这里的e.target.result就是转换后base64格式的图片文件
let image = new Image(); //新建一个img标签(还没嵌入DOM节点)
image.src = e.target.result;
return (image.onload = () => {
let canvas = document.createElement('canvas');
debugger;
let context = canvas.getContext('2d');
let imageWidth = image.width * 0.3; //压缩后图片的大小
let imageHeight = image.height * 0.3;
let data = '';
canvas.width = imageWidth;
canvas.height = imageHeight;
context.drawImage(image, 0, 0, imageWidth, imageHeight);
data = canvas.toDataURL('image/jpeg');
let zipFile = dataURLtoFile(data, fileName);
console.log(zipFile);
resolve(zipFile);
//压缩完成
});
};
});
};
const dataURLtoFile = (dataurl, filename) => {
// 将base64转换为文件
let arr = dataurl.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type: mime });
};
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论