将imageIcon导出为缓冲图像

问题描述 投票:0回答:1

我下面的Java代码现在在标签和按钮中显示一个imageIcon。当按下按钮时,它将绘制一个缓冲的图像并导出该图像。导出的图像与图像图标中的图像无关。

而不是绘制图像,我希望在ImageIcon中导出图像,就像绘制和导出图像一样。因此,我认为必须将图像Icon中的图像转换为缓冲图像,然后导出为400宽度和400高度的图像。

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import javax.swing.*;  

public class second {  
JFrame f;  
second() throws IOException{ 

//use paintCompent 


    f=new JFrame();  
    JButton b1 = new JButton("Action Listener");

    JLabel b2=new JLabel("");;  


    b2.setIcon(new ImageIcon(new ImageIcon("/Users/johnzalubski/Desktop/javaCode/cd.jpg").getImage().getScaledInstance(400, 400, Image.SCALE_DEFAULT)));





    f.add(b1,BorderLayout.NORTH);  
    f.add(b2,BorderLayout.CENTER);  



    b1.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int width = 300;
            int height = 300;


            BufferedImage  buffIMg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = buffIMg.createGraphics();

            g2d.setColor(Color.white);
            g2d.fillRect(0, 0, width, height);
            g2d.setColor(Color.black);
            g2d.fillOval(0,0,width,height);
            g2d.setColor(Color.orange);
            g2d.drawString("Jessica ALba:", 55, 111);


            g2d.dispose();


            File file = new File("aa.png");

            try {
                ImageIO.write(buffIMg, "png",file);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });


    f.setSize(400,400);  
    f.setVisible(true);  
}  
    public static void main(String[] args) throws IOException {  
    new second();  


    }  



}  
java jbutton bufferedimage imageicon actionevent
1个回答
0
投票

除了write方法之外,ImageIO还具有read方法。使用它来加载图像,而不是使用ImageIcon拥有图像加载器:

BufferedImage unscaledButtonImage;
try {
    unscaledButtonImage = ImageIO.read(
        new File("/Users/johnzalubski/Desktop/javaCode/cd.jpg"));
} catch (IOException e) {
    throw new RuntimeException(e);
}

要缩放,请使用scaling Graphics.drawImage method

BufferedImage scaledButtonImage =
    new BufferedImage(400, 400, unscaledButtonImage.getType());
Graphics g = scaledButtonImage.createGraphics();
g.drawImage(unscaledButtonImage, 0, 0, 400, 400, null);
g.dispose();

您可以很容易地用它制作一个ImageIcon:

b2.setIcon(new ImageIcon(scaledButtonImage));

但是之后您就不需要ImageIcon了,因为您有原始的BufferedImage。

© www.soinside.com 2019 - 2024. All rights reserved.