繁体   English   中英

用Java放大和缩小图像

[英]Zoom in and out of images in Java

我认为这个问题非常明显。 我想使用JSlider实现一个简单的缩放功能,例如在Windows Live Photo Gallery中。

我在网上看了一下,但是当我把它复制到Eclipse时,我尝试使用的所有代码都有错误。 我真的不想使用第三方库,因为该应用程序可能以公司名称出售。 另外,我开始意识到为了防止错误可能需要一些安全预防措施,但我不知道这些会是什么。

因此,如果有人可以提供一些Java代码来放大和缩小图像,那将非常感激。

PS我计划在JLabel使用Image作为ImageIcon ,它将被添加到JScrollPane

您可以通过在原始图像上使用缩放变换轻松实现此目的。 假设您当前的图像宽度为newImageWidth ,当前图像高度为newImageHeight ,以及当前缩放级别zoomLevel ,您可以执行以下操作:

int newImageWidth = imageWidth * zoomLevel;
int newImageHeight = imageHeight * zoomLevel;
BufferedImage resizedImage = new BufferedImage(newImageWidth , newImageHeight, imageType);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newImageWidth , newImageHeight , null);
g.dispose();

现在,取代原来的图像, originalImage在您的显示面积, resizedImage

您也可以按如下方式使用它:

public class ImageLabel extends JLabel{
    Image image;
    int width, height;

    public void paint(Graphics g) {
        int x, y;
        //this is to center the image
        x = (this.getWidth() - width) < 0 ? 0 : (this.getWidth() - width);
        y = (this.getHeight() - width) < 0 ? 0 : (this.getHeight() - width);

        g.drawImage(image, x, y, width, height, null);
    }

    public void setDimensions(int width, int height) {
        this.height = height;
        this.width = width;

        image = image.getScaledInstance(width, height, Image.SCALE_FAST);
        Container parent = this.getParent();
        if (parent != null) {
            parent.repaint();
        }
        this.repaint();
    }
}

然后你可以把它放到你的框架上,并使用缩放因子缩放的方法,我使用了百分比值。

public void zoomImage(int zoomLevel ){
    int newWidth, newHeight, oldWidth, oldHeight;
    ImagePreview ip = (ImagePreview) jLabel1;
    oldWidth = ip.getImage().getWidth(null);
    oldHeight = ip.getImage().getHeight(null);

    newWidth = oldWidth * zoomLevel/100;
    newHeight = oldHeight * zoomLevel/100;

    ip.setDimensions(newHeight, newWidth);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM