Image对象与 BufferedImage

由一个Imge转化成BufferedImage,源码如下:
//covert Image object to BufferedImage object
//pic (Image type)
	private BufferedImage convertImageToBuffer(){
		BufferedImage bufferedImage = new BufferedImage(pic
				.getWidth(null), pic.getHeight(null),
				BufferedImage.TYPE_INT_RGB);
		Graphics g = bufferedImage.createGraphics();
		g.drawImage(pic, 0, 0, null);
		g.dispose();
		return bufferedImage;
	}



获取JPanel上的图像,并将其保存为jpg格式图片:
public static void saveImage(Component com){
		int comH=com.getHeight();
		int comW=com.getWidth();
		BufferedImage bufferImage=new BufferedImage(comW,comH,BufferedImage.TYPE_INT_RGB);
		Graphics2D g2=bufferImage.createGraphics();
		g2.setBackground(Color.white);
		com.paint(g2);
		g2.dispose();
FileFilter filter = new FileFilter() {
			@Override
			public boolean accept(File f) {
				// TODO Auto-generated method stub
				return f.isFile() && f.getName().endsWith("jpg")
						|| f.getName().endsWith("JPG");
			}

			@Override
			public String getDescription() {
				// TODO Auto-generated method stub
				return "JPG or jpg";
			}
		};
		JFileChooser fileChoose = new JFileChooser();
		fileChoose.setFileFilter(filter);
		int result = fileChoose.showSaveDialog(null);
		if (result == JFileChooser.APPROVE_OPTION) {
			File file = fileChoose.getSelectedFile();
			String path = file.getPath();
		try {

				FileOutputStream output = new FileOutputStream(path);
				JPEGImageEncoder jpg = JPEGCodec.createJPEGEncoder(output);
				jpg.encode(bufferImage);
				output.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ImageFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

你可能感兴趣的:(F#)