簡體   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