Java解决调整大小后的图像质量低的问题

一、概述

在脚本中,它从300×300左右的标记下降到60×60。由于目前效果不佳,因此需要提高整体图像质量。

public static Boolean resizeImage(String sourceImg, String destImg, Integer Width, Integer Height, Integer whiteSpaceAmount) 
{
    BufferedImage origImage;

    try 
    {
        origImage = ImageIO.read(new File(sourceImg));
        int type = origImage.getType() == 0? BufferedImage.TYPE_INT_ARGB : origImage.getType();
        int fHeight = Height;
        int fWidth = Width;
        int whiteSpace = Height + whiteSpaceAmount; //Formatting all to squares so don't need two whiteSpace calcs..
        double aspectRatio;

        //Work out the resized dimensions
        if (origImage.getHeight() > origImage.getWidth()) //If the pictures height is greater than the width then scale appropriately.
        {
            fHeight = Height; //Set the height to 60 as it is the biggest side.

            aspectRatio = (double)origImage.getWidth() / (double)origImage.getHeight(); //Get the aspect ratio of the picture.
            fWidth = (int)Math.round(Width * aspectRatio); //Sets the width as created via the aspect ratio.
        }
        else if (origImage.getHeight() < origImage.getWidth()) //If the pictures width is greater than the height scale appropriately.
        {
            fWidth = Width; //Set the height to 60 as it is the biggest side.

            aspectRatio = (double)origImage.getHeight() / (double)origImage.getWidth(); //Get the aspect ratio of the picture.
            fHeight = (int)Math.round(Height * aspectRatio); //Sets the height as created via the aspect ratio.
        }

        int extraHeight = whiteSpace - fHeight;
        int extraWidth = whiteSpace - fWidth;

        BufferedImage resizedImage = new BufferedImage(whiteSpace, whiteSpace, type);
        Graphics2D g = resizedImage.createGraphics();
        g.setColor(Color.white);
        g.fillRect(0, 0, whiteSpace, whiteSpace);

        g.setComposite(AlphaComposite.Src);
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g.drawImage(origImage, extraWidth/2, extraHeight/2, fWidth, fHeight, null);
        g.dispose();

        ImageIO.write(resizedImage, "jpg", new File(destImg));
    } 
    catch (IOException ex) 
    {
        return false;
    }

    return true;
}

真的只是需要知道我可以插入的东西是否会提高质量,或者是否需要完全研究其他东西。

二、详解

您看到的问题实际上与用于缩减的重采样滤波器有关。显然,您的库使用的那个对于这种情况是不好的。缩小比例时,最近的邻居,双线性和双三次是典型的不良示例。我不知道Photoshop使用的确切的重采样滤镜,但是我使用了三叶lanczos并得到以下结果,要解决您的问题,您需要使用更智能的重采样滤波器。

如若转载,请注明出处:https://www.javaidea.cn/article/8325.html

(0)
上一篇 2022年2月7日 上午10:03
下一篇 2022年2月7日 上午10:03

相关推荐

发表评论

您的电子邮箱地址不会被公开。