JSP 如何缩放图像?
有没有办法缩放图像然后在jsp页面中显示?当检索和显示图像时,我想以相同的尺寸显示所有照片。有什么API可以做到吗?我从谷歌搜索过,我发现那些是关于使用 Takeit 缩放图像的,但不能在网络应用程序中工作。
Is there anyway to scale an image then display in jsp page? When retrieve and display the images, I want to show all photos in same size. is there any API can do it? I have searched from google, those I found was about scaling images byusing tookit but can't works in web application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用内置的 Java 2D API (基本Sun 教程此处)。
基本上,您需要创建一个 Servlet ,它获取
InputStream< /code> doGet()
方法中的原始图像,将其通过 Java 2D API 传递,然后将其写入 HTTP 响应的OutputStream
中。然后,您只需将此 Servlet 映射到web.xml
中的某个url-pattern
上,例如/thumbs/*
并在/thumbs/*
中调用此 Servlet HTML元素的 code>src 属性。
这是一个基本的启动示例(您仍然需要按照自己想要的方式自行处理意外情况):
在
web.xml
中映射 servlet,如下所示:可以按如下方式使用:
注意:不,这个无法单独使用 JSP 来完成,因为它是一种不适合此任务的视图技术。
注 2:这是一项相当昂贵的(CPU 密集型)任务,请记住这一点。您可能需要考虑自己预先缓存或预生成拇指。
You can use the builtin Java 2D API for this (basic Sun tutorial here).
Basically, you need to create a Servlet which gets an
InputStream
of the original image in thedoGet()
method, passes it through the Java 2D API and then writes it to theOutputStream
of the HTTP response. Then you just map this Servlet on a certainurl-pattern
inweb.xml
, e.g./thumbs/*
and call this Servlet in thesrc
attribute of the HTML<img>
element.Here's a basic kickoff example (you still need to handle unexpected conditions yourself the way you want):
With the servlet mapped in
web.xml
as follows:This can be used as follows:
Note: no, this cannot be done with JSP alone since it's a view technology unsuitable for this task.
Note 2: this is a pretty expensive (CPU intensive) task, keep this in mind. You may want to consider to cache or pregenerate the thumbs beforehand yourself.
从技术上讲你可以做到,但实际上这不是可取的。
是的,我会长时间缓存图像,以及一些用于识别对原始图像的更改的内容,然后仅在原始图像发生更改时重新创建调整大小的图像(或者缓存过期,可能在上次访问图像一周后) 。
Technically you can do it, but indeed it's not something that's advisable.
And yes, I'd cache the images for a long time, together with something to identify changes to the original, then recreate the resized image only if the original changes (or the cache expires, maybe a week after the image was last accessed).