Commit d66c702b authored by chenqikuai's avatar chenqikuai

存储图片压缩代码

parent d7187807
var fileinput = document.getElementById('fileinput')
var preview = document.getElementById('preview')
const max_width = 100
const max_height = 100
var form = document.getElementById('form')
function processfile(file: File) {
return new Promise((resolve) => {
if (!/image/i.test(file.type)) {
alert('File ' + file.name + ' is not an image.')
return false
}
// read the files
var reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onload = function (event: Event) {
// blob stuff
if (!reader.result) return
var blob = new Blob([reader.result]) // create blob...
window.URL = window.URL || window.webkitURL
var blobURL = window.URL.createObjectURL(blob) // and get it's URL
// helper Image object
var image = new Image()
image.src = blobURL
//preview.appendChild(image); // preview commented out, I am using the canvas instead
image.onload = function () {
// have to wait till it's loaded
var resized = resizeMe(image) // send it to canvas
resolve(resized)
}
}
})
}
// === RESIZE ====
function resizeMe(img: HTMLImageElement) {
var canvas = document.createElement('canvas')
var width = img.width
var height = img.height
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > max_width) {
//height *= max_width / width;
height = Math.round((height *= max_width / width))
width = max_width
}
} else {
if (height > max_height) {
//width *= max_height / height;
width = Math.round((width *= max_height / height))
height = max_height
}
}
// resize the canvas and draw the image data into it
canvas.width = width
canvas.height = height
var ctx = canvas.getContext('2d')
ctx && ctx.drawImage(img, 0, 0, width, height)
return canvas.toDataURL('image/jpeg', 0.7) // get the data from canvas as 70% JPG (can be also PNG, etc.)
}
...@@ -32,7 +32,7 @@ ...@@ -32,7 +32,7 @@
"src/**/*.vue", "src/**/*.vue",
"tests/**/*.ts", "tests/**/*.ts",
"tests/**/*.tsx", "tests/**/*.tsx",
"src/plugins/longPress.js" "src/plugins/longPress.js",
], ],
"exclude": [ "exclude": [
"node_modules" "node_modules"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment