JTable保存为图片

历经几天研究,终于搞定,记录下
代码如下:
import java.awt.*;  
import java.awt.image.BufferedImage;  
import java.io.OutputStream;  
import javax.imageio.ImageIO;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.swing.*;  
import javax.swing.table.TableColumn;  
import javax.swing.table.DefaultTableModel;  
import javax.swing.table.DefaultTableCellRenderer;  
  
  
public class ImageGenerator extends HttpServlet {  
    /** */  
    /** 
     * 
     */  
    private static final long serialVersionUID = -3938318741402322164L;  
  
  
    @Override  
    public void doGet(HttpServletRequest request, HttpServletResponse response) {  
        try {  
  
            response.setHeader("Pragma", "No-cache");  
            response.setHeader("Cache-Control", "no-cache");  
            response.setDateHeader("Expires", 0);  
  
            //GraphicsEnvironment ge =  
               //     GraphicsEnvironment.getLocalGraphicsEnvironment();  
            //System.out.println("ge.isHeadless() = " + ge.isHeadless());  
            //if (!ge.isHeadless()) {  
            //    System.setProperty("java.awt.headless", "true");  
            //}  
  
            String columnNames[] = {"编号", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"};  
            String[][] rowData = {{"04001", "01", "02", "", "", "", "", "", "", "", "", ""}  
                    , {"04001", "01", "02", "", "", "", "", "", "", "", "", ""}  
                    , {"04002", "", "", "03", "", "", "06", "", "08", "", "", ""}  
                    , {"04003", "", "02", "", "04", "05", "", "", "", "", "", ""}  
                    , {"04004", "", "", "", "", "", "", "07", "", "09", "10", ""}  
                    , {"04005", "", "", "", "", "", "", "", "", "", "", ""}  
                    , {"04006", "", "", "", "", "", "06", "", "08", "", "", ""}  
                    , {"04007", "", "", "", "04", "", "", "07", "", "", "", ""}  
                    , {"04008", "", "", "", "", "05", "", "", "", "09", "", "11"}  
                    , {"04009", "01", "", "03", "", "05", "", "", "", "", "", ""}  
            };  
            DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {  
  
                public boolean isCellEditable(int row, int column) {  
                    return false;  
                }  
            };  
  
            DefaultTableCellRenderer tcr = new DefaultTableCellRenderer() {  
                public Component getTableCellRendererComponent(JTable table,  
                                                               Object value, boolean isSelected, boolean hasFocus,  
                                                               int row, int column) {  
  
                    if (value != null && value.toString().trim().length() != 0 && column != 0) {  
                        setBackground(Color.red);  
                    } else {  
                        setBackground(Color.white);  
                    }  
                    return super.getTableCellRendererComponent(table, value,  
                            isSelected, hasFocus, row, column);  
                }  
            };  
            
            //Jtable大小
            int table_width = 300;  
            int table_hight = 180; 
            //图片生成后再压缩后大小
            int image_width = 180; 
            int image_hight = 180; 
             
            JTable table = new JTable(model);  
            table.setPreferredSize(new Dimension(table_width, table_hight));  
            //设置列表现器------------------------//  
            for (int i = 0; i < columnNames.length; i++) {  
                table.getColumn(columnNames[i]).setCellRenderer(tcr);  
            }  
            int width = 40;  
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);  
  
            TableColumn firsetColumn = table.getColumnModel().getColumn(0);  
            firsetColumn.setPreferredWidth(width);  
            firsetColumn.setMinWidth(width);  
            firsetColumn.setMinWidth(width);  
            JFrame f = new JFrame();  
            JScrollPane scrollPane = new JScrollPane(table);  
            scrollPane.setAutoscrolls(false);  
            f.getContentPane().add(scrollPane);  
            f.setSize(table_width, table_hight);  
            f.pack();  
            //f.setVisible(true);  
              
              
            BufferedImage image = createImage(table);  
            if (f != null) {  
                f.dispose();  
            }  

            //对图片进行压缩处理,输出到指定目录
            JTableImageCreator.reduceImg(image
                    , "d:/test.png"
                    , image_width, image_hight);

            OutputStream os = response.getOutputStream();  
            ImageIO.write(image, "PNG", os);  
            os.flush();  
            os.close();  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
  
    }  
  
    public static BufferedImage createImage(JTable table) {  
        //get the table header component  
        JTableHeader tableHeaderComp = table.getTableHeader();  
  
        int totalWidth = table.getPreferredSize().width;  
        int totalHeight = table.getPreferredSize().height;  
        BufferedImage tableImage = new BufferedImage(totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB);  
  
        Graphics2D g2D = (Graphics2D) tableImage.createGraphics();  
  
        g2D.setColor(Color.WHITE);  
        g2D.fillRect(0, 0, totalWidth, totalHeight);  
  
        g2D.translate(0, 0);  
        tableHeaderComp.paint(g2D);  
  
        g2D.translate(0, tableHeaderComp.getPreferredSize().height);  
        table.paint(g2D);  
  
  
        g2D.dispose();  
  
        //return the table image  
        return tableImage;  
    }  
    
    //压缩图片
    public static void reduceImg(BufferedImage bufferedImage, String imgdist, int widthdist,
                                 int heightdist) {
        try {
            BufferedImage tag = new BufferedImage(widthdist,
                    heightdist, BufferedImage.TYPE_INT_RGB);
            /*
            * Image.SCALE_SMOOTH 的缩略算法  生成缩略图片的平滑度的
            * 优先级比速度高 生成的图片质量比较好 但速度慢
            */
            tag.getGraphics().drawImage(
                    bufferedImage.getScaledInstance(widthdist, heightdist,
                            Image.SCALE_SMOOTH), 0, 0, null);


            ImageIO.write(tag, "png", new File(imgdist));
        } catch (IOException e) {
            logger.error("reduceImg error :" + e.toString());
        }
    }
  
}  


该段代码是运行在tomcat调试所用,所以需要配置下web.xml
加入
<servlet>
        <servlet-name>imageGenerator</servlet-name>
        <servlet-class>com.topman.molowap.data.trendimage.ImageGenerator</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>imageGenerator</servlet-name>
        <url-pattern>/image.jsp</url-pattern>
    </servlet-mapping>


在linux环境下需要配置x windons
启动命令:startx &
然后执行命令:
1) export DISPLAY=:0.0
2) xhost +
为linux环境下配置郁闷了好几天,-Djava.awt.headless=true这个参数就不能加在java启动项里,原理没有去深究了,日后再补
配置是否成功访问: http://ip:port/image.jsp,如果显示出图片,表明配置成功


你可能感兴趣的:(linux,swing,servlet,OS,F#)