Java 简易电子相册(一)

六眼飞鱼酱① 提交于 2020-08-08 12:34:29

一、前言

如图所示:
在这里插入图片描述
目前代码实现了文件夹读取,缩略图展示这两个功能,剩余功能大家看界面也能猜到了,有生之年系列吧,下次想写再说吧。

二、准备

1.win10

2.eclipse

在这里插入图片描述

3.jdk 1.8.0_221

在这里插入图片描述

4.jar

在这里插入图片描述
下载链接:https://search.maven.org/artifact/net.coobird/thumbnailator/0.4.8/jar

三、结构

在这里插入图片描述
其中日志模块还没有写。

四、代码

1、启动main

package imageView.lyrics.main;

import java.awt.EventQueue;

import imageView.lyrics.ui.ImageViewFrameUI;

public class Main {
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					new ImageViewFrameUI();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}

2、service

package imageView.lyrics.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Locale;

import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultMutableTreeNode;

import imageView.lyrics.ui.AlbumTreeUI;
import imageView.lyrics.ui.ImageUI;
import imageView.lyrics.util.ResizeImage;

public class AlbumService {
	enum ImageType{
		jpg,jpeg,png,CR2
	}
	private AlbumTreeUI albumTreeUI = AlbumTreeUI.getInstance(); 
	private ImageUI imageUI = ImageUI.getInstance();

	private String browseFolder() {
		// 拿到文件系统
		FileSystemView fsv = FileSystemView.getFileSystemView();
		// 设置过滤器
		FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("Image File","jpg","jpeg","png");
		// 修改为英文 
		JFileChooser.setDefaultLocale(Locale.US);
		// 实例化
		JFileChooser fileChooser = new JFileChooser();
		// 设置当前工作目录为桌面
		fileChooser.setCurrentDirectory(fsv.getHomeDirectory());
		// 设置标头
		fileChooser.setDialogTitle("select");
		// 设置文件选择类型
		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		// 移除所有文件过滤模式
		fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
		// 添加文件过滤
		fileChooser.setFileFilter(fileNameExtensionFilter);
		// 拿到操作结果
		int result = fileChooser.showOpenDialog(null);
		// 判断操作结果
		if(result == JFileChooser.APPROVE_OPTION) {
			// 打印所选文件路径
			return fileChooser.getSelectedFile().toString();
		}
		return null;
	}
	private void ergodicImage(String path,ArrayList<String> list) {
		DefaultMutableTreeNode parent = albumTreeUI.addAlbum(path);
		File file = new File(path);
		File[] tempList = file.listFiles();
	    for (int i = 0; i < tempList.length; i++) {
	    	String temp = tempList[i].toString();
	        if (tempList[i].isFile() && isImage(temp)) {
	        	albumTreeUI.addImage(parent, temp);
	        	String outPath = "thumbnail\\"+temp.substring(temp.lastIndexOf("\\")+1, temp.lastIndexOf("."))+"Temp.jpg";
	        	ResizeImage.generateFixedSizeImage(temp, outPath);
	        	imageUI.addImage(outPath);
	        }
	        if (tempList[i].isDirectory()) {
	        	ergodicImage(tempList[i].getAbsolutePath(),list);
	        }
	    }
	}
	private boolean isImage(String name) {
		String suffix = name.substring(name.lastIndexOf(".")+1);
		for(ImageType type:ImageType.values()) {
			if(suffix.equalsIgnoreCase(type.toString())) {
				return true;
			}
		}
		return false;
		
	}
	public boolean openFolder() {
		String path = browseFolder();
		if(path==null|| path.isEmpty()) {
			return false;
		}
		ArrayList<String> arrayList = new ArrayList<String>();
		ergodicImage(path,arrayList);
		return true;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}

3、界面

AlbumTreeUI

package imageView.lyrics.ui;

import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JScrollPane;

public class AlbumTreeUI extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private DefaultMutableTreeNode root;
	public JTree tree;
	private Map<DefaultMutableTreeNode,String> map = new HashMap<>();
	private static final AlbumTreeUI instance = new AlbumTreeUI();
	public Map<DefaultMutableTreeNode,String> getMap() {
		return map;
	}

	public static AlbumTreeUI getInstance() {
		return instance;
	}

	/**
	 * Create the panel.
	 */
	private AlbumTreeUI() {
		root = new DefaultMutableTreeNode("Album");
		DefaultTreeModel model = new DefaultTreeModel(root);
		setLayout(new BorderLayout(0, 0));
		
		JPanel panel = new JPanel();
		add(panel, BorderLayout.CENTER);
		panel.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		panel.add(scrollPane);
		panel.setPreferredSize(new Dimension(80,520));
		tree = new JTree();
		scrollPane.setViewportView(tree);
		tree.setModel(model);
	}
	public DefaultMutableTreeNode addAlbum(String path) {
		 String name = path.substring(path.lastIndexOf("\\"));
		 DefaultMutableTreeNode parent = new DefaultMutableTreeNode(name);
		 root.add(parent);
		 return parent;
	}
	public void addImage(DefaultMutableTreeNode parent, String path) {
		DefaultMutableTreeNode defaultMutableTreeNode = new DefaultMutableTreeNode(path.substring(path.lastIndexOf("\\")+1));
		getMap().put(defaultMutableTreeNode, path);
		parent.add(defaultMutableTreeNode);
	}
	public void deleteImage() {
		 DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
	     if ((selectNode == null) || (selectNode.isRoot())) {
	         return;
	     }
	     DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
	     model.removeNodeFromParent(selectNode);
	     tree.repaint();
	}
	public String openImage() {
		DefaultMutableTreeNode selectNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
	     if ((selectNode == null) || (selectNode.isRoot())) {
	         return null;
	     }
	     String path = map.get(selectNode);
	     return path;
	}

}

