2012-02-18 116 views
3

圖像,我認爲這個問題是相當自我explainitory,我想用一個JSlider就像在Windows Live照片庫,例如實現一個簡單的變焦功能。放大和縮小在Java中

我有一個快速瀏覽一下網上,但所有我試圖使用的代碼似乎在當我把它複製到Eclipse中的錯誤。我不想使用第三方庫,因爲應用程序可能以公司名稱出售。另外,我begginning認識到,有可能是爲了防止錯誤所需的一些安全precations,但我不知道這些會。

所以,如果有人能給我提供一些Java代碼來放大和縮小圖像,這將是grately讚賞。

在此先感謝

PS我打算使用圖像作爲JLabel將被添加到JScrollPane

回答

8

您可以輕鬆地通過使用規模達到這個將原始圖像上。 假設您對當前圖像寬度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

+0

感謝GETAH,我已經有一個方法可以在我的代碼中執行此操作,它只是沒有點擊它,它也可以用於此目的,但正如我剛剛測試的那樣 - 顯然它可以! – Andy 2012-02-18 15:51:04

+0

等待,這種方法似乎影響圖像的透明度(透明位是黑色的),你有什麼想法和更多的如何解決這個問題? – Andy 2012-02-18 15:55:01

+0

@Andy似乎使用AffineTransform應該保留圖像的透明度...檢查了這一點http://stackoverflow.com/a/2176977/782719 – GETah 2012-02-18 16:11:55

1

內的ImageIcon我建議你看看這些教程:

  1. Tutorial jinni
  2. Java tips
  3. Java2s

他們可能不是複製粘貼解決方案,但我認爲他們是非常好的起點。 希望這些可以幫助你完成你打算做的事情。

問候

+0

謝謝你的教程。我已經看到了Java的技巧之一,但我有點困惑,因爲它只是使圖像更大或更小 - 是所有變焦是什麼?如果是這樣,標準的'getScaledImage'方法會做同樣的事情嗎? – Andy 2012-02-18 15:21:59

+0

我同意你關於Java技巧教程(我以爲你正在尋找一個快速修復的解決方案),事實是,我沒有閱讀所有這些,但我認爲第三個可能是你正在尋找。 – 2012-02-18 15:35:00

+0

由於我已經接受了GETAH的回答,我認爲Java Tips教程中的代碼現在就足夠了。我只接受GETAH的回答,因爲它對我來說更加方便直接,但是你的幫助非常大,所以非常感謝你! (事實證明,基本上所有的縮放是 - 因爲某種原因,我認爲這是一個非常複雜的操作) – Andy 2012-02-18 15:47:16

2

您也可以按如下 使用它:

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); 
}