利用ImageIO读取图片文件, 再利用BufferedImage的getSubimage取到X,Y轴和需要取出来的图片的宽高。
package com.vod.util;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
/**
* 这个类用于从整个图片中加载每个项目的图片
*/
public class ImageLoader {
private static BufferedImage sourceImg;
public ImageLoader(String imagePath) throws IOException {
sourceImg = ImageIO.read(new File(imagePath));
}
/**
* 处理Image
*
* 以左上角顶点为基准
*
* @param posX
* 左上角顶点的x轴
* @param posY
* 左上角顶点的x轴
* @param width
* 图片的宽度
* @param height
* 图片的高度
* @return img
*/
public Image getImage(int posX, int posY, int width, int height) {
BufferedImage targetImg = this.sourceImg.getSubimage(posX, posY, width, height);
Image img = new ImageIcon(targetImg).getImage();
return img;
}
/**
* 处理ImageIcon
*
* 以左上角顶点为基准
*
* @param posX
* 左上角顶点的x轴
* @param posY
* 左上角顶点的x轴
* @param width
* 图片的宽度
* @param height
* 图片的高度
* @return img
*/
public static ImageIcon getIconImage(int posX, int posY, int width, int height) {
BufferedImage targetImg = sourceImg.getSubimage(posX, posY, width, height);
ImageIcon img = new ImageIcon(targetImg);
return img;
}
/**
* 感觉处理出来的图片不如 上面两个的。
*
* @param button
* @param posX
* @param posY
* @param width
* @param height
* @param tip
* @return
*/
public static JButton changeIconSize(JButton button, int posX, int posY, int width, int height, String tip) {
button.setBounds(0, 0, width, height);
ImageIcon buttonImg = getIconImage(posX, posY, width, height);
buttonImg.getImage();
// 改变图片的大小
Image temp = buttonImg.getImage().getScaledInstance(button.getWidth(), button.getHeight(), Image.SCALE_DEFAULT);
button = new JButton(new ImageIcon(temp));
// 以下是设置按钮为透明的,这样图片才能填充满整个按钮
button.setOpaque(false); // 设置边缘不显示
button.setContentAreaFilled(false); // 显示为透明按钮
// button.setFocusPainted(false); //去掉按钮文字周围的焦点框
button.setBorderPainted(false);// 去除按钮的边框
// button.setBorder(null); //设置边缘为空
// button.setMargin(new Insets(0, 0, 0, 0));//是设置边距的。
button.setToolTipText(tip); // 提示
return button;
}
/**
*
* @param button
* @param url
* @param width
* @param height
* @param tip
* @return
*/
public static JButton changeIconSize(JButton button, String url, int width, int height, String tip) {
button.setBounds(0, 0, width, height);
ImageIcon buttonImg = new ImageIcon(url);
// 改变图片的大小
Image temp = buttonImg.getImage().getScaledInstance(button.getWidth(), button.getHeight(),
buttonImg.getImage().SCALE_DEFAULT);
button = new JButton(new ImageIcon(temp));
button.setToolTipText(tip); // 提示
return button;
}
}