applet中保存canvas中的图片

效果图如下:


 

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.CubicCurve2D;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
 
public class ComponentToImage extends Canvas {
    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        int w = getWidth();
        int h = getHeight();
        g2.setPaint(getBackground());
        g2.fillRect(0,0,w,h);
        g2.setPaint(Color.red);
        g2.draw(new CubicCurve2D.Double(w/4, h*3/4, -w*3/8, -h/4,
                                        w*11/8, -h/4, w*3/4, h*3/4));
    }
 
    private BufferedImage makeImage() {
        int w = getWidth();
        int h = getHeight();
        int type = BufferedImage.TYPE_INT_RGB;
        BufferedImage image = new BufferedImage(w,h,type);
        Graphics2D g2 = image.createGraphics();
        paint(g2);
        g2.dispose();
        return image;
    }
 
    private void save(BufferedImage image) {
        String ext = "jpg";  // png, bmp (j2se 1.5+), gif (j2se 1.6+)
        File file = new File("componentToImage." + ext);
        try {
            ImageIO.write(image, ext, file);
        } catch(IOException e) {
            System.out.println("write error: " + e.getMessage());
        }
    }
 
    private void saveToFile() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch(InterruptedException e) {
                    System.out.println("interrupted");
                }
                save(makeImage());
            }
        }).start();
    }
 
    public static void main(String[] args) {
        ComponentToImage test = new ComponentToImage();
        Frame f = new Frame();
        f.addWindowListener(closer);
        f.add(test);
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
        test.saveToFile();
    }
 
    private static WindowListener closer = new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    };
}

 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值