将imageIcon导出为缓冲的图像

我下面的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,width,height);
            g2d.setColor(Color.black);
            g2d.fillOval(0,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();  


    }  



}  
gongchen10 回答:将imageIcon导出为缓冲的图像

除了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,null);
g.dispose();

您可以轻松地用它制作一个ImageIcon:

b2.setIcon(new ImageIcon(scaledButtonImage));

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

本文链接:https://www.f2er.com/2565036.html

大家都在问