Skip to content

18.如何使用html5进行图片压缩上传? #18

@webVueBlog

Description

@webVueBlog
Member

H5:进行图片压缩上传

<canvas canvas-id='attendCanvasId' class='myCanvas' :style="'width:' + imageSize.imageWidth + 'px; height:' + imageSize.imageHeight  + 'px;'"></canvas>

imageSize: '',

压缩代码:

// 压缩图片
paressImage: function(image, fn) {
	let img = new Image()
	// 要给对象图片的路径
	img.src = image.path
	let canvas = document.createElement('canvas');
	let ctx = canvas.getContext('2d')
	// 最大尺寸限制
	var maxWidth = 500,
		maxHeight = 500;
	var canvasWidth, canvasHeight;
	// 取得压缩后得高宽
	if (image.width > image.height) {
		if (image.width > maxWidth) {
			canvasWidth = maxWidth;
			canvasHeight = image.height * (canvasWidth / image.width)
		} else {
			canvasWidth = image.width;
			canvasHeight = image.height;
		}
	} else {
		if (image.height > maxHeight) {
			canvasHeight = maxHeight;
			canvasWidth = image.width * (canvasHeight / image.height);
		} else {
			canvasWidth = image.width;
			canvasHeight = image.height;
		}
	}
	canvas.width = canvasWidth
	canvas.height = canvasHeight
	// 图片画在画布上
	ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight)
	// 图片资源
	canvas.toBlob((fileSrc) => {
		console.log('fileSrc', fileSrc)
		var imgSrc = window.URL.createObjectURL(fileSrc)
		fn(imgSrc);
	}, 'image/png', 0.50);

},

图片上传:

uploadFile

url: this.$store.state.baseUrl + '/manage/upload/upload_file',
filePath: imgSrc,
fileType: 'image',
name: 'file',
...
var obj = JSON.parse(uploadFileRes.data)
this.query.image = obj.data.img_url

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @webVueBlog

        Issue actions

          18.如何使用html5进行图片压缩上传? · Issue #18 · weekCodeing/interview-answe