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

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

问题描述

我有一个简单的服务器端代码,它接收一个表示 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 的图像,需要 6 秒.对于 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 默认使用磁盘缓存(到临时文件)有关,即使您的源是 字节数组输入流.所以如果你的文件系统很慢,不管输入源如何,读取也会很慢.

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(false).这仍将缓存您的流(以允许向后搜索),但仅限于内存中.

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天全站免登陆