Java resize an image

徘徊边缘 提交于 2019-12-11 11:14:57

问题


I would like to display an image in an area in my Jframe but the image takes up much space.

I would like to take it fair precise dimensions. How can I do this in Java

This is my simple code :

I am open to any proposal if I did not use the right method or the right class to instantiate the image.

import java.awt.*;
import javax.swing.*;

public class ExempleDeplace extends JFrame{

    private JLabel myLabel;

    public ExempleDeplace(){
         setLayout(new FlowLayout());
         setTitle("Fenetre, modele Duchi");
         setSize(500,700);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         JLabel j = new JLabel(new ImageIcon("src/images/bateau.png"));
         add(j);
         setVisible(true);
    }

    public static void main (String[] args) {    
          ExempleDeplace c = new ExempleDeplace();
    }
}

回答1:


You can paint the image in a JPanel as the whole panel. Then whenever the panel is resized, the image will be resized along with it. Here's a quick-n-dirty runnable demo:

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ImgFrame extends JFrame {

    private static BufferedImage IMG;
    static{
        try {
            IMG = ImageIO.read(new File("img/Original_Doge_meme.jpg")); //Replace with your image path
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ImgFrame(){
        add(new ImgPanel(), BorderLayout.CENTER);
        setSize(500,700);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    class ImgPanel extends JPanel{
        @Override
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g.drawImage(IMG, 0, 0, getWidth(), getHeight(), this);
        }
    }

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



回答2:


It's probably cleaner to just resize the image. I highly recommend the image resizing utility methods provided by filthyrichclients.

I actually highly recommend the book as well, as it was one of the few books that actually demonstrated the power of Swing...

Once you have the code, you will want to call

createCompatibleImage(myImage, myWidth,myHeight);


来源:https://stackoverflow.com/questions/28701599/java-resize-an-image

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