@Override
 public InputStream getAvatar(String userName) {
   GridFS avatarFS = new GridFS(m_template.getDb());
   GridFSDBFile imageForOutput = avatarFS.findOne(String.format(AVATAR_NAME, userName));
   if (imageForOutput != null) {
     return imageForOutput.getInputStream();
   }
   // try default avatar
   imageForOutput = avatarFS.findOne(String.format(AVATAR_NAME, "default"));
   if (imageForOutput != null) {
     return imageForOutput.getInputStream();
   }
   return null;
 }
예제 #2
0
 @Override
 public ByteArrayFileCache getBlob(final MD5 md5, final ByteArrayFileCacheManager bafcMan)
     throws NoSuchBlobException, BlobStoreCommunicationException, FileCacheIOException,
         FileCacheLimitExceededException {
   final GridFSDBFile out;
   try {
     out = getFile(md5);
     if (out == null) {
       throw new NoSuchBlobException(
           "Attempt to retrieve non-existant blob with chksum " + md5.getMD5());
     }
     final boolean sorted;
     if (!out.containsField(Fields.GFS_SORTED)) {
       sorted = false;
     } else {
       sorted = (Boolean) out.get(Fields.GFS_SORTED);
     }
     final InputStream file = out.getInputStream();
     try {
       return bafcMan.createBAFC(file, true, sorted);
     } finally {
       try {
         file.close();
       } catch (IOException ioe) {
         throw new RuntimeException("Something is broken", ioe);
       }
     }
   } catch (MongoException me) {
     throw new BlobStoreCommunicationException("Could not read from the mongo database", me);
   }
 }
예제 #3
0
파일: Books.java 프로젝트: Jsalim/mekong2
 /**
  * Queries GridFS for the cover image binary and sends it to the user.
  *
  * @param isbn Match against the aliases of all files in the GridFS store.
  * @return Matched file, or nothing if not found.
  */
 public static Result cover(String isbn) {
   GridFSDBFile cover = Book.findCoverByISBN(isbn);
   response().setContentType("image/gif");
   if (null != cover) {
     return ok(cover.getInputStream());
   } else {
     return notFound();
   }
 }
  /**
   * 生成随机默认头像,如果存在原图,则查询各个尺寸头像,对不存在的头像重新用原图生成
   *
   * @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);
    }
  }
예제 #5
0
 private void writeResponse(GridFSDBFile file, HttpServletResponse response) throws IOException {
   if (file != null) {
     byte[] data = IOUtils.toByteArray(file.getInputStream());
     response.setContentType(file.getContentType());
     response.setContentLength((int) file.getLength());
     response.getOutputStream().write(data);
     response.getOutputStream().flush();
   } else {
     response.setStatus(HttpStatus.NOT_FOUND.value());
   }
 }
예제 #6
0
 @GET
 @Path("/{id}")
 public javax.ws.rs.core.Response getAttachment(@PathParam("id") final String id)
     throws IOException {
   final DB db = this.client.getDB("grid");
   final GridFS gridFS = new GridFS(db);
   final GridFSDBFile file = gridFS.findOne(id);
   // log.info(file);
   if (file == null) {
     throw new WebApplicationException(404);
   }
   return Response.ok(
           org.apache.commons.io.IOUtils.toByteArray(file.getInputStream()), file.getContentType())
       .build();
 }
예제 #7
0
 @GET
 @Path("{objectid}")
 public Response getImage(
     @PathParam("objectid") String objectId, @HeaderParam("If-Modified-Since") String modified) {
   GridFSDBFile mongoFile = imageRepository.getImage(objectId);
   if (mongoFile != null) {
     if (modified != null) {
       if (new Date(modified).before(mongoFile.getUploadDate())) {
         return Response.status(Status.NOT_MODIFIED).build();
       }
     }
     return Response.ok(mongoFile.getInputStream(), mongoFile.getContentType())
         .lastModified(mongoFile.getUploadDate())
         .build();
   }
   return Response.status(Status.NOT_FOUND).build();
 }
예제 #8
0
  @RequestMapping(value = "/getPhoto/{code}", method = RequestMethod.GET)
  public @ResponseBody ResponseEntity<byte[]> getCodableDTO(@PathVariable("code") String code) {

    System.out.println("finding getCodableDTO: code: " + code);

    try {

      // List<GridFSDBFile> result = gridFsTemplate.find(new
      // Query().addCriteria(Criteria.where("filename").is(code)));
      GridFSDBFile gridFsFile =
          gridFsTemplate.findOne(new Query().addCriteria(Criteria.where("_id").is(code)));

      final HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.IMAGE_JPEG);
      return new ResponseEntity<>(
          IOUtils.toByteArray(gridFsFile.getInputStream()), headers, HttpStatus.CREATED);

    } catch (Exception e) {
      System.out.println("eeeeeeeey get photo " + e);
      return null;
    }
  }