How do I make java's ImageBuffer to read a PNG file correctly?

前端 未结 3 1108
一生所求
一生所求 2021-01-12 03:02

For some reason, opening up some PNG files using ImageBuffer and ImageIO does not work. Here\'s some code I am using that works fine for resizing/cropping JPGs:



        
相关标签:
3条回答
  • 2021-01-12 03:53

    egervari, you can use a library like imgscalr (Apache 2) to do all the resizing for you "properly" that fixes issues like these with a very simple API -- it won't help with the cropping, but the resizing is what it does best (different speeds, qualities, even anti-aliasing if you want).

    I would point out that the code you are using now (forcing a CUSTOM type into a 3BYTE_BGR type) should also account for inbound images with an alpha channel.

    Also if you want to keep using your custom code, RGB and ARGB are two of the best supported image types in Java2D -- if you use a poorly supported image type, when Java2D goes to perform the image op, it falls back to its software rendering pipeline and doesn't use the specialized hardware accelerated ones. This doesn't just effect performance as you'll see the result actually look worse (e.g. in GIF You see this a lot).

    Again, imgscalr takes care of all this for you automatically if you wanted to give it a try, but if not, I figured I'd just give a heads up incase you were running into some of these headaches.

    java image processing is... temperamental :)

    0 讨论(0)
  • 2021-01-12 04:03

    When running my function on Windows, croppedImaged.getType() returns the value 5. So, the simple "hack" is to store the type, check to see if it's 0... and if it is, set the value to 5 manually.

    int imageType = croppedImage.getType();
    if(imageType == 0) imageType = 5;
    

    We then pass in imageType instead and it should work on Linux.

    I am sure this has the drawback that if the value is 0 in other cases, it will set it to 5 and that will be wrong. However, this seems to work for common image types on Linux and it hasn't caused any problems.

    It's pretty clear that the Windows version of Java 1.6 is perfectly fine, but the Linux version has a bug in it.

    0 讨论(0)
  • 2021-01-12 04:06

    A workaround solution would be to convert the file to jpeg first, and then process it. The type 0 bug seems to mostly affect PNG images.

    0 讨论(0)
提交回复
热议问题