ImageDispalyUI

package imageView.lyrics.ui;

import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;

public class ImageDispalyUI extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public JButton btnNewButton;
	private ImageIcon imageIcon;

	/**
	 * Create the panel.
	 */
	public ImageDispalyUI(String imagePath) {
		imageIcon = new ImageIcon(imagePath);
		setSize(imageIcon.getIconWidth(),imageIcon.getIconHeight());
		setLayout(new BorderLayout(0, 0));
		btnNewButton = new JButton("");
		btnNewButton.setIcon(imageIcon);
		add(btnNewButton);
	}
	public ImageIcon getImageIcon() {
		return imageIcon;
	}

}

ImageUI

package imageView.lyrics.ui;

import java.awt.Dimension;

import javax.swing.JPanel;

public class ImageUI extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final ImageUI instance = new ImageUI();
	private int positionX = 5;
	private int positionY = 5;

	
	public static ImageUI getInstance() {
		return instance;
	}
	/**
	 * Create the panel.
	 */
	private ImageUI() {
		setLayout(null);
	}

	public void addImage(String path) {
		ImageDispalyUI imageDispalyUI = new ImageDispalyUI(path);
		int width = this.getWidth()-80;
		int height = this.getHeight()-80; 
		int imageWidth = imageDispalyUI.getWidth();
		int imageHeight = imageDispalyUI.getHeight();
		imageDispalyUI.setBounds(positionX, positionY, imageWidth,imageHeight);
		int x = imageWidth+positionX;
		int y = imageHeight+positionY;
		if(x<width && y<height) {
			positionX += imageWidth+5;
		}
		if(x>width && y<height) {
			positionX = 5;
			positionY += imageHeight+5;
		}
		if(x>width && y>height) {
			positionY += imageHeight;
			this.setPreferredSize(new Dimension(positionX,positionY));
		}
		this.add(imageDispalyUI);
		this.updateUI();
	}
}

ImageViewFrameUI

package imageView.lyrics.ui;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

import imageView.lyrics.service.AlbumService;

public class ImageViewFrameUI {

	private JFrame frame;
	private JMenuItem mntmOpenfolder;
	private AlbumService albumService = new AlbumService();
    private AlbumTreeUI albumTreeUI = AlbumTreeUI.getInstance();

	/**
	 * Create the application.
	 */
	public ImageViewFrameUI() {
		initialize();
		addListener();
		leftPanelListener();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setVisible(true);
		frame.setTitle("Image View");
		frame.setBounds(100, 100, 800, 600);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);
		
		JMenu mnFile = new JMenu("File");
		menuBar.add(mnFile);
		
		JMenuItem mntmOpenFile = new JMenuItem("open file");
		mnFile.add(mntmOpenFile);
		
		mntmOpenfolder = new JMenuItem("open folder");
		mnFile.add(mntmOpenfolder);
		
		JMenu mnEdit = new JMenu("Edit");
		menuBar.add(mnEdit);
		
		JMenuItem mntmAdd = new JMenuItem("add");
		mnEdit.add(mntmAdd);
		
		JMenuItem mntmModify = new JMenuItem("modify");
		mnEdit.add(mntmModify);
		
		JMenuItem mntmRemove = new JMenuItem("remove");
		mnEdit.add(mntmRemove);
		
		JMenu mnView = new JMenu("View");
		menuBar.add(mnView);
		
		JMenuItem mntmFind = new JMenuItem("find");
		mnView.add(mntmFind);
		
		JMenu mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);
		
		JMenuItem mntmAbout = new JMenuItem("About");
		mnHelp.add(mntmAbout);
		frame.getContentPane().setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		frame.getContentPane().add(scrollPane);
		JPanel panel = new JPanel();
		scrollPane.setViewportView(panel);
		panel.setPreferredSize(new Dimension(760,520));
		panel.setLayout(new BorderLayout(0, 0));
		
		JSplitPane splitPane = new JSplitPane();
		splitPane.setOneTouchExpandable(true);
		splitPane.setResizeWeight(0.2);
		panel.add(splitPane);
		AlbumTreeUI albumTreeUI = AlbumTreeUI.getInstance(); 
		splitPane.setLeftComponent(albumTreeUI);
		ImageUI imageUI = ImageUI.getInstance();
		splitPane.setRightComponent(imageUI);
	}
	
	private void addListener() {
		mntmOpenfolder.addActionListener(event -> {
			albumService.openFolder();
		});
		
	}
	private void leftPanelListener() {
		MouseAdapter mouseAdapter = new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				String imagePath = albumTreeUI.openImage();	
				System.out.println(imagePath);
			}
		}; 
		albumTreeUI.tree.addMouseListener(mouseAdapter);
	}
}

4.util

package imageView.lyrics.util;

import net.coobird.thumbnailator.Thumbnails;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**

 */
public class ResizeImage {
    public static void main(String[] args) {
		ResizeImage.generateFixedSizeImage("D:\\download\\毕业图片\\IMG_3303.CR2","thumbnail\\3.jpg");
    }

    /**
     * 使用给定的图片生成指定大小的图片
     */
    public static String generateFixedSizeImage(String inputPath,String outputPath){
        try {
        	InputStream inputStream = new FileInputStream(inputPath);
            Thumbnails.of(inputStream).size(80,80).toFile(outputPath);
            return outputPath;
        } catch (IOException e) {
            System.out.println("原因: " + e.getMessage());
        }
		return "";
    }
}

五、效果

初始界面
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述




六、晚安

困了困了,晚安,代码写的不好,大家多多包涵

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!