工作上需要做一个裁剪图片的一个上传本地图片的功能,在摸索中做出来也顺便记录一下。
需求是如果图片宽高超过1024 * 1024 的话图片等比缩小至1024,并截图上传。
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
@inject("store")
@observer
export default class WorksView extends Component {
constructor(props) {
super(props);
this.imgWidth = 0;//加载本地图片的宽
this.imgHeight = 0;//加载本地图片的高
this.fileType = null;//canvas截图的图片类型
}
initCanvas = (imgurl,file) => {
<!--获取到canvas-->
let can = this.refs.mycanvas;
let ctxt = can.getContext("2d");
if(this.imgWidth !== 0 && this.imgHeight !== 0){
let width = this.imgWidth,height = this.imgHeight;
let shearSize = 1024;
<!--如果原始图片宽度大于高度-->
if(width > height){
<!--取到缩小的比例得出缩小后的高度-->
let w = width / shearSize;
can.width = shearSize;
can.height = height / w;
}else if(height > width){
<!--如果原始图片高度大于宽度-->
let h = height / shearSize;
can.height = shearSize;
<!--取到缩小的比例得出缩小后的宽度-->
can.width = width / h;
}
let image = new Image();
image.onload = () => {
<!--绘制图片裁剪尺寸按原始图片的尺寸等比缩到裁剪尺寸-->
ctxt.drawImage(image,0,0,width,height,0,0,can.width,can.height);
}
image.src = imgurl;
}
}
localImage = (event) => {
let file = event.target.files[0];
<!-- 加载文件类型不是图片就不执行-->
if(file.type !== "image/jpeg" && file.type !== "image/jpg" && file.type !== "image/png"){
return false;
}
<!--获取加载图片的信息-->
this.getImageData(file);
this.fileType = file.type;
}
getImageData = (file) => {
<!--获取加载图片的信息-->
var reader = new FileReader;
reader.readAsDataURL(file);
reader.onload = (e) =>{
var img = new Image();
img.src = e.target.result;
img.onload = () => {
this.imgWidth = img.width;
this.imgHeight = img.height;
if (this.imgWidth > 1024 || this.imgHeight > 1024) {
this.initCanvas(window.URL.createObjectURL(file),file)
}
}
}
}
upload = () => {
if(this.fileType !== null){
// canvas截图图片
this.refs.shearImg.toDataURL(this.fileType);
// upload fun ()...
}
}
render() {
return (
<div className="local-container">
<canvas ref="mycanvas" />
<input className="btns" type="file" onChange={event=>this.localImage(event)} />
<div className="upload" onClick={this.upload}>上传</div>
</div>
);
}
}