Java,JPanel在旋转时裁剪图像

时间:2017-05-23 19:32:29

标签: java image rotation jpanel crop

我在java中制作简单的图像编辑器。我的问题是当我旋转图像被裁剪时,我会尝试在图像上显示它:

旋转前

http://i.imgur.com/KjtHslb.jpg

45度后的

http://i.imgur.com/SKOEFP7.jpg

旋转90度后

我[点] imgur [点] com / 4NrABIA.jpg

看起来JPanel庄稼将图像旋转成原始图像的大小,我不知道为什么:/所以我正在寻求帮助。谢谢。

继承我的代码:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener;
import javax.swing.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import static java.awt.image.ImageObserver.WIDTH;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;

public class OknoInterfejsu extends JFrame{

Container content;
BufferedImage image = null;
JLabel picLabel;
Image scaledImage;
private final JButton przyciski[];
private JComboBox wybor;
private String wybor_str[];
private int picHeight;
private int picWidth;
private int realHeight;
double picAspect;
private String path;


private class ObslugaPrzycisku implements ActionListener{

   private final JFrame ref_okno;

   ObslugaPrzycisku(JFrame okno){
        ref_okno = okno;
   }

   public void actionPerformed(ActionEvent e) {
        JButton bt = (JButton)e.getSource();
        if(bt==przyciski[0]){
           //-----------WCZYTAJ PRZYCISK-------------
        {
            JFileChooser fileChooser = new JFileChooser("C:\\Users\\Filip\\Pictures\\");
            FileFilter imageFilter = new FileNameExtensionFilter(
             "Image files", ImageIO.getReaderFileSuffixes());
            fileChooser.setFileFilter(imageFilter);
             if (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
             {
                 File plik = fileChooser.getSelectedFile();
                 path = plik.getPath();
                 System.out.print(path);
                try {
                    image = ImageIO.read(new File(path));
                } catch (IOException ex) {
                    Logger.getLogger(OknoInterfejsu.class.getName()).log(Level.SEVERE, null, ex);
                }

               picHeight = image.getHeight();
               picWidth = image.getWidth();
               picAspect = (double) picHeight / picWidth;
               //if(picAspect>1)realHeight = 400;
               //else realHeight = 800;
               realHeight = 400;
                scaledImage = image.getScaledInstance(realHeight, (int) (realHeight*picAspect),Image.SCALE_SMOOTH);

                picLabel = new JLabel(new ImageIcon(scaledImage));

                content.add(picLabel);
               content.revalidate();
               content.repaint();

             }

        } 
        }
          //--------------------------OBROT +------------  
         else if(bt==przyciski[1]){
            picLabel.setIcon(null);

            int temp1 = (int) (400*picAspect);

            picRotate(scaledImage, 400,temp1);

            picLabel = new JLabel(new ImageIcon(scaledImage));
               content.add(picLabel);
               content.revalidate();
               content.repaint();
        }   


   }
   }

    public OknoInterfejsu()
   {    
    super("Okno interfejsu");


    setSize(1000,700);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   //-------------------------------------------------------
    przyciski = new JButton[2];
    przyciski[0] = new JButton("Wczytaj Obraz");
    przyciski[0].addActionListener(new ObslugaPrzycisku(this));

    przyciski[1] = new JButton("Obrót +");
    przyciski[1].addActionListener(new ObslugaPrzycisku(this));

    JPanel panelPrzyciski   = new JPanel(new FlowLayout());
    panelPrzyciski.add(przyciski[0]);
    panelPrzyciski.add(przyciski[1]);

    //-------------------------------------------------------
    content  = getContentPane();
    content.setLayout(new BorderLayout());
    content.add(panelPrzyciski,BorderLayout.SOUTH);

    setVisible(true);
    }



     public static void main(String args[]){
     new OknoInterfejsu();
    }

    public void picRotate(Image image,int w,int h){

    BufferedImage temp=(BufferedImage)createImage(w,h);
    Graphics2D  g2d=(Graphics2D)temp.createGraphics(); 
    g2d.rotate((Math.PI/2)*22.5, w/2, h/2);

    g2d.drawImage(image,0,0,null); 
    this.scaledImage=temp; 
    g2d.dispose();  


    }
    }

2 个答案:

答案 0 :(得分:1)

旋转图像时,它会改变尺寸,您需要创建一个新图像,其边界包含这个新尺寸,例如

public Image rotateBy(Image image, double degrees) {

    // The size of the original image
    int w = source.getWidth();
    int h = source.getHeight();
    // The angel of the rotation in radians
    double rads = Math.toRadians(degrees);
    // Some nice math which demonstrates I have no idea what I'm talking about
    // Okay, this calculates the amount of space the image will need in
    // order not be clipped when it's rotated
    double sin = Math.abs(Math.sin(rads));
    double cos = Math.abs(Math.cos(rads));
    int newWidth = (int) Math.floor(w * cos + h * sin);
    int newHeight = (int) Math.floor(h * cos + w * sin);

    // A new image, into which the original can be painted
    BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = rotated.createGraphics();
    // The transformation which will be used to actually rotate the image
    // The translation, actually makes sure that the image is positioned onto
    // the viewable area of the image
    AffineTransform at = new AffineTransform();
    at.translate((newWidth - w) / 2, (newHeight - h) / 2);

    // And we rotate about the center of the image...
    int x = w / 2;
    int y = h / 2;
    at.rotate(rads, x, y);
    g2d.setTransform(at);
    // And we paint the original image onto the new image
    g2d.drawImage(image, 0, 0, null);
    g2d.dispose();

    return rotated;
}

然后你只需要打电话......

picLabel.setIcon(new ImageIcon(rotateBy(scaledImage, 22.5)));

因为setIcon是一个绑定属性,它应该自动触发布局和绘制通道,否则,你可以简单地调用revalidaterepaint来手动触发它们

答案 1 :(得分:0)

我看到您正在使用picLabel存储图像并显示它:

     picRotate(scaledImage, 400,temp1);

        picLabel = new JLabel(new ImageIcon(scaledImage));
           content.add(picLabel);
           content.revalidate();
           content.repaint();

由于某种原因,标签尺寸是图像的高度和宽度,但标签并不知道图像已旋转。解决这个问题的方法可能是在将图像添加到标签之前设置标签的大小,并且可以保证即使旋转图像也能容纳整个图像:

     picRotate(scaledImage, 400,temp1);

        picLabel = new JLabel();
           picLabel.setPreferredSize(new Dimension(800, 800));
           picLabel.add(new ImageIcon(scaledImage))
           content.add(picLabel);
           content.revalidate();
           content.repaint();

现在,必须根据旋转图像所需的空间计算首选大小的picLabel宽度和高度。我的一些三角函数可能对此有所帮助。我假设800x800有足够的空间容纳图像