如何裁剪/缩放用户图像,以便可以显示固定大小的缩略图而不倾斜和拉伸?
我正在努力允许用户为我的网站上传个人资料图片。 我试图避免的典型例子是 plentyoffish.com,其中每个用户的图像都是倾斜的并且看起来非常难看:
那么,如何在没有上面演示的倾斜的情况下以编程方式裁剪/创建图像的标准尺寸版本?
I'm working on allowing users to upload profile pictures for my site. The classic example of what I'm trying to avoid is plentyoffish.com where each users image is skewed and looks very ugly:
So, how can I progmatically crop/create standard sized versions of an image without the skewing demonstrated above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
好吧,您必须有最大高度和宽度,假设您可用的图像尺寸是正方形,例如 100x100。
当用户上传图像时,获取图像的尺寸,然后计算出高度或宽度哪个更大。
然后进行最大的测量,并得到该测量值与目标测量值的比率,然后使用该比率来缩放高度和宽度。
因此,如果用户上传一张高度为 500、宽度为 450 的图片,由于高度最大,您需要将 100 除以 500(缩略图大小)。 这给了我们 0.2 作为比率。 这意味着宽度将变为 90,因此您将缩小到 100x90,并且不会发生扭曲。
Well, you must have a maximum height and width, lets assume the image size you have available is square, say 100x100.
When a user uploads an image get the dimensions of it, then work out which is greater, the height or the width.
Then take the greatest measurement and get the ratio of that measurement to your target measurement, then use that ratio to scale both the height and width.
So if the user uploads a picture of 500 height and 450 width, as the height is greatest you'd divide 100 by 500, your thumbnail size. This gives us .2 as the ratio. which means the width will become 90, so you would shrink to 100x90, and no distortion would occur.
这是我用来调整大小的一些代码(C#),类似于blowdart建议的方法。 只需将“300”替换为您的情况下一侧的最大尺寸:
Here's some code (C#) I used to do a resize, similar to the method suggested by blowdart. Just replace the "300"s with the maximum size of one side in your case:
或者:如果您仍然想要固定尺寸,请按照blowdart的说明进行操作,但计算最大比例:100px / 450px = .22..
编辑:或者让用户选择如何裁剪最大尺寸。
OR: If you would still like fixed dimensions, you follow blowdart's instructions but calculate the greatest ratio instead: 100px / 450px = .22..
EDIT: Or let the user select how to crop the greatest dimension.
使用ImageMagick。 在命令行上使用:
Use ImageMagick. On the command line use:
我不久前为 PHP 创建了这个函数,非常适合这个场景和其他一些场景:
I made this function for PHP a while ago that works great for this and some other scenarios:
这是我使用 ImageMagick 的转换工具组合起来完成此操作的 bash 命令。 对于位于父目录中的一组图像,一些是纵向的,一些是横向的,要在当前目录中创建缩放到 600x400 的图像,从中心裁剪纵向图像并简单地缩放横向图像:
Here's a bash command I threw together to accomplish this using ImageMagick's convert tool. For a set of images sitting in the parent directory, some portrait, some landscape, to create images in the current directory scaled to 600x400, cropping portrait images from the centre and simply scaling the landscape images: