2011-01-24 59 views
0

我想旋轉一個圖像,並在下一級我想調整它的大小 幫助我。 我創建了一個從JPanel擴展並覆蓋paintComponent()方法 繪製圖像的類。如何調整大小和旋轉圖像

public class NewJPanel extends javax.swing.JPanel { 

/** Creates new form NewJPanel */ 
public NewJPanel() { 
    initComponents(); 
} 

@Override 
protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.drawImage(image, 20, 20, this); 
} 

回答

3

這是我使用的一些代碼。您可以修改它以符合您的需求。

調整圖像大小:

 

/** 
    * Resizes the image 
    * @param filePath File path to the image to resize 
    * @param w Width of the image 
    * @param h Height of the image 
    * @return A resized image 
    */ 
    public ImageIcon resizeImage(String filePath, int w, int h) { 


     String data = filePath; 
     BufferedImage bsrc, bdest; 
     ImageIcon theIcon; 
     //scale the image 
     try 
     { 
      if(dataSource == DataTypeEnum.file) 
      { 
       bsrc = ImageIO.read(new File(data)); 
      } 
      else 
      { 
       bsrc = ImageIO.read(new URL(filePath)); 
      } 
      bdest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); 
      Graphics2D g = bdest.createGraphics(); 
      AffineTransform at = AffineTransform.getScaleInstance((double) w/bsrc.getWidth(), 
        (double) h/bsrc.getHeight()); 
      g.drawRenderedImage(bsrc, at); 

      //add the scaled image 
      theIcon = new ImageIcon(bdest); 
      return theIcon; 
     } 
     catch (Exception e) 
     { 
      Window.getLogger().warning("This image can not be resized. Please check the path and type of file."); 
      //restore the old background 
      return null; 
     } 

    } 
 

旋轉圖像:
注:角弧度

 

public static BufferedImage rotate(BufferedImage image, double angle) { 
    double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle)); 
    int w = image.getWidth(), h = image.getHeight(); 
    int neww = (int)Math.floor(w*cos+h*sin), newh = (int)Math.floor(h*cos+w*sin); 
    GraphicsConfiguration gc = getDefaultConfiguration(); 
    BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT); 
    Graphics2D g = result.createGraphics(); 
    g.translate((neww-w)/2, (newh-h)/2); 
    g.rotate(angle, w/2, h/2); 
    g.drawRenderedImage(image, null); 
    g.dispose(); 
    return result; 
} 

 
-1

使用BufferedImage類

的BufferedImage newImg =新的BufferedImage(newWidth,newHeight,IMAGETYPE); (),0,0,newWidth,newHeight,0,0,oldWidth,oldHeight,null); newImg.createGraphics()。drawImage(oldImg,0,0,newWidth,newHeight,0,0,oldWidth,oldHeight,null);

然後只是重新使用newImg代替舊圖像,應該工作,我目前不在編譯器附近進行測試。

http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html#drawImage%28java.awt.Image,%20int,%20int,%20int,%20int,%20int,%20int,%20int,%20int,%20java.awt.image.ImageObserver%29

+1

那怎麼旋轉圖像? – 2011-01-24 21:04:59

相關問題