调整图像大小以适应jLabel麻烦

时间:2013-10-05 16:06:36

标签: java image image-processing awt bufferedimage

我想重新调整我的ImageIcon大小以适合我的jLabel。使用这篇文章的答案Scale the ImageIcon automatically to label size我正在使用

public jfrmHome() {
    initComponents();
    this.setLocationRelativeTo(null);
    ImageIcon iconimage;
    iconimage = new ImageIcon(getClass().getResource("/org/me/musiconweb/resources/Music-icon.png"));
    BufferedImage bi = new BufferedImage(iconimage.getIconWidth(), iconimage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics g = bi.createGraphics();
    iconimage.paintIcon(null, g, 0,0);
    g.dispose();
    BufferedImage resizedimage=resize(bi,jlblPicture.getWidth(), jlblPicture.getHeight());
    ImageIcon resizedicon=new ImageIcon(resizedimage);
    jlblPicture.setIcon(resizedicon);
}

这会重新调整Image的大小,但我有一点问题。图像的背景变为黑色而不是白色

original image

转向

error image

请问我做错了什么?

3 个答案:

答案 0 :(得分:3)

该图像具有透明度。因此,将BufferedImage.TYPE_INT_RGB更改为BufferedImage.TYPE_INT_ARGB

在白色BG的SO上并不明显,但试试这个SSCCE&它变得更加清晰..

import java.net.URL;
import javax.swing.*;

class ShowImage {

    public static void main(String[] args) throws Exception {
        final URL url = new URL("http://i.stack.imgur.com/1yeUy.png");
        Runnable r = new Runnable() {
            @Override
            public void run() {
                JLabel l = new JLabel(new ImageIcon(url));

                JOptionPane.showMessageDialog(null, l);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

enter image description here

答案 1 :(得分:0)

您的图片具有透明背景。因此,当在新创建的不透明图像上绘制时,它显示为黑色。使用

g.setColor(Color.WHITE);
g.fillRect(0, 0, jlblPicture.getWidth(), jlblPicture.getHeight());

如果你想要一个白色背景。对于透明背景,请改为在TYPE_INT_ARGB图像上绘制。

答案 2 :(得分:0)

试试这些代码

ImageIcon icon1 = new 
ImageIcon(getClass().getResource("\\image\\"+f1.getName()));  
BufferedImage bi = new 
BufferedImage(icon1.getIconWidth(),icon1.getIconHeight()
,   BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
icon1.paintIcon(null, g, 0,0);
g.dispose();`
        //image resizing code...............>
ImageIcon resizedicon=new ImageIcon(bi.getScaledInstance(imglbl.getWidth(), 
imglbl.getHeight(),1 ));
imglbl.setBackground(new java.awt.Color(255, 255, 255));
imglbl.setIcon(resizedicon);