uniapp applet uploads and compresses images

uniapp applet uploads and compresses images

introduction

Since the uniapp applet project needs to compress images and upload them to oss before users upload them, I found a plug-in in the uniapp plug-in market and modified it.

Plugins used

Image Compression

Problems with plugins

When compressing images, I found that when the width of the uploaded image is less than the height, the image will be rotated. When using uni.getImageInfo() to obtain image information, the maximum value becomes the width, so the compressed image will be deformed.

Solution

After importing the project in the plug-in market, the w-compress folder will appear in the components directory of the project. Add the following code to the calcImageSize method in the compress.js file of w-compress to solve the problem of uploading images with a width smaller than the height. Deformation occurs later

Insert image description here

// 图片分辨率压缩
const calcImageSize = (res, pixels) => {
    
    
	let imgW, imgH
	imgW = res.width
	imgH = res.height
	// 此处为添加的判断
	if (res.orientation === 'left' || res.orientation === 'right') {
    
    
		imgW = res.height
		imgH = res.width
	}
	
	let ratio
	if((ratio = imgW * imgH / pixels) > 1) {
    
    
		ratio = Math.sqrt(ratio)
		imgW = parseInt(imgW / ratio)
		imgH = parseInt(imgH / ratio)
	} else {
    
    
		ratio = 1
	}
	
	return {
    
     imgW, imgH }
}

This modification is to determine whether the current image has been rotated

end

If you don’t want to use plug-ins to prepare your own packages, you also need to pay attention to the rotation problem when obtaining image information. I also found out after using some plug-ins that the plug-ins did not pay attention to the rotation problem of pictures! ! !

I hope this article will be helpful to you. If there are any mistakes, I hope you will give me some advice.

Guess you like

Origin blog.csdn.net/m0_64344940/article/details/125065006