10.2图片处理

从硬盘读取图片

Image image = null;
try {
// Read from a file
File file = new File("image.gif");
image = ImageIO.read(file);

// Read from an input stream
InputStream is = new BufferedInputStream(
new FileInputStream("image.gif"));
image = ImageIO.read(is);

// Read from a URL
URL url = new URL("http://hostname.com/image.gif");
image = ImageIO.read(url);
} catch (IOException e) {
}

// Use a label to display the image
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);

产生缩略图  和  使两个图片合并到一起

import java.awt.AWTException;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

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

public class MyImage extends JFrame{

@SuppressWarnings("deprecation")
public MyImage(){
JLabel jl = new JLabel();
//Image im = this.getImage();
Image im = null;
try {
im = this.margeImages();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageIcon ic = new ImageIcon(im);
jl.setIcon(ic);
this.add(jl);
this.setSize(600,450);
this.show();
}

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

public Image getImage(){
Image img = null;
try {
/*
* 截屏并产生缩略图
*/
Robot myrobot = new Robot();
BufferedImage bi = myrobot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
/*
* 产生缩略图的方法
*/
img = bi.getScaledInstance(360, 250, BufferedImage.SCALE_AREA_AVERAGING);

} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return img;
}

public Image margeImages() throws IOException{
BufferedImage b = null;
Image img1 = null;
Image img = null;
try {
/*
* 截全屏
*/
b = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
img = b.getScaledInstance(b.getWidth(), b.getHeight(), BufferedImage.SCALE_SMOOTH);
img1 = b.getScaledInstance(300, 200, BufferedImage.SCALE_SMOOTH);
} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* 获得画布
*/
Graphics my_g = b.getGraphics();
/*
* 画另一副图
*/
my_g.drawImage(img1, 100, 100, 200, 400,null);
//my_g.drawImage(img,0,0,b.getWidth(), b.getHeight(),null);
/*
* 释放相应的资源
*/
my_g.dispose();
return img;
}

}

posted @ 2012-02-19 11:01  张良  阅读(188)  评论(0编辑  收藏  举报