LoadImage.java:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JApplet;
public class LoadImage extends JApplet{
String addrs="D:\\test1.jpg";//改成自己的图片路径
BufferedImage mm,child;
CutImage ci;
public LoadImage(){
try {
mm=ImageIO.read(new File(addrs));
} catch (IOException e) {
System.out.println("图片读取失败!");
e.printStackTrace();
}
ci=new CutImage(mm);
child=ci.getChildImage(50, 0, 150, 220);
}
public void init(){
}
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("原图:",0,10);
g.drawImage(mm, 20,10,this);
g.drawString("ci.getChildImage(50, 0, 150, 220)截取后的图片",mm.getWidth()+30,10);
g.drawImage(child, mm.getWidth()+50,20,this);
}
}
CutImage.java
import java.awt.Image;
import java.awt.image.BufferedImage;
public class CutImage {
private BufferedImage img;
private BufferedImage child;
public CutImage(){
}
public CutImage(BufferedImage im){
img=im;
}
public CutImage(Image im){
img=(BufferedImage)im;
}
public void setImg(BufferedImage img) {
this.img = img;
}
public BufferedImage getChildImage(int x,int y,int width,int height) {
int cw=width;
int ch=height;
int pw=img.getWidth();
int ph=img.getHeight();
if(pw<x+width){
System.out.println("给出的参数超出原图片的范围!程序会自动减小宽度或高度");
cw=pw-x;
}
if(ph<y+height){
System.out.println("给出的参数超出原图片的范围!程序会自动减小宽度或高度");
ch=ph-y;
}
child=new BufferedImage(cw,ch,BufferedImage.TYPE_INT_ARGB );
for(int i=0;i<ch;i++){
for(int j=0;j<cw;j++){
child.setRGB(j, i, img.getRGB(x+j, y+i));
}
}
return child;
}
}