Java ImageIcon Load getImageIcon(URL u, int w)

Here you can find the source of getImageIcon(URL u, int w)

Description

get Image Icon

License

Apache License

Declaration

public static ImageIcon getImageIcon(URL u, int w) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2014 Rafael Garcia Moreno.//from w ww  .j  a  v  a 2  s . c o  m
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Main {
    public static ImageIcon getImageIcon(URL u, int w) throws IOException {
        BufferedImage img = null;
        BufferedImage tmp = ImageIO.read(u);
        ImageIcon icon = null;

        if (tmp != null) {
            float h = (float) tmp.getHeight() * (float) w / (float) tmp.getWidth();

            img = scaleImage(w, (int) h, tmp, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            icon = new ImageIcon((Image) img);
        }

        return icon;
    }

    public static BufferedImage scaleImage(int w, int h, BufferedImage img, Object interpolation) {
        BufferedImage bi;

        bi = new BufferedImage(w, h, img.getType());
        Graphics2D g2d = (Graphics2D) bi.createGraphics();
        // g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        // RenderingHints.VALUE_ANTIALIAS_ON);
        // g2d.addRenderingHints(new
        // RenderingHints(RenderingHints.KEY_RENDERING,
        // RenderingHints.VALUE_RENDER_QUALITY));

        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation);
        g2d.drawImage(img, 0, 0, w, h, null);
        g2d.dispose();
        return bi;
    }
}

Related

  1. getImageIcon(String name)
  2. getImageIcon(String path)
  3. getImageIcon(String path, String description)
  4. getImageIcon(String res)
  5. getImageIcon(String resource)
  6. getImageIcon(URL url)
  7. getScaledInstance(Image img, int targetWidth, int targetHeight)
  8. loadImageIcon(byte bytes[], String descr)
  9. loadImageIcon(Class clas, String iconPath)