Java: Load image from file, edit and add to JPanel

允我心安 提交于 2019-12-25 07:52:02

问题


I want to load an image from my computer into 2D Graphics so that I can edit it afterwards and then I want to add it to JPanel. If you need to see my project I can send it to you.

void loadImage()
{

    FileDialog fd = new FileDialog(new Frame(), "Please choose a file:", FileDialog.LOAD);
    fd.show();
    if (fd.getFile() != null)
    {
        File fil = new File(fd.getDirectory(), fd.getFile());
        strDirectory = fd.getDirectory();
        strFileType = fd.getFile();
        mainImage.setIcon(new ImageIcon(fil.toString()));
        getFileList(strDirectory);
        checkFileType(strFileType);
    }
}

Thanks in advance


回答1:


To load your image into the memory, you can use ImageIO.read(File). To edit it afterwards, obtain a Graphics2D instance from it by calling createGraphics():

BufferedImage img = ImageIO.read(yourFile);
Graphics2D g = img.createGraphics();
// Draw here on the graphics
g.dispose();

You can even turn on anti-alias by setting a RenderingHint before drawing:

g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                   RenderingHints.VALUE_ANTIALIASING_ON);

Then, to add it to a JPanel, create your custom JComponent and add an instance of that component to your JPanel:

public class JImageComponent extends JComponent
{
    private BufferedImage img;

    public JImageComponent(BufferedImage bi)
    {
        img = bi;
    }

    @Override
    public void paintComponent(Graphics g)
    {
        g.drawImg(img, 0, 0, this);
    }

}



回答2:


please read this tutorials about Icon in Swing and your Image/ImageIcon would by placed to the JLabel, this way eliminated all troubles came from paint/paintComponents ...




回答3:


For image loading you should use ImageIO object with method read(File file) see docs. Then you will get BufferedImage instance of which you can make your changes through Graphics2D instance which you'll obtain by calling createGraphics() on the image instance see docs. Last thing, override method paintComponent() from JPanel or better JComponent see docs and there you can draw your image on Graphics instance which you'll get as parameter in paintComponent(Graphics g) method by calling drawImage(Image img, int x, int y, ImageObserver observer) see docs where ImageObserver set to null.



来源:https://stackoverflow.com/questions/6795023/java-load-image-from-file-edit-and-add-to-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!