Java 2D 和调整大小

标签 java image resize 2d image-scaling

我想重用一些旧的 Java 2D 代码,但我想知道,这是获得最高质量图像的最佳方式吗?

    public static BufferedImage getScaled(BufferedImage imgSrc, Dimension dim) {

    //  This code ensures that all the pixels in the image are loaded.
    Image scaled = imgSrc.getScaledInstance(
            dim.width, dim.height, Image.SCALE_SMOOTH);

    // This code ensures that all the pixels in the image are loaded.
    Image temp = new ImageIcon(scaled).getImage();

    // Create the buffered image.
    BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), 
            temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

    // Copy image to buffered image.
    Graphics g = bufferedImage.createGraphics();
    // Clear background and paint the image.
    g.setColor(Color.white);
    g.fillRect(0, 0, temp.getWidth(null),temp.getHeight(null));
    g.drawImage(temp, 0, 0, null);
    g.dispose();


    // j2d's image scaling quality is rather poor, especially when
    // scaling down an image to a much smaller size. We'll post filter  
    // our images using a trick found at 
    // http://blogs.cocoondev.org/mpo/archives/003584.html
    // to increase the perceived quality....
    float origArea = imgSrc.getWidth() * imgSrc.getHeight();
    float newArea = dim.width * dim.height;
    if (newArea <= (origArea / 2.)) {
        bufferedImage = blurImg(bufferedImage);
    }

    return bufferedImage;
}

public static BufferedImage blurImg(BufferedImage src) {
    // soften factor - increase to increase blur strength
    float softenFactor = 0.010f;
    // convolution kernel (blur)
    float[] softenArray = {
            0,              softenFactor,       0, 
            softenFactor, 1-(softenFactor*4), softenFactor, 
            0,              softenFactor,       0};

    Kernel kernel = new Kernel(3, 3, softenArray);
    ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
    return cOp.filter(src, null);
}

最佳答案

Chris Campbell 有一篇关于缩放图像的出色而详细的文章 - 请参阅 this article .

Chet Haase 和 Romain Guy 在他们的书 Filthy Rich Clients 中也有关于图像缩放的详细且非常有用的文章。 .

关于Java 2D 和调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/543130/

相关文章:

java - 从类路径目录中获取资源列表

javascript - 预加载/加载大图像的最快方法

HTML/CSS 等列高度

java - 如何设置 SashForm 子项默认大小

c++ - 为什么 C++ STL vector 在做很多保留时会慢 1000 倍?

java - 在android的日历 View 中禁用每个星期日

java - 如何强制运行未签名的java应用程序

java - 以编程方式删除java缓存

css - 为调整大小的照片添加边框

java - 尝试将图像绘制到 JPanel 上