需要实现的页面效果:
点击头像进行图片上传;再次点击可以修改
遇到的问题:上传图片反显到框里面 图片旋转
最终解决方案:
<div style={
{padding:'10px 0'}}>
<span className={s.fileStyle}>
<img src={this.state.imgSrc} alt="" className={s.imgs} id='imgBox'/>
<ImagePicker
length={1}
files={this.state.files}
onChange={this.onChange}
onImageClick={(index, fs) => console.log(index, fs)}
selectable={true}
accept="image/gif,image/jpeg,image/jpg,image/png"
disableDelete
/>
</span>
</div>
//js代码
onChange = (files, type, index) => {
console.log(files, type, index);
if (type == 'add') {
this.setState({
files,
});
var file=files[files.length - 1].file;
const windowURL = window.URL || window.webkitURL;//实现预览
var u = navigator.userAgent;
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
if(isiOS){
console.log('ios');
console.log(file.size/1024+'kb')
const isLt400K = file.size /1024 < 200;
if(!isLt400K){
return this.getsmallpic(file)
}else{
this.setState({
imgArr:files[files.length - 1].file,
imgSrc:files[files.length - 1].url
})
}
}else if(isAndroid){
console.log('Android');
var that=this;
this.rotateImg(files[files.length - 1].file).then(blob => {
document.getElementById('imgBox').src = URL.createObjectURL(blob) // 转换后的img
this.blobToDataURL(blob, function(dataurl) {
console.log(file.size/1024+'kb')
const isLt400K = file.size /1024 < 200;
if(!isLt400K){
return that.getsmallpic(that.dataURLtoFile(dataurl,file.name))
}else{
this.setState({
imgArr:files[files.length - 1].file
})
}
});
});
}else{
console.log('pc')
console.log(file.size/1024+'kb')
const isLt400K = file.size /1024 < 200;
if(!isLt400K){
return this.getsmallpic(file)
}else{
this.setState({
imgArr:files[files.length - 1].file,
imgSrc:files[files.length - 1].url
})
}
}
}
}
blobToDataURL(blob, callback) {
var a = new FileReader();
a.onload = function(e) {
callback(e.target.result);
}
a.readAsDataURL(blob);
return a;
}
//图片翻转
rotateImg(file) {
return new Promise((resolve, reject) => {
let img = new Image();
img.src = window.URL.createObjectURL(file);
img.onload = () => {
util.addScript('https://cdn.jsdelivr.net/npm/exif-js', () => {
var EXIF=window.EXIF;
// 获取图片源数据 上面已经引入EXIF全局变量
EXIF.getData(img, function () {
// 获取图片orientation值
console.log(EXIF.getAllTags(this))
let orientation = EXIF.getTag(this, "Orientation");
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
switch (orientation) {
case 3: // 旋转180°
canvas.width = img.width;
canvas.height = img.height;
ctx.rotate((180 * Math.PI) / 180);
ctx.drawImage(img, -img.width, -img.height, img.width, img.height);
break;
case 6: // 旋转90°