public File downloadImageAndResize(int thumbnailSize) {
    if (this.type != Type.image) {
      log.warn("Cannot download non-images!");
      return null;
    }
    HttpGet get = null;
    HttpResponse getResponse = null;
    try {
      File f = File.createTempFile(this.getClass().getSimpleName() + "-", ".image");
      get = new HttpGet(imageUrl);
      getResponse = httpClient.execute(get);
      getResponse.getEntity().writeTo(new FileOutputStream(f));

      BufferedImage org = ImageIO.read(f);
      ResampleOp resampleOp = new ResampleOp(thumbnailSize, thumbnailSize);
      BufferedImage scaled = resampleOp.filter(org, null);

      File imageFile = File.createTempFile(this.getClass().getSimpleName() + "-", ".png");
      ImageIO.write(scaled, "png", imageFile);
      f.delete();

      return imageFile;
    } catch (Exception e) {
      log.warn(this + ": Unable to download file", e);
      hadErrors = true;
      if (get != null) {
        get.abort();
      }
      if (getResponse != null) {
        try {
          EntityUtils.consume(getResponse.getEntity());
        } catch (IOException e1) {
          log.debug("Failed to clean up", e1);
        }
      }
    }
    return null;
  }
Example #2
0
 private void width(String path, Integer imgWidth) {
   try {
     BufferedImage imageResize = ImageIO.read(new File(path));
     int width = imageResize.getWidth();
     int height = imageResize.getHeight();
     float ratio = (float) width / (float) height;
     if (width > imgWidth) {
       width = imgWidth;
       height = (int) (imgWidth / ratio);
     }
     ResampleOp reOp = new ResampleOp(width, height);
     BufferedImage newImg = reOp.filter(imageResize, null);
     File file = new File(path);
     String parentPath = file.getParent();
     String name = file.getName();
     // 判断整数
     if (name.substring(0, name.indexOf(".")).matches("[\\d]+")) {
       ImageIO.write(newImg, "JPEG", new File(parentPath + "/" + imgWidth + "_" + name));
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }