/** * 上传头像 * * @throws Exception */ @SuppressWarnings("deprecation") @RequestMapping("uploadImage") public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws Exception { Properties props = System.getProperties(); // 系统属性 // System.out.println("操作系统的名称:"+props.getProperty("os.name")); String separator = "/"; if (props.getProperty("os.name").startsWith("Windows")) { separator = "\\"; } PrintWriter out = response.getWriter(); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); try { MultipartFile file = ((DefaultMultipartHttpServletRequest) request) .getFile("photo"); CommonsMultipartFile tmpFile = (CommonsMultipartFile) file; ImageRename imageRename = new ImageRename(); String rename = imageRename.rename(tmpFile); InputStream iis = file.getInputStream(); BufferedImage bi = ImageIO.read(iis); // 重新设定图片的尺寸 double width = bi.getWidth(); double height = bi.getHeight(); int newWidth = 135; int newHeight =(int) ((height * 135) / width);; BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR); Graphics graphics = image.createGraphics(); graphics.drawImage(bi, 0, 0, newWidth, newHeight, null); String realPath=request.getRealPath("/"); String saveDirectory = realPath.substring(0,realPath.lastIndexOf("root")) + "/images" + "/headImage/"; // 上传到项目根目录/images/headImage文件夹下 File fdirect = new File(saveDirectory); if (!fdirect.exists()) { fdirect.mkdirs(); } DataOutputStream outt = new DataOutputStream(new FileOutputStream( saveDirectory + rename));// 存放文件的绝对路径 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outt); JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(image); jep.setQuality(10000f, true); encoder.encode(image, jep); // ImageIO.write(image, "jpg", outt);这是第二种图片写入方法 // 返回文件路径 File filePath = new File(saveDirectory + rename); String ip=""; try { InetAddress addr = InetAddress.getLocalHost(); ip=addr.getHostAddress().toString(); } catch (Exception e) { } String returnPath = filePath.toString().substring( filePath.toString().lastIndexOf("images") - 1) .replace("\\", "/"); String fileName="http://"+ip+":"+request.getLocalPort()+returnPath; out.write("{success:true,returnPath:'" + fileName + "'}"); out.flush(); out.close(); outt.close(); iis.close(); } catch (Exception e) { System.out.println(e.getMessage()); out.write("{success:false}"); out.flush(); out.close(); e.printStackTrace(); } }
java上传图片设置宽高_java上传图片并重新设定图片尺寸...
最新推荐文章于 2022-05-27 09:55:31 发布