1简单图片上传
<input type="file" id="upload">
<img src="" id="image">
<script>
var uploadFile = document.getElementById("upload")
uploadFile.onchange = function(){
var file = uploadFile.files[0]
var fileSize = file.size
if (fileSize < 10240){
console.log('图片小于10KB')
}
var r = new FileReader()
r.readerAsDataUrl(file)
r.onload = function(e){
var fileBase64 = e.target.result
document.getElementById("image").src = fileBase64
console.log(fileBase64)
}
}
</script>
2 图片压缩转码
- base64图片压缩
function dealImage(base64, w, callback) {
var newImage = new Image();
var quality = 0.6;
newImage.src = base64.url;
newImage.setAttribute('crossOrigin', 'Anonymous');
var imgWidth, imgHeight;
newImage.onload = function() {
imgWidth = this.width;
imgHeight = this.height;
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
if (Math.max(imgWidth, imgHeight) > w) {
if (imgWidth > imgHeight) {
canvas.width = w;
canvas.height = (w * imgHeight) / imgWidth;
} else {
canvas.height = w;
canvas.width = (w * imgWidth) / imgHeight;
}
} else {
canvas.width = imgWidth;
canvas.height = imgHeight;
quality = 0.6;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
var base64 = canvas.toDataURL('image/jpeg', quality);
callback(base64);
};
}
- base64图片转换二进制流
const base64toFile = (dataurl, filename = 'file') => {
let arr = dataurl.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let suffix = mime.split('/')[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}.${suffix}`, {
type: mime
});
};
- 接口调用上传
let apirul = `xxx/upload_file`;
let filedata = new FormData();
dealImage(files[filesIndex], 500, useImg);
function useImg(base64) {
filedata.append('file', base64toFile(base64));
let request = new Request(apirul, {
method: 'POST',
credentials: 'include',
body: filedata
});
fetch(request).then(response => {
response.json().then(async data => {
console.log('上传成功');
console.log(data);
if (data.code === 0) {
setFilesIndex(filesIndex + 1);
setImgfileId([...imgfileId, data.data]);
} else {
Toast.success(data.msg, 3);
}
});
});
}
3 Vue2.0实现调用摄像头进行拍照图片上传
- hmtl
DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title>title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.min.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.5.1/vue-resource.js">script>
<style type="text/css">
.bgred{
background-color: red;
color: #fff !important;
}
.nav-title p:nth-child(2) a {
display: block;
width: 100%;
height: 100%;
}
.container {
margin-top: 28px;
}
.uploading{
width: 100%;
height: 250px;
}
style>
head>
<body>
<div id="app" v-cloak>
<input @change="fileChange($event)" type="file" name="" id="" />
<p class="uploading">
点击上传封面
p>
div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/exif-js/2.3.0/exif.js">script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/layer/2.3/layer.js">script>
<script src="index.js" type="text/javascript" charset="utf-8">script>
body>
html>
- js
var data = {
keyurl:'',
key:'',
token:'',
accept: ['image/gif', 'image/jpeg', 'image/png', 'image/bmp'],
width:'',
height:''
}
var app = new Vue({
el: "#app",
data: data,
methods: {
fileChange:function(el){
let file = el.target.files[0];
let type = file.type;
let size = file.size;
if (this.accept.indexOf(type)==-1) {
layer.msg("请选择我的支持的图片格式");
return false;
};
if (size>3145728){
layer.msg("请选择3M以内的图片");
return false;
};
if (!file.size) return;
if (!file) return;
var orientation;
EXIF.getData(file, function () {
orientation = EXIF.getTag(this, 'Orientation');
});
var reader = new FileReader();
var self = this;
reader.onload = function () {
self.getImgData(this.result, orientation, function (result) {
var img = new Image();
img.src = result;
if (result.length <= 200) {
self.fileList(file);
img = null;
return;
};
if (img.complete) {
callback();
} else {
img.onload = callback;
};
function callback () {
var data = self.compress(img);
var file = self.dataURLtoFile(data,'1.png');
self.fileList(file);
img = null;
}
});
};
reader.readAsDataURL(file);
},
dataURLtoFile:function(dataurl, filename){
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/),
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
},
compress:function(img) {
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var tCanvas = document.createElement('canvas');
var tctx = tCanvas.getContext('2d');
let initSize = img.src.length
let parentWh = $('.creater_class .files');
let wid = parentWh.width();
let hei = parentWh.height();
this.AutoSize(img, wid, hei);
var width = this.width;
var height = this.height;
var ratio;
if ((ratio = width * height / 4000000) > 1) {
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
} else {
ratio = 1;
}
canvas.width = width;
canvas.height = height;
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, canvas.width, canvas.height);
var count;
if ((count = width * height / 1000000) > 1) {
count = ~~(Math.sqrt(count) + 1);
var nw = ~~(width / count);
var nh = ~~(height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for (let i = 0; i < count; i++) {
for (let j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
}
}
} else {
ctx.drawImage(img, 0, 0, width, height);
}
var ndata = canvas.toDataURL('image/jpeg', 0.5);
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
return ndata;
},
AutoSize:function(image, maxWidth, maxHeight) {
if (image.width < maxWidth && image.height < maxHeight) {
this.width = image.width;
this.height = image.height;
} else {
if (maxWidth / maxHeight <= image.width / image.height) {
this.width = maxWidth;
this.height = maxWidth * (image.height / image.width);
} else {
this.width = maxHeight * (image.width / image.height);
this.height = maxHeight;
}
}
},
getImgData:function(img, dir, next) {
var image = new Image();
image.onload = function () {
var degree = 0;
var drawWidth;
var drawHeight;
var width;
var height;
drawWidth = this.naturalWidth;
drawHeight = this.naturalHeight;
var maxSide = Math.max(drawWidth, drawHeight);
if (maxSide > 1024) {
var minSide = Math.min(drawWidth, drawHeight);
minSide = minSide / maxSide * 1024;
maxSide = 1024;
if (drawWidth > drawHeight) {
drawWidth = maxSide;
drawHeight = minSide;
} else {
drawWidth = minSide;
drawHeight = maxSide;
}
}
var canvas = document.createElement('canvas');
canvas.width = width = drawWidth;
canvas.height = height = drawHeight;
var context = canvas.getContext('2d');
switch (dir) {
case 3:
degree = 180
drawWidth = -width
drawHeight = -height
break
case 6:
canvas.width = height
canvas.height = width
degree = 90
drawWidth = width
drawHeight = -height
break
case 8:
canvas.width = height
canvas.height = width
degree = 270
drawWidth = -width
drawHeight = height
break
}
context.rotate(degree * Math.PI / 180)
context.drawImage(this, 0, 0, drawWidth, drawHeight)
next(canvas.toDataURL('image/jpeg', 0.8))
}
image.src = img
},
fileList:function(files){
this.imageUpload(files);
},
imageUpload:function(fileDom){
var imageData = new FormData();
imageData.append('file',fileDom);
imageData.append('token',this.token);
this.$http.post('qiniuUrl',imageData).then((result)=>{
this.key = result.data.key;
});
}
}
});