黑马程序员java   图片添加水印

来源:互联网 发布:use女装知乎 编辑:程序博客网 时间:2024/05/17 03:00
package ekaiser.rong.frame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;

public class NonstandardFrame extends JFrame {
    //图片预览面板
    privatePhotoPanel pane = null;
    //预览滚动面板
    privateJScrollPane scrollPane = null;
    //上方的面板
    private BoxboxNorth = null;
    //下方的面板
    private BoxboxSouth = null;
    //图片地址文本框
    privateJTextField imageFileText = null;
    //打开图片按钮
    privateJButton openFileButton = null;
    //水印文字
    privateJTextField text = null;
    //字体大小文本框
    privateJTextField fontSizeText = null;
    //是否粗体
    privateJCheckBox boldBox = null;
    //是否斜体
    privateJCheckBox italicBox = null;
    //字体文本框
    privateJComboBox fontBox = null;
    //文字显示X坐标
    privateJTextField pointXText = null;
    //文字显示Y坐标
    privateJTextField pointYText = null;
    // 调色板
    privateJColorChooser colorChooser = null;
    //颜色按钮
    privateJButton colorButton = null;
    //透明度滑块
    privateJScrollBar alphaBar = null;
    //透明度文本框
    privateJTextField alphaText = null;
    //预览按钮
    privateJButton previewButton = null;
    //输出图片按钮
    privateJButton outImagebutton = null;
    //图片输入、输出选择框
    privateJFileChooser fileChooser = null;
    //缓冲图像
    privateBufferedImage bufferedImage = null;
    //导入的图片
    privateImage image = null;

   
    publicNonstandardFrame() {
       super("图像水印小工具");
       init();
       getContentPane().add(boxNorth, BorderLayout.NORTH);
       getContentPane().add(scrollPane);
       getContentPane().add(boxSouth, BorderLayout.SOUTH);
       setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       setSize(800, 600);
       setLocationRelativeTo(null);
       setVisible(true);
    }

   
    private voidinit() {
       pane = new PhotoPanel();
       scrollPane = new JScrollPane(pane);
       boxNorth = Box.createHorizontalBox();
       boxSouth = Box.createHorizontalBox();
       boxNorth.setBorder(BorderFactory.createEmptyBorder(5, 5, 5,5));
       boxSouth.setBorder(BorderFactory.createEmptyBorder(5, 5, 5,5));
       text = new JTextField("Java实现照片水印效果", 30);
       imageFileText = new JTextField(20);
       imageFileText.setEditable(false);
       openFileButton = new JButton("打开图片");
       // 打开图片
       openFileButton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               loadImage();
           }
       });
       // 获得系统默认字体
       GraphicsEnvironment eq = GraphicsEnvironment
               .getLocalGraphicsEnvironment();
       String[] fontNames = eq.getAvailableFontFamilyNames();
       // 构造字体选择组件
       fontBox = new JComboBox(fontNames);
       fontBox.setPreferredSize(new Dimension(80, 20));
       fontBox.setMinimumSize(new Dimension(80, 20));
       fontBox.setMaximumSize(new Dimension(80, 20));
       // 默认宋体
       fontBox.setSelectedItem("宋体");
       fontSizeText = new JTextField("30", 4);
       // 透明度滑块
       alphaBar = new JScrollBar(JScrollBar.HORIZONTAL);
       alphaBar.setMaximum(265);
       alphaBar.setMinimum(1);
       alphaBar.setValue(255);
       alphaBar.setPreferredSize(new Dimension(120, 18));
       alphaText = new JTextField("255");
       alphaText.setMinimumSize(new Dimension(45, 28));
       alphaText.setEditable(false);
       alphaBar.addAdjustmentListener(new AdjustmentListener() {
           public void adjustmentValueChanged(AdjustmentEvent e) {
               alphaText.setText(String.valueOf(alphaBar.getValue()));
           }
       });
       boldBox = new JCheckBox("粗体", true);
       italicBox = new JCheckBox("斜体", true);
       pointXText = new JTextField("30", 4);
       pointYText = new JTextField("50", 4);
       // 颜色按钮,默认黑色
       colorButton = new JButton(" ");
       colorButton.setBackground(Color.BLACK);
       colorButton.setPreferredSize(new Dimension(28, 28));
       // 构造调色板组件,默认黑色
       colorChooser = new JColorChooser(Color.BLACK);
       colorButton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               Color color = colorChooser.showDialog(NonstandardFrame.this,"选择文字颜色", Color.BLACK);
               colorButton.setBackground(color);
           }
       });
       previewButton = new JButton("效果预览");
       previewButton.setEnabled(false);
       previewButton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               preview();
           }
       });
       fileChooser = new JFileChooser();
       // 添加过滤器
       fileChooser.setFileFilter(new FileFilter() {
           public String getDescription() {
               return "*.jpg";
           }
           public boolean accept(File f) {
               String name = f.getName();
               String e = name.substring(name.lastIndexOf(".") + 1);
               return f.isDirectory() || e.equalsIgnoreCase("jpg") ? true :false;
           }
       });
       outImagebutton = new JButton("生成图片");
       outImagebutton.setEnabled(false);
       outImagebutton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               writeImage();
           }
       });
       boxNorth.add(new JLabel("图片:"));
       boxNorth.add(imageFileText);
       boxNorth.add(openFileButton);
       boxNorth.add(Box.createHorizontalStrut(10));
       boxNorth.add(new JLabel("水印文字:"));
       boxNorth.add(text);
       boxNorth.add(Box.createHorizontalStrut(10));
       boxNorth.add(outImagebutton);
       boxSouth.add(new JLabel("字体:"));
       boxSouth.add(fontBox);
       boxSouth.add(Box.createHorizontalStrut(10));
       boxSouth.add(new JLabel("大小:"));
       boxSouth.add(fontSizeText);
       boxSouth.add(Box.createHorizontalStrut(10));
       boxSouth.add(boldBox);
       boxSouth.add(Box.createHorizontalStrut(10));
       boxSouth.add(italicBox);
       boxSouth.add(Box.createHorizontalStrut(10));
       boxSouth.add(new JLabel("颜色:"));
       boxSouth.add(colorButton);
       boxSouth.add(Box.createHorizontalStrut(10));
       boxSouth.add(new JLabel("透明:"));
       boxSouth.add(alphaText);
       boxSouth.add(alphaBar);
       boxSouth.add(Box.createHorizontalStrut(10));
       boxSouth.add(new JLabel("X:"));
       boxSouth.add(pointXText);
       boxSouth.add(Box.createHorizontalStrut(10));
       boxSouth.add(new JLabel("Y:"));
       boxSouth.add(pointYText);
       boxSouth.add(Box.createHorizontalStrut(10));
       boxSouth.add(previewButton);
    }

   
    private voidloadImage() {
       // 设置为打开模式
       int x = fileChooser.showOpenDialog(this);
       if (x == 0) {
           File file = fileChooser.getSelectedFile();
           imageFileText.setText(file.getPath());
           createBufferedImage(file);
           previewButton.setEnabled(true);
           outImagebutton.setEnabled(true);
       }
    }

   
    private voidwriteImage() {
       int x = fileChooser.showSaveDialog(this);
       if(x == 0){
           File file = fileChooser.getSelectedFile();
           // 防止未输入jpg后缀名
           if(file.getName().indexOf(".") == -1){
               file = new File(file.getPath() + ".jpg");
           }
           try {
               BufferedImage bi = pane.getImage();
               ImageIO.write(bi, "jpg", file);
               JOptionPane.showMessageDialog(this, "图片已保存成功!", "成功",JOptionPane.INFORMATION_MESSAGE);
           }catch (NullPointerException e) {
               JOptionPane.showMessageDialog(this, "请先加载图片后再生成图片!", "警告",JOptionPane.WARNING_MESSAGE);
           }catch (IOException e) {
               JOptionPane.showMessageDialog(this, "错误:图像写入文件发生IO错误!", "IO错误",JOptionPane.ERROR_MESSAGE);
           }
       }
    }
   
   
    public voidpreview() {
       // 如果还没有加载图片
       if(pane.getBufferedImage() == null){
           JOptionPane.showMessageDialog(this, "请先加载图片后再预览效果!", "预览警告",JOptionPane.WARNING_MESSAGE);
           return;
       }
       String str = text.getText();
       int style = 0;
       if(boldBox.isSelected()){
           style = 1;
       }
       if(italicBox.isSelected()){
           style = 2;
       }
       if(boldBox.isSelected() &&italicBox.isSelected()){
           style = 3;
       }
       Font font = new Font((String) fontBox.getSelectedItem(), style,Integer.parseInt(fontSizeText.getText()));
       Color c = colorButton.getBackground();
       Color color = new Color(c.getRed(), c.getGreen(), c.getBlue(),alphaBar.getValue());
       int x = Integer.parseInt(pointXText.getText());
       int y = Integer.parseInt(pointYText.getText());
       pane.setDrawString(str, x, y, font, color);
       pane.showPhoto();
    }
   
   
    private voidcreateBufferedImage(File file) {
       try {
           bufferedImage = ImageIO.read(file);
           if (bufferedImage == null) {
               JOptionPane.showMessageDialog(this, "失败,图片格式已损坏!", "图片加载警告",
                       JOptionPane.WARNING_MESSAGE);
               return;
           }
           drawImage();
       } catch (IOException e) {
           JOptionPane.showMessageDialog(this, "失败,IO读取错误!", "图片加载警告",
                   JOptionPane.ERROR_MESSAGE);
       }
    }

   
    private voiddrawImage() {
       int w = bufferedImage.getWidth();
       int h = bufferedImage.getHeight();
       pane.setPreferredSize(new Dimension(w, h));
       pane.setBufferedImage(bufferedImage);
       pane.showPhoto();
       scrollPane.updateUI();
    }

    publicstatic void main(String[] args) {
       new NonstandardFrame();
    }

}

 


