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

增加图片压缩功能

上级 a71787f7
import React from 'react';
import { Upload, message } from 'antd';
import {Upload, message} from 'antd';
import config from '@/webPublic/one_stop_public/config';
import {zipImage} from "@/webPublic/zyd_public/utils/handlePhoto";
export default class ImgUploadCom extends React.Component {
constructor(props) {
super(props);
......@@ -10,56 +12,63 @@ export default class ImgUploadCom extends React.Component {
};
}
triggerChange = (changedValue) => {
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 });
this.setState({url: value});
}
}
changeUrl = (info, key) => {
if (info.file.status === 'done') {
message.success(`图片上传成功`);
if (!('value' in this.props)) {
this.setState({ url: info.file.response });
this.setState({url: info.file.response});
}
this.triggerChange(info.file.response);
} else if (info.file.status === 'error') {
message.error(`图片上传失败`);
}
};
changePos = (obj) => {
changePos = obj => {
if (!('value' in this.props)) {
this.setState({ ...obj });
this.setState({...obj});
}
this.triggerChange({ ...obj });
this.triggerChange({...obj});
};
render() {
const { json, disabled } = this.props;
const { url } = this.state;
const {json, disabled} = this.props;
const {url} = this.state;
return (
<Upload.Dragger
disabled={disabled}
accept={'image/*'}
url={url}
beforeUpload={(file) => {
return zipImage(file, 4); // 图片压缩函数. 超过fileSizeLimitMb兆的图片 直接压缩成原来的 30% 如果后续有其他需求考虑 做成全局配置项 配置可以压缩的图片的范围
}}
showUploadList={false}
name="file"
action={config.uploadUrl}
onChange={this.changeUrl}
multiple={false}
style={{ padding: 0 }}>
style={{padding: 0}}
>
{url ? (
<img src={config.httpServer + url} style={{ height: json.height, width: json.width }} />
<img src={config.httpServer + url} style={{height: json.height, width: json.width}}/>
) : (
<div style={{ height: json.height, width: json.width }} />
<div style={{height: json.height, width: json.width}}/>
)}
</Upload.Dragger>
);
......
import React, { useState } from 'react';
import { isJSON } from '@/webPublic/one_stop_public/copy';
/***
* 处理铜川学生头像颠倒的bug
* */
......@@ -14,7 +13,7 @@ export default function HandlePhoto({ urlObj, style, ...props }) {
}
const [needTransForm, setTransform] = useState(false);
if (url) {
getIsNeedTransform(url).then((res) => {
getIsNeedTransform(url).then(res => {
if (res) {
setTransform(true);
}
......@@ -75,11 +74,7 @@ export function getIsNeedTransform(url) {
* */
export function getFileInfo(fileJsonStr) {
if (!fileJsonStr || !isJSON(fileJsonStr)) {
if (
fileJsonStr &&
fileJsonStr.indexOf('http') <= -1 &&
fileJsonStr.length > 10
) {
if (fileJsonStr && fileJsonStr.indexOf('http') <= -1 && fileJsonStr.length > 10) {
// 拼一站式的 图片路径 可能需要修改
const prefix = window.specialImportantSystemConfig && window.specialImportantSystemConfig.dfs;
return {
......@@ -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 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论