How do you create a thumbnail image out of a JPEG in Java?

后端 未结 13 2330
日久生厌
日久生厌 2020-11-29 16:51

Can someone please help with some code for creating a thumbnail for a JPEG in Java.

I\'m new at this, so a step by step explanation would be appreciated.

13条回答
  •  野性不改
    2020-11-29 17:38

    As you might have found out "easy" and "good looking result" are two very different things. I have encapsulated both of these requirements into a very simple java image scaling library (Apache 2 license) that just does everything right for you.

    Example code to create a thumbnail looks like this:

    BufferedImage img = ImageIO.read(...); // load image
    BufferedImage scaledImg = Scalr.resize(img, 150);
    

    Your image proportions are honored, the library makes a best-guess at the method it should use based on the amount of change in the image due to scaling (FASTEST, BALANCED or QUALITY) and the best supported Java2D image types are always used to do the scaling to avoid the issue of "black" results or really terrible looking output (e.g. overly dithered GIF images).

    Also, if you want to force it to output the best looking thumbnail possible in Java, the API call would look like this:

    BufferedImage img = ImageIO.read(...); // load image
    BufferedImage scaledImg = Scalr.resize(img, Method.QUALITY, 
                                           150, 100, Scalr.OP_ANTIALIAS);
    

    Not only will the library use the Java2D recommended incremental scaling for you to give you the best looking result, it will also apply an optional antialiasing effect to the thumbnail (ConvolveOp with a very fine-tuned kernel) to every-so-slightly soften the transitions between pixel values so make the thumbnail look more uniform and not sharp or poppy as you might have seen when you go from very large images down to very small ones.

    You can read through all the comments in the library (the code itself is doc'ed heavily) to see all the different JDK bugs that are worked around or optimizations that are made to improve the performance or memory usage. I spent a LOT of time tuning this implementation and have had a lot of good feedback from folks deploying it in web apps and other Java projects.

提交回复
热议问题