/** * 生成随机默认头像,如果存在原图,则查询各个尺寸头像,对不存在的头像重新用原图生成 * * @param userId * @param userName * @return */ public void avatarGenerate(String userId, String userName) { // 获取缩略名字 userName = DefaultAvatarGeneratorService.obatainName(userName); // 判断是否有初始头像,如果有用初始头像切割小头像,然后组装 // 如果没有则随机选择一个初始头像,添加姓名水印后切割小头像,其实是一种容错机制 GridFSDBFile intinalAvatarFile = imageStoreService.get(AvatarIdGenerator.obtainMobileLargeAvatarId(userId)); // 要裁剪的尺寸 List<Double> thumbnailSizeList = SnapFileConfigUtils.obtainAvatarScaleSizes(); int number = 0; BufferedImage bimage = null; if (intinalAvatarFile == null) { Random random = new Random(); number = random.nextInt(DefaultAvatarCacheService.DEFAULT_AVATAR_NUMBER); number++; bimage = DefaultAvatarCacheService.obtainCacheRandomAvatar(number); // 如果姓名不为空,加水印随机图片 if (!StringUtils.isEmpty(userName)) { drawName(bimage, userName); } } else { try { bimage = ImageIO.read(intinalAvatarFile.getInputStream()); thumbnailSizeList = this.obtainThumbnailSizeList(userId); } catch (IOException e) { e.printStackTrace(); } } int width = bimage.getWidth(); int height = bimage.getHeight(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); ImageOutputStream imOut; try { imOut = ImageIO.createImageOutputStream(bs); ImageIO.write(bimage, "png", imOut); // 存储原图到数据库 imageService.uploadTempLogo(new ByteArrayInputStream(bs.toByteArray()), userId); } catch (IOException e) { Logger.error("上传随机头像出错", e); e.printStackTrace(); } if (!thumbnailSizeList.isEmpty()) { // 生成切割小图片,存入数据库 imageService.rectAndStoreAvatar( userId, 0, 0, width, height, thumbnailSizeList, AvatarIdGenerator.USER_TYPE); } }
/** * 判断是否需要生成默认头像, 用于判断组装的小头像是否存在,如果存在直接返回 * * @param userId * @return */ public boolean needGenerateDefaultAvatar(String userId) { GridFSDBFile tinyAvatar = imageStoreService.get(AvatarIdGenerator.obtainBigTinyAvatarId(userId)); if (tinyAvatar != null) { return false; } else { return true; } }
/** * 获取不存在的头像尺寸 * * @param userId * @return */ private List<Double> obtainThumbnailSizeList(String userId) { List<Double> list = new ArrayList<Double>(); GridFSDBFile intinalAvatarFile = null; for (Double size : SnapFileConfigUtils.obtainAvatarScaleSizes()) { intinalAvatarFile = imageStoreService.get(AvatarIdGenerator.genegratorUserAvatarId(userId, size)); if (intinalAvatarFile == null) { list.add(size); } } return list; }