目录
总览
图像尺寸调整算法
如何在网页上使用控件?
如何从控件中获取上传的图像?
源代码
参考文献
总览我们在图像大小调整和裁剪方面存在长期问题。我们的问题是,如果我们在服务器端调整大小,图像质量被破坏并且我们无法根据宽高比进行裁剪,因为上载的图像可以是任何大小和尺寸。对于B2B类型的项目,我们面临很多问题,因为网站用户需要上传图片,他们没有自己调整大小,也没有上传大图片来发布帖子,这使网站加载缓慢。
最后,我做了一个控件,该控件将上传的图像强制调整为所需的尺寸,并保持原始图像及其质量的正确比例。之后,用户可以选择自己的裁剪部分。
这是用户可以在其中进行裁剪的画布:
裁剪后,他们可以查看裁剪后的图像,并有机会再次进行其他裁剪,并按比例上传所需的尺寸(保持我为图像固定的长宽比)。
上传图像后,它将显示上传图像的预览,而无需刷新页面。
所有过程都是使用JavaScript,JQuery和AJAX完成的。因此,无需回发页面或刷新页面,并且此调整大小、裁剪、上传过程现在更加专业。我可以设置纵向和横向图像比例来进行裁剪,而不会扭曲图像的当前比例。为此,我开发了自己的调整大小算法并使用JavaScript实现。这是JavaScript格式的算法。
function ImageResizer(canvasWidth, canvasHeight, sourceWidth,
sourceHeight, destinationX, destinationY, destinationWidth, destinationHeight) {
var canvasRatio = canvasWidth / canvasHeight;
var sourceRatio = sourceWidth / sourceHeight;
if (sourceWidth > canvasWidth || sourceHeight > canvasHeight) {
//if the image does not fit into the required canvas
if (canvasRatio >= 1) {
//if the canvas is landscape
if (sourceRatio 1) {
//if the image is landscape
if (canvasRatio < sourceRatio) {
//make the landscape image fit inside the required Canvas.
//In this case, ImageX is bigger than
//canvasWidth & ImageY is smaller than canvasHeight
destinationWidth = canvasWidth;
destinationHeight = destinationWidth / sourceRatio;
destinationX = 0;
destinationY = (canvasHeight - destinationHeight) / 2;
} else if (canvasRatio >= sourceRatio) {
//In this case, ImageY is bigger than canvasHeight &
//ImageX is smaller than canvasWidth
destinationHeight = canvasHeight;
destinationWidth = destinationHeight * sourceRatio;
destinationX = (canvasWidth - destinationWidth) / 2;
destinationY = 0;
}
}
}
else if (canvasRatio < 1) {
//if the canvas is portrait
if (sourceRatio >= 1) {
//if the image is landscape
destinationWidth = canvasWidth;
destinationHeight = destinationWidth / sourceRatio;
destinationX = 0;
destinationY = (canvasHeight - destinationHeight) / 2;
}
else if (sourceRatio < 1) {
//if the image is portrait
if (canvasRatio > sourceRatio) {
//make the portrait image fit inside the required Canvas.
//In this case, ImageY is bigger than
//canvasHeight & ImageX is small than canvasWidth
destinationHeight = canvasHeight;
destinationWidth = destinationHeight * sourceRatio;
destinationX = (canvasWidth - destinationWidth) / 2;
destinationY = 0;
} else if (canvasRatio
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?
立即登录/注册


微信扫码登录