Make a BufferedImage use less RAM?

后端 未结 6 1338
挽巷
挽巷 2020-12-25 08:02

I have java program that reads a jpegfile from the harddrive and uses it as the background image for various other things. The image itself is stored in a BufferImage

6条回答
  •  不思量自难忘°
    2020-12-25 08:43

    I assume all this is because the image is being stored in ram as raw RGB data, not compressed or optimized in any way.

    Exactly... Say a 1920x1200 JPG can fit in, say, 300 KB while in memory, in a (typical) RGB + alpha, 8 bits per component (hence 32 bits per pixel) it shall occupy, in memory:

    1920 x 1200 x 32 / 8 = 9 216 000 bytes 
    

    so your 300 KB file becomes a picture needing nearly 9 MB of RAM (note that depending on the type of images you're using from Java and depending on the JVM and OS this may sometimes be GFX-card RAM).

    If you want to use a picture as a background of a 1920x1200 desktop, you probably don't need to have a picture bigger than that in memory (unless you want to some special effect, like sub-rgb decimation / color anti-aliasing / etc.).

    So you have to choices:

    1. makes your files less wide and less tall (in pixels) on disk
    2. reduce the image size on the fly

    I typically go with number 2 because reducing file size on hard disk means you're losing details (a 1920x1200 picture is less detailed than the "same" at 3940x2400: you'd be "losing information" by downscaling it).

    Now, Java kinda sucks big times at manipulating pictures that big (both from a performance point of view, a memory usage point of view, and a quality point of view [*]). Back in the days I'd call ImageMagick from Java to resize the picture on disk first, and then load the resized image (say fitting my screen's size).

    Nowadays there are Java bridges / APIs to interface directly with ImageMagick.

    [*] There is NO WAY you're downsizing an image using Java's built-in API as fast and with a quality as good as the one provided by ImageMagick, for a start.

提交回复
热议问题