- 创建页面
窗体 按钮 字体
public void showUI(){JFrame jf = new JFrame("图像处理");jf.setSize(1700,1200);jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);jf.setLayout(new FlowLayout());Font font =new Font("楷体",Font .BOLD,16);for (int i = 0; i < strs.length; i++) {JButton btn =new JButton(strs[i]);btn .setBackground(Color.lightGray);btn .setFont(font );jf.add(btn);jf.setVisible(true);public static void main(String[] args) {ImagePad imagePad=new ImagePad();imagePad.showUI();
- 创建监听器
Switch case语句进行选择
public class ImageListener implements ActionListener {@Overridepublic void actionPerformed(ActionEvent e) {String btnstr =e.getActionCommand();System.out.println("点击了:"+btnstr);switch (btnstr){case"原图":System.out.println("原图");break;case"灰度":break;case"二值化":break;case"马赛克":break;}}
}
将监听器与窗体按钮创建关联
ImageListener imageListener=new ImageListener();btn.addActionListener(imageListener);
- 创建imagetools
将图片的宽高创建二维数组
public class ImageTools {int x=100;int y=100;public int [][] getImagePiexArry(String path){File file=new File(path);BufferedImage bufferedImage=null;try {bufferedImage= ImageIO.read(file);} catch (IOException e) {throw new RuntimeException(e);}int width=bufferedImage.getWidth();int heigth=bufferedImage.getHeight();int[][] imArr=new int[width][heigth];System.out.println(imArr.length);System.out.println(imArr[0].length);for (int i = 0; i < imArr.length; i++) {for (int j = 0; j < imArr[i].length; j++) {imArr[i][j]=bufferedImage.getRGB(i,j);}}return imArr;}
循环遍历/原图/灰度/二值化
public void drawImage(int [][] imgArr,Graphics g){for (int i = 0; i < imgArr.length; i++) {for (int j = 0; j < imgArr[i].length; j++) {int pixnum=imgArr[i][j];Color color =new Color(pixnum);g.setColor(color );g.fillRect(x+i,y+j,1,1);}}}public void drawGrayImage(int [][] imgArr,Graphics g){for (int i = 0; i < imgArr.length; i++) {for (int j = 0; j < imgArr[i].length; j++) {int pixnum=imgArr[i][j];int red=(pixnum>>16)&225;int green=(pixnum>>8)&225;int blue=(pixnum>>0)&225;int gray=(red+green+blue)/3;Color color =new Color(gray,gray,gray);g.setColor(color );g.fillRect(x+i,y+j,1,1);}}}public void drawBinaryImage(int [][]imArr,Graphics g){for (int i = 0; i < imArr.length; i++) {for (int j = 0; j < imArr[i].length; j++) {int pixnum=imArr[i][j];int red=(pixnum>>16)&225;int green=(pixnum>>8)&225;int blue=(pixnum>>0)&225;int gray=(red+green+blue)/3;if (gray<112) {g.setColor(Color.white);}else {g.setColor(Color.black);}g.fillRect(x+i,y+j,1,1);}}}
在监听器中创建imagetools
ImageTools imagetools=new ImageTools();
- 在监听器中创建画笔和窗口连接
Graphics g;
imageListener.g=jf.getGraphics();
- 在监听器中引入图片的路径
int[][]imageArr;{String path="C:\\Users\\13517\\Desktop\\编2\\图1.png";imageArr=imagetools.getImagePiexArry(path);}