Java 头像剪切及上传服务器JSP 笔记

这篇博客介绍了如何使用Java的JFrame文件选择器选取图片,并通过拦截方法过滤非图片格式。选取图片后进行剪切操作,支持矩形和圆形两种方式,并将处理后的图片保存到服务器。代码中涉及文件路径处理、图片读取与写入,以及数据库存储文件名。文章适合Java Web开发者参考。
摘要由CSDN通过智能技术生成

头像存储真是个令人头疼的问题啊

效果:
视频没办法发,好不容易上传到B站结果这里告诉我格式错误
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  1. 主要用到Java的JFrame文件选择器,然后用拦截方法过滤掉不是图片类型的文件。
  2. 用JFrame得到文件路径之后对图片进行剪切。
  3. 剪切完之后imagewrite写入服务器文件夹。
    ps:数据库里存的是文件名。

参考博文1:文件选择器
https://blog.csdn.net/chen_z_p/article/details/82794534
参考博文2:图片剪切
https://blog.csdn.net/jameschen9051/article/details/99703207

前端指向action
在这里插入图片描述

action方法:

public boolean accept(File file){//拦截方法
 	   //文件夹必须是可选(打开)的
 	   if(file.isDirectory())  return true;
 	   //以.jpg..结尾,设置为可选
 	   else if(file.getName().endsWith(".jpg")||file.getName().endsWith(".jpeg")||file.getName().endsWith(".png")) 
 		   return true;
 	   //其它的文件类型都设置为不可选
 	   return false;
 	   }
	
	public String updateUhead() {
		int uid=(Integer) session.getAttribute("uid");
		// 创建一个JFrame组件为parent组件
    	JFrame frame = new JFrame();
    	//窗体前置
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setAlwaysOnTop(true); 
        // 创建一个默认打开用户文件夹的文件选择器
    	JFileChooser chooser = new JFileChooser();
    	FileSystemView fsv = FileSystemView.getFileSystemView();  //桌面路径
		chooser.setCurrentDirectory(fsv.getHomeDirectory());
    	int flag = chooser.showOpenDialog(frame);
    	if (flag == JFileChooser.APPROVE_OPTION&&accept(chooser.getSelectedFile())) {
    		String filePath=chooser.getSelectedFile().getAbsolutePath();
    		UheadUpload uheadUpload=new UheadUpload();
    		String upName=uheadUpload.headUpload(filePath,uid);
    		ub.updateUhead(upName,uid);
    	}else {
    		JOptionPane.showMessageDialog(null, "无效的头像上传");
    		//System.out.println("头像上传失败,可能是格式不对(jpg、jpeg、png)");
    	}
		return SUCCESS;
	}

其中调用的UheadUpload类:

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

public class UheadUpload {
	
	public UheadUpload(){ }
	
	//剪切矩形头像
	public BufferedImage imageCutByRectangle(BufferedImage image) {
		//判断x、y方向是否超过图像最大范围
		int xCoordinate = image.getWidth();
		int yCoordinate = image.getHeight();
		int a=xCoordinate;
		if (xCoordinate > yCoordinate) {
			a = yCoordinate;
		}
		BufferedImage resultImage = new BufferedImage(a, a, image.getType());
		for (int x = 0; x < a; x++) {
			for (int y = 0; y < a; y++) {
				int rgb = image.getRGB(x, y);
				resultImage.setRGB(x, y, rgb);
			}
		}
		return resultImage;
	}
	//剪切圆形头像
	public BufferedImage cutImageCircle(BufferedImage image){
		// 判断圆心左右半径是否超限
		int xCoordinate = image.getWidth() / 2 - 1;
		int yCoordinate = image.getHeight() / 2 - 1;
		int radius = xCoordinate;
		if (xCoordinate > yCoordinate) {
			radius = yCoordinate;
		}
		int length = 2 * radius + 1;
		BufferedImage resultImage = new BufferedImage(length, length,
				image.getType());
		for (int i = 0; i < length; i++) {
			for (int j = 0; j < length; j++) {
				int x = i - radius;
				int y = j - radius;
				int distance = (int) Math.sqrt(x * x + y * y);
				if (distance <= radius) {
					int rgb = image.getRGB(x + xCoordinate, y + yCoordinate);
					resultImage.setRGB(i, j, rgb);
				}
			}
		}
		return resultImage;
	}
	
	public String headUpload(String filePath,int notRandomId){
		filePath = filePath.replace(File.separatorChar,'/');
		
		// 获取web服务器工作路径
		String realPath = ServletActionContext.getServletContext().getRealPath("/");
		realPath = realPath.replace(File.separatorChar,'/');

		// 获取当前时间
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		//当前时间格式化
		String currntTime = sdf.format(date);
		//设置新的文件名   用户ID+当前时间
		String imageName = notRandomId + currntTime;
		String newName = imageName + filePath.substring(filePath.lastIndexOf("."));
		//System.out.println(realPath);
		String path1="C:/Users/Catwang.DESKTOP-LAVTUUH/Desktop/Catwang/Course/Web框架开发/201750545管惠亭/firstly1_3/WebRoot";
		File fileWeb=new File(path1+"/userHead/"+newName);
		File fileWeb1=new File(realPath+"/userHead/"+newName);
		File fileWebRe=new File(path1+"/userHead/re"+newName);
		File fileWebRe1=new File(realPath+"/userHead/re"+newName);
		//获取选择的文件		
		File file=new File(filePath);
		//System.out.println(filePath);
		try {
			BufferedImage image = ImageIO.read(file);
			BufferedImage CircleResult = cutImageCircle(image);
			BufferedImage RectangleResult = imageCutByRectangle(image);
			ImageIO.write(CircleResult,"png", fileWeb);
			ImageIO.write(CircleResult,"png", fileWeb1);
			ImageIO.write(RectangleResult,"png", fileWebRe);
			ImageIO.write(RectangleResult,"png", fileWebRe1);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return newName;
	}
}

代码这么多大家可能都醉了,其实只要理解了就觉得没什么了,前年做的时候我还觉得这是什么乱七八糟的玩意儿,现在就是不过如此而已
加油~

附上今天的沙皮笔记
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悢七

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值