Adjust Image Size with Java Imagery

Asked

Viewed 2,615 times

1

I would like to resize an image to be shown in my jLabel. Here’s my code:

    BufferedImage imagem;
    Icon novaImg;
    try {
        String newPath = "file:///" + aleat(); // carrega imagem aleatória

        imagem = ImageIO.read(new URL(newPath));

        novaImg = new ImageIcon(imagem);
        jLabelPrincipal.setIcon(novaImg);
    } catch(IOException exception) {
        System.err.println(exception);
    }

1 answer

1


    BufferedImage imagem;
    Icon novaImg;
    try {
        String caminho = "file:///" + aleat(); // carrega imagem aleatória
        int largura = 200, altura = 300;
        imagem = ImageIO.read(new URL(caminho));
        novaImg = new ImageIcon(imagem.getScaledInstance(largura, altura,
        java.awt.Image.SCALE_SMOOTH));

    } catch(IOException exception) {
        System.err.println(exception);
    }
  • imagem = (BufferedImage) imagem.getScaledInstance(largura, altura, java.awt.Image.SCALE_SMOOTH);

java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage

  • @user5693, edited the answer and now this' without the casting.

  • 1

    This new one was really good, exactly the way I wanted it! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.