字节数组缓冲图像转换速度慢 [英] Byte array to buffered image conversion slow

查看:204
本文介绍了字节数组缓冲图像转换速度慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的服务器端代码,它接收一个表示JPEG格式图像的字节数组,并返回图像的尺寸。

I have a simple server-side code that receives a byte array representing an image in JPEG format and returns the dimensions of the image.

public String processImage(byte[] data) {
    long startTime = System.currentTimeMillis();
    ByteArrayInputStream stream = new ByteArrayInputStream(data);
    BufferedImage bufferedImage;
    bufferedImage = ImageIO.read(stream);

    int height = bufferedImage.getHeight();
    int width = bufferedImage.getWidth();

    long endTime = System.currentTimeMillis();

    return "height="+height+" | width="+width+" | elapsed="+(endTime-startTime);
}

它有效,但问题是它的速度慢得令人无法接受。对于100KB的图像,它需要6s。对于900KB的图像,它需要30秒。这是预期的吗?有没有办法让字节数组更快地进行bufferedImage转换?

It works, but the problem is it's unacceptably slow. For an image that's 100KB, it's taking 6s. For an image that's 900KB, it's taking 30s. Is that expected? Is there a way to make byte array to bufferedImage conversion faster?

仅供参考,抓住身高/宽度不是我打算做的唯一事情。我最终想要处理bufferedImage。所以获取高度/宽度只是一个示例代码。

FYI, grabbing height/width isn't the only thing I intend to do. I eventually want to process the bufferedImage. So getting height/width was just an example code.

推荐答案

我认为问题可能与ImageIO默认情况有关使用磁盘缓存(到临时文件),即使你的源是 ByteArrayInputStream 。因此,如果您的文件系统很慢,无论输入源是什么,读取都会很慢。

I think the problem might be related to the fact that ImageIO by default uses disk caching (to a temp file), even if your source is a ByteArrayInputStream. So if your file system is slow, reading will also be slow, regardless of input source.

您可以禁用磁盘缓存(以使用更多内存为代价) ImageIO。 setUseCache(假) 。这仍将缓存您的流(以允许向后搜索),但仅限于内存。

You can disable the disk caching (at the cost of using more memory) with ImageIO.setUseCache(false). This will still cache your streams (to allow backwards seeking), but only in memory.

还可以使用 ImageIO。 setCacheDirectory(cacheDirectory) ,如果你有更快的磁盘/ ramdisk或类似的存储你的临时文件。

It's also possible to set the cache directory to a specific path using ImageIO.setCacheDirectory(cacheDirectory), if you have a faster disk/ramdisk or similar to store your temp files.

那就是说,您报告的读取时间似乎过高,即使对于磁盘缓存读取也是如此。如果问题仍然存在,我建议使用分析器找出花费的时间,并查看可能的优化。

That said, your reported read times seems unreasonably high, even for disk cached reads. If the problem persists, I suggest using a profiler to find out where the time is spent, and look at possible optimizations.

PS:我也有自定义 ByteArrayImageInputStream 这可能有助于减少磁盘访问和内存消耗,如果这确实是问题。

PS: I also have a custom ByteArrayImageInputStream that might help reduce both disk access and memory consumption, should this really be the problem.

这篇关于字节数组缓冲图像转换速度慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