class PhotoPanel extends JPanel {
    privateBufferedImage bufferedImage = null;
    privateBufferedImage image = null;
    privateString str = "";
    private intfontX = 10;
    private intfontY = 22;
    private Fontfont = new Font("宋体", 0, 12);
    privateColor fontColor = Color.BLACK;

    publicPhotoPanel() {
    }

   
    public voidshowPhoto(){
       repaint();
    }
   
   
    publicBufferedImage getImage() throws NullPointerException {
       image.getGraphics().dispose();
       return image;
    }
   
   
    protectedvoid paintComponent(Graphics g) {
       super.paintComponent(g);
       if (bufferedImage == null) {
           return;
       }
       image = new BufferedImage(bufferedImage.getWidth(),bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
       Graphics2D g2 = (Graphics2D) image.getGraphics();
       g2.drawImage(bufferedImage, null, 0, 0);
       g2.setColor(fontColor);
       g2.setFont(font);
       g2.drawString(str, fontX, fontY);
       Graphics2D g2d = (Graphics2D) g;
       g2d.drawImage(bufferedImage, null, 0, 0);
       g2d.setColor(fontColor);
       g2d.setFont(font);
       g2d.drawString(str, fontX, fontY);
    }

   
    public voidsetDrawString(String str, int fontX, int fontY, Font font, ColorfontColor) {
       this.str = str;
       this.fontX = fontX;
       this.fontY = fontY;
       this.font = font;
       this.fontColor = fontColor;
    }
   
    publicBufferedImage getBufferedImage() {
       return bufferedImage;
    }

    public voidsetBufferedImage(BufferedImage bufferedImage) {
       this.bufferedImage = bufferedImage;
    }

    publicString getStr() {
       return str;
    }

    public voidsetStr(String str) {
       this.str = str;
    }

    public intgetFontX() {
       return fontX;
    }

    public voidsetFontX(int fontX) {
       this.fontX = fontX;
    }

    public intgetFontY() {
       return fontY;
    }

    public voidsetFontY(int fontY) {
       this.fontY = fontY;
    }

    public FontgetFont() {
       return font;
    }

    public voidsetFont(Font font) {
       this.font = font;
    }

    public ColorgetFontColor() {
       return fontColor;
    }

    public voidsetFontColor(Color fontColor) {
       this.fontColor = fontColor;
    }

}黑马程序员java <wbr> <wbr> <wbr>图片添加水印

原创粉丝点击