io write Java,Java ImageIO.write()最多需要6秒

I am writing an web application where I need to send an image from servlet to client. Image is generated dynamically and is quite big(+-2MB). It might be jpeg, png, or gif.

Now, I am using ImageIO.write() to write the image to output stream, but its veeeery slow. It takes up to 6 seconds till the client see the image. I need to speed it up.

Any suggestions?

btw. I am aware of Looking for a faster alternative to ImageIO topic. But it didn't help me.

Since it's slow with PNG ImageMagick is not a solution and

I have tested JAI and it was even worse.

Thanks in advance

Edit:

To show you some code:

BufferedImage bi = [code to generate Image];

response.setContentType(mime);

ServletOutputStream out = response.getOutputStream();

ImageIO.write(bi,"png",out);

I stripped down Exception handling for readability.

解决方案

Image encoding in java is pretty slow in general but you may also want to ensure you have the native libraries installed as they make quite a noticeable difference in performance.

imageio.write()是Java中的一个方法,用于将图像写入指定的输出流或文件中。它的用法如下: 1. 导入相关类 ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; ``` 2. 创建BufferedImage对象 ```java BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); ``` 3. 将图像数据写入BufferedImage对象中 ```java // TODO: 将图像数据写入BufferedImage对象中 ``` 4. 将BufferedImage对象写入文件或输出流中 ```java File output = new File("output.png"); try { ImageIO.write(image, "png", output); } catch (IOException e) { e.printStackTrace(); } ``` 其中,第一个参数image是要写入的BufferedImage对象,第二个参数是输出格式,第三个参数是输出的文件或输出流。 注意,ImageIO.write()方法支持的输出格式包括:BMP、GIF、JPEG、PNG、WBMP等。 完整示例代码: ```java import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ImageIOWriteExample { public static void main(String[] args) { int width = 200; int height = 200; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int rgb = (x + y) % 2 == 0 ? 0xFFFFFF : 0x000000; image.setRGB(x, y, rgb); } } File output = new File("output.png"); try { ImageIO.write(image, "png", output); } catch (IOException e) { e.printStackTrace(); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值