コード例 #1
0
ファイル: ImageTools.java プロジェクト: qiaohe/repaymentApp
 /**
  * 根据尺寸缩放图片
  *
  * @param width 缩放后的图片宽度
  * @param height 缩放后的图片高度
  * @param srcPath 源图片路径
  * @param newPath 缩放后图片的路径
  */
 public static void resizeImage(String srcPath, String newPath, int width, int height)
     throws InterruptedException, IOException, IM4JavaException {
   IMOperation op = new IMOperation();
   op.addImage(srcPath);
   op.resize(width, height);
   op.addImage(newPath);
   // linux下不要设置此值,不然会报错
   if (isWin) {
     convertCmd.setSearchPath(imageMagickPath);
   }
   convertCmd.run(op);
 }
コード例 #2
0
ファイル: ImageTools.java プロジェクト: qiaohe/repaymentApp
 /**
  * 根据尺寸缩放图片
  *
  * @param angle 旋转过图片的角度
  * @param srcPath 源图片路径
  * @param newPath 缩放后图片的路径
  */
 public static void rotateImage(String srcPath, String newPath, Double angle)
     throws InterruptedException, IOException, IM4JavaException {
   IMOperation op = new IMOperation();
   op.addImage(srcPath);
   op.rotate(angle);
   op.addImage(newPath);
   // linux下不要设置此值,不然会报错
   if (isWin) {
     convertCmd.setSearchPath(imageMagickPath);
   }
   convertCmd.run(op);
 }
コード例 #3
0
ファイル: ImageTools.java プロジェクト: qiaohe/repaymentApp
 /**
  * 给图片加水印
  *
  * @param srcPath 源图片路径
  */
 public static void addImgText(String srcPath)
     throws InterruptedException, IOException, IM4JavaException {
   IMOperation op = new IMOperation();
   op.font("宋体").gravity("southeast").pointsize(18).fill("#BCBFC8").draw("text 5,5 juziku.com");
   op.addImage();
   op.addImage();
   // linux下不要设置此值,不然会报错
   if (isWin) {
     convertCmd.setSearchPath(imageMagickPath);
   }
   convertCmd.run(op, srcPath, srcPath);
 }
コード例 #4
0
ファイル: ImageTools.java プロジェクト: qiaohe/repaymentApp
 /**
  * 根据坐标裁剪图片
  *
  * @param srcPath 要裁剪图片的路径
  * @param newPath 裁剪图片后的路径
  * @param x 起始横坐标
  * @param y 起始挫坐标
  * @param x1 结束横坐标
  * @param y1 结束挫坐标
  */
 public static void cropImage(String srcPath, String newPath, int x, int y, int x1, int y1)
     throws InterruptedException, IOException, IM4JavaException {
   int width = x1 - x;
   int height = y1 - y;
   IMOperation op = new IMOperation();
   op.addImage(srcPath);
   /** width:裁剪的宽度 height:裁剪的高度 x:裁剪的横坐标 y:裁剪的挫坐标 */
   op.crop(width, height, x, y);
   op.addImage(newPath);
   if (isWin) {
     convertCmd.setSearchPath(imageMagickPath);
   }
   convertCmd.run(op);
 }
コード例 #5
0
ファイル: ImageUtil.java プロジェクト: 354447958/fuc
 /**
  * 等比例图片缩放.
  *
  * @param srcFile 源文件
  * @param destFile 目标文件
  * @param destWidth 目标宽度(>0)
  * @param destHeight 目标高度(>0)
  */
 public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
   if (type == Type.jdk) {
     try {
       BufferedImage srcBufferedImage = ImageIO.read(srcFile);
       int srcWidth = srcBufferedImage.getWidth();
       int srcHeight = srcBufferedImage.getHeight();
       int width = destWidth;
       int height = destHeight;
       if (srcHeight >= srcWidth) {
         width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
       } else {
         height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
       }
       BufferedImage destBufferedImage =
           new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
       Graphics2D graphics2D = destBufferedImage.createGraphics();
       graphics2D.setBackground(BACKGROUND_COLOR);
       graphics2D.clearRect(0, 0, destWidth, destHeight);
       graphics2D.drawImage(
           srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
           (destWidth / 2) - (width / 2),
           (destHeight / 2) - (height / 2),
           null);
       graphics2D.dispose();
       ImageIO.write(destBufferedImage, FileUtil.getExtension(destFile), destFile);
     } catch (IOException e) {
       throw new RuntimeException(e);
     }
   } else {
     IMOperation operation = new IMOperation();
     operation.thumbnail(destWidth, destHeight);
     operation.gravity("center");
     operation.background(toHexEncoding(BACKGROUND_COLOR));
     operation.extent(destWidth, destHeight);
     operation.quality((double) DEST_QUALITY);
     operation.addImage(srcFile.getPath());
     operation.addImage(destFile.getPath());
     if (type == Type.graphicsMagick) {
       ConvertCmd convertCmd = new ConvertCmd(true);
       if (graphicsMagickPath != null) {
         convertCmd.setSearchPath(graphicsMagickPath);
       }
       try {
         convertCmd.run(operation);
       } catch (IOException | InterruptedException | IM4JavaException e) {
         throw new RuntimeException(e);
       }
     } else {
       ConvertCmd convertCmd = new ConvertCmd(false);
       if (imageMagickPath != null) {
         convertCmd.setSearchPath(imageMagickPath);
       }
       try {
         convertCmd.run(operation);
       } catch (IOException | InterruptedException | IM4JavaException e) {
         throw new RuntimeException(e);
       }
     }
   }
 }
コード例 #6
0
ファイル: Convert.java プロジェクト: Jijun/incubator
  public static void main(String[] args) {
    IMOperation op = new IMOperation();
    op.addImage();
    op.addImage();

    ConvertCmd convert = new ConvertCmd();

    try {
      convert.createScript("convert.sh", op);
      convert.run(op, (Object[]) args);
    } catch (CommandException ce) {
      ce.printStackTrace();
      ArrayList<String> cmdError = ce.getErrorText();
      for (String line : cmdError) {
        System.err.println(line);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #7
0
  public static BufferedImage ConvertPageToImage(File afile, int i)
      throws IOException, InterruptedException, IM4JavaException {

    IMOperation op = new IMOperation();
    op.addImage(afile.getAbsolutePath() + "[" + i + "]"); // look at myscript.sh
    op.colorspace("RGB");
    op.resize(640, 830);
    op.type("TrueColor");
    op.addImage("jpg:-"); // place holder for output file

    // op.alpha("off"); //this command is slow and not needed anymore
    //  op.interpolate("spline");
    //  op.colorspace("RGB");
    ConvertCmd convert = new ConvertCmd();
    //		  convert.setSearchPath("/usr/local/Cellar/imagemagick/6.7.7-6/bin/convert");
    //		  convert.setSearchPath("/usr/bin/convert");
    //		  convert.setSearchPath("/Volumes/Main
    // Drive/Users/angellopozo/ImageMagick-6.7.8/bin/convert");
    //		  convert.setSearchPath("Users/angellopozo/ImageMagick-6.7.8/bin/convert");
    //		  convert.setSearchPath("/usr/local/bin");
    Stream2BufferedImage s2b = new Stream2BufferedImage();
    convert.setOutputConsumer(s2b);
    convert.run(op);
    //		  convert.createScript("myscript.sh",op);//debug`` line
    BufferedImage aPDF_img = s2b.getImage(); // PDF_img is the pdf_image
    ImageIO.write(
        aPDF_img,
        "jpeg",
        new File("Page_" + (i + 1) + "of_PDF.jpg")); // write whole pdf page to png
    return aPDF_img;
  } // end of ConvertPagetoImage
コード例 #8
0
  public RenderedImage convertCMYKtoRGB(byte[] bytes, String type, boolean fork) {

    ImageMagick imageMagick = getImageMagick();

    if (!imageMagick.isEnabled()) {
      return null;
    }

    File inputFile = _fileUtil.createTempFile(type);
    File outputFile = _fileUtil.createTempFile(type);

    try {
      _fileUtil.write(inputFile, bytes);

      IMOperation imOperation = new IMOperation();

      imOperation.addRawArgs("-format", "%[colorspace]");
      imOperation.addImage(inputFile.getPath());

      String[] output = imageMagick.identify(imOperation.getCmdArgs(), fork);

      if ((output.length == 1) && output[0].equalsIgnoreCase("CMYK")) {
        if (_log.isInfoEnabled()) {
          _log.info("The image is in the CMYK colorspace");
        }

        imOperation = new IMOperation();

        imOperation.addRawArgs("-colorspace", "RGB");
        imOperation.addImage(inputFile.getPath());
        imOperation.addImage(outputFile.getPath());

        imageMagick.convert(imOperation.getCmdArgs(), fork);

        bytes = _fileUtil.getBytes(outputFile);

        return read(bytes, type);
      }
    } catch (Exception e) {
      if (_log.isErrorEnabled()) {
        _log.error(e, e);
      }
    } finally {
      _fileUtil.delete(inputFile);
      _fileUtil.delete(outputFile);
    }

    return null;
  }
コード例 #9
0
  /**
   * @param inputPath Absolute filename pathname or "-" to use a stream
   * @param inputStream Can be null
   * @param params
   * @param sourceFormat
   * @param fullSize
   * @param outputStream Stream to write to
   * @throws ProcessorException
   */
  private void doProcess(
      String inputPath,
      InputStream inputStream,
      Parameters params,
      SourceFormat sourceFormat,
      Dimension fullSize,
      OutputStream outputStream)
      throws ProcessorException {
    final Set<OutputFormat> availableOutputFormats = getAvailableOutputFormats(sourceFormat);
    if (getAvailableOutputFormats(sourceFormat).size() < 1) {
      throw new UnsupportedSourceFormatException(sourceFormat);
    } else if (!availableOutputFormats.contains(params.getOutputFormat())) {
      throw new UnsupportedOutputFormatException();
    }

    try {
      IMOperation op = new IMOperation();
      op.addImage(inputPath);
      assembleOperation(op, params, fullSize);

      op.addImage(params.getOutputFormat().getExtension() + ":-"); // write to stdout

      ConvertCmd convert = new ConvertCmd(true);

      String binaryPath =
          Application.getConfiguration().getString("GraphicsMagickProcessor.path_to_binaries", "");
      if (binaryPath.length() > 0) {
        convert.setSearchPath(binaryPath);
      }
      if (inputStream != null) {
        convert.setInputProvider(new Pipe(inputStream, null));
      }
      convert.setOutputConsumer(new Pipe(null, outputStream));
      convert.run(op);
    } catch (InterruptedException | IM4JavaException | IOException e) {
      throw new ProcessorException(e.getMessage(), e);
    }
  }
コード例 #10
0
  /**
   * 根据尺寸缩放图片[等比例缩放:参数height为null,按宽度缩放比例缩放;参数width为null,按高度缩放比例缩放]
   *
   * @param imagePath 源图片路径
   * @param newPath 处理后图片路径
   * @param width 缩放后的图片宽度
   * @param height 缩放后的图片高度
   * @return 返回true说明缩放成功,否则失败
   */
  public static boolean zoomImage(
      String imagePath, String newPath, Integer width, Integer height, String quality) {
    boolean flag = false;
    try {
      IMOperation op = new IMOperation();
      op.addImage(imagePath);
      if (width == null) { // 根据高度缩放图片
        op.resize(null, height);
      } else if (height == null) { // 根据宽度缩放图片
        op.resize(width, null);
      } else {
        op.resize(width, height);
      }
      op.addImage(newPath);
      if ((quality != null && quality.equals(""))) {
        op.addRawArgs("-quality", quality);
      }
      ConvertCmd convert = new ConvertCmd(true);
      if (OS_NAME.indexOf("win") >= 0) {
        // linux下不要设置此值,不然会报错
        String path = getGraphicsMagickPath();
        if (StringUtils.isNotBlank(path)) convert.setSearchPath(path);
      }
      convert.run(op);
      flag = true;
    } catch (IOException e) {
      flag = false;
      e.printStackTrace();
    } catch (InterruptedException e) {
      flag = false;
      e.printStackTrace();
    } catch (IM4JavaException e) {
      flag = false;
      e.printStackTrace();
    } finally {

    }
    return flag;
  }
コード例 #11
0
ファイル: ImageUtils.java プロジェクト: treejames/shop-2
  static {
    if (graphicsMagickPath == null) {
      String osName = System.getProperty("os.name").toLowerCase();
      if (osName.indexOf("windows") >= 0) {
        String pathVariable = System.getenv("Path");
        if (pathVariable != null) {
          String[] paths = pathVariable.split(";");
          for (String path : paths) {
            File gmFile = new File(path.trim() + "/gm.exe");
            File gmdisplayFile = new File(path.trim() + "/gmdisplay.exe");
            if (gmFile.exists() && gmdisplayFile.exists()) {
              graphicsMagickPath = path.trim();
              break;
            }
          }
        }
      }
    }

    if (imageMagickPath == null) {
      String osName = System.getProperty("os.name").toLowerCase();
      if (osName.indexOf("windows") >= 0) {
        String pathVariable = System.getenv("Path");
        if (pathVariable != null) {
          String[] paths = pathVariable.split(";");
          for (String path : paths) {
            File convertFile = new File(path.trim() + "/convert.exe");
            File compositeFile = new File(path.trim() + "/composite.exe");
            if (convertFile.exists() && compositeFile.exists()) {
              imageMagickPath = path.trim();
              break;
            }
          }
        }
      }
    }

    if (type == Type.auto) {
      try {
        IMOperation operation = new IMOperation();
        operation.version();
        IdentifyCmd identifyCmd = new IdentifyCmd(true);
        if (graphicsMagickPath != null) {
          identifyCmd.setSearchPath(graphicsMagickPath);
        }
        identifyCmd.run(operation);
        type = Type.graphicsMagick;
      } catch (Throwable e1) {
        try {
          IMOperation operation = new IMOperation();
          operation.version();
          IdentifyCmd identifyCmd = new IdentifyCmd(false);
          identifyCmd.run(operation);
          if (imageMagickPath != null) {
            identifyCmd.setSearchPath(imageMagickPath);
          }
          type = Type.imageMagick;
        } catch (Throwable e2) {
          type = Type.jdk;
        }
      }
    }
  }
コード例 #12
0
ファイル: ImageUtils.java プロジェクト: treejames/shop-2
  public static void addWatermark(File srcFile, File destFile, File watermarkFile, int alpha) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(alpha >= 0);
    Assert.state(alpha <= 100);
    if (watermarkFile == null || !watermarkFile.exists()) {
      try {
        FileUtils.copyFile(srcFile, destFile);
      } catch (IOException e) {
        e.printStackTrace();
      }
      return;
    }
    if (type == Type.jdk) {
      Graphics2D graphics2D = null;
      ImageOutputStream imageOutputStream = null;
      ImageWriter imageWriter = null;
      try {
        BufferedImage srcBufferedImage = ImageIO.read(srcFile);
        int srcWidth = srcBufferedImage.getWidth();
        int srcHeight = srcBufferedImage.getHeight();
        BufferedImage destBufferedImage =
            new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
        graphics2D = destBufferedImage.createGraphics();
        graphics2D.setBackground(BACKGROUND_COLOR);
        graphics2D.clearRect(0, 0, srcWidth, srcHeight);
        graphics2D.drawImage(srcBufferedImage, 0, 0, null);
        graphics2D.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100F));

        BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
        int watermarkImageWidth = watermarkBufferedImage.getWidth();
        int watermarkImageHeight = watermarkBufferedImage.getHeight();
        int x = srcWidth - watermarkImageWidth;
        int y = srcHeight - watermarkImageHeight;

        graphics2D.drawImage(
            watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);

        imageOutputStream = ImageIO.createImageOutputStream(destFile);
        imageWriter =
            ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                .next();
        imageWriter.setOutput(imageOutputStream);
        ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        imageWriteParam.setCompressionQuality(DEST_QUALITY / 100F);
        imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
        imageOutputStream.flush();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (graphics2D != null) {
          graphics2D.dispose();
        }
        if (imageWriter != null) {
          imageWriter.dispose();
        }
        if (imageOutputStream != null) {
          try {
            imageOutputStream.close();
          } catch (IOException e) {
          }
        }
      }
    } else {
      IMOperation operation = new IMOperation();
      operation.dissolve(alpha);
      operation.quality((double) DEST_QUALITY);
      operation.addImage(watermarkFile.getPath());
      operation.addImage(srcFile.getPath());
      operation.addImage(destFile.getPath());
      if (type == Type.graphicsMagick) {
        CompositeCmd compositeCmd = new CompositeCmd(true);
        if (graphicsMagickPath != null) {
          compositeCmd.setSearchPath(graphicsMagickPath);
        }
        try {
          compositeCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      } else {
        CompositeCmd compositeCmd = new CompositeCmd(false);
        if (imageMagickPath != null) {
          compositeCmd.setSearchPath(imageMagickPath);
        }
        try {
          compositeCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #13
0
ファイル: ImageUtils.java プロジェクト: treejames/shop-2
  public static void zoom(File srcFile, File destFile, int destWidth, int destHeight) {
    Assert.notNull(srcFile);
    Assert.notNull(destFile);
    Assert.state(destWidth > 0);
    Assert.state(destHeight > 0);
    if (type == Type.jdk) {
      Graphics2D graphics2D = null;
      ImageOutputStream imageOutputStream = null;
      ImageWriter imageWriter = null;
      try {
        BufferedImage srcBufferedImage = ImageIO.read(srcFile);
        int srcWidth = srcBufferedImage.getWidth();
        int srcHeight = srcBufferedImage.getHeight();
        int width = destWidth;
        int height = destHeight;
        if (srcHeight >= srcWidth) {
          width = (int) Math.round(((destHeight * 1.0 / srcHeight) * srcWidth));
        } else {
          height = (int) Math.round(((destWidth * 1.0 / srcWidth) * srcHeight));
        }
        BufferedImage destBufferedImage =
            new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
        graphics2D = destBufferedImage.createGraphics();
        graphics2D.setBackground(BACKGROUND_COLOR);
        graphics2D.clearRect(0, 0, destWidth, destHeight);
        graphics2D.drawImage(
            srcBufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH),
            (destWidth / 2) - (width / 2),
            (destHeight / 2) - (height / 2),
            null);

        imageOutputStream = ImageIO.createImageOutputStream(destFile);
        imageWriter =
            ImageIO.getImageWritersByFormatName(FilenameUtils.getExtension(destFile.getName()))
                .next();
        imageWriter.setOutput(imageOutputStream);
        ImageWriteParam imageWriteParam = imageWriter.getDefaultWriteParam();
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        imageWriteParam.setCompressionQuality((float) (DEST_QUALITY / 100.0));
        imageWriter.write(null, new IIOImage(destBufferedImage, null, null), imageWriteParam);
        imageOutputStream.flush();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (graphics2D != null) {
          graphics2D.dispose();
        }
        if (imageWriter != null) {
          imageWriter.dispose();
        }
        if (imageOutputStream != null) {
          try {
            imageOutputStream.close();
          } catch (IOException e) {
          }
        }
      }
    } else {
      IMOperation operation = new IMOperation();
      operation.thumbnail(destWidth, destHeight);
      operation.gravity("center");
      operation.background(toHexEncoding(BACKGROUND_COLOR));
      operation.extent(destWidth, destHeight);
      operation.quality((double) DEST_QUALITY);
      operation.addImage(srcFile.getPath());
      operation.addImage(destFile.getPath());
      if (type == Type.graphicsMagick) {
        ConvertCmd convertCmd = new ConvertCmd(true);
        if (graphicsMagickPath != null) {
          convertCmd.setSearchPath(graphicsMagickPath);
        }
        try {
          convertCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      } else {
        ConvertCmd convertCmd = new ConvertCmd(false);
        if (imageMagickPath != null) {
          convertCmd.setSearchPath(imageMagickPath);
        }
        try {
          convertCmd.run(operation);
        } catch (IOException e) {
          e.printStackTrace();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } catch (IM4JavaException e) {
          e.printStackTrace();
        }
      }
    }
  }
コード例 #14
0
  private void _generateImagesIM(
      FileVersion fileVersion,
      File file,
      int depth,
      int dpi,
      int height,
      int width,
      boolean thumbnail)
      throws Exception {

    // Generate images

    String tempFileId =
        DLUtil.getTempFileId(fileVersion.getFileEntryId(), fileVersion.getVersion());

    IMOperation imOperation = new IMOperation();

    imOperation.alpha("off");

    imOperation.density(dpi, dpi);

    if (height != 0) {
      imOperation.adaptiveResize(width, height);
    } else {
      imOperation.adaptiveResize(width);
    }

    imOperation.depth(depth);

    if (thumbnail) {
      imOperation.addImage(file.getPath() + "[0]");
      imOperation.addImage(getThumbnailTempFilePath(tempFileId));
    } else {
      imOperation.addImage(file.getPath());
      imOperation.addImage(getPreviewTempFilePath(tempFileId, -1));
    }

    _convertCmd.run(imOperation);

    // Store images

    if (thumbnail) {
      File thumbnailTempFile = getThumbnailTempFile(tempFileId);

      try {
        addFileToStore(
            fileVersion.getCompanyId(), THUMBNAIL_PATH,
            getThumbnailFilePath(fileVersion), thumbnailTempFile);
      } finally {
        FileUtil.delete(thumbnailTempFile);
      }
    } else {

      // ImageMagick converts single page PDFs without appending an
      // index. Rename file for consistency.

      File singlePagePreviewFile = getPreviewTempFile(tempFileId, -1);

      if (singlePagePreviewFile.exists()) {
        singlePagePreviewFile.renameTo(getPreviewTempFile(tempFileId, 1));
      }

      int total = getPreviewTempFileCount(fileVersion);

      for (int i = 0; i < total; i++) {
        File previewTempFile = getPreviewTempFile(tempFileId, i + 1);

        try {
          addFileToStore(
              fileVersion.getCompanyId(),
              PREVIEW_PATH,
              getPreviewFilePath(fileVersion, i + 1),
              previewTempFile);
        } finally {
          FileUtil.delete(previewTempFile);
        }
      }
    }
  }
コード例 #15
0
  private void assembleOperation(IMOperation op, Parameters params, Dimension fullSize) {
    // region transformation
    Region region = params.getRegion();
    if (!region.isFull()) {
      if (region.isPercent()) {
        // im4java doesn't support cropping x/y by percentage (only
        // width/height), so we have to calculate them.
        int x = Math.round(region.getX() / 100.0f * fullSize.width);
        int y = Math.round(region.getY() / 100.0f * fullSize.height);
        int width = Math.round(region.getWidth());
        int height = Math.round(region.getHeight());
        op.crop(width, height, x, y, "%");
      } else {
        op.crop(
            Math.round(region.getWidth()), Math.round(region.getHeight()),
            Math.round(region.getX()), Math.round(region.getY()));
      }
    }

    // size transformation
    Size size = params.getSize();
    if (size.getScaleMode() != Size.ScaleMode.FULL) {
      if (size.getScaleMode() == Size.ScaleMode.ASPECT_FIT_WIDTH) {
        op.resize(size.getWidth());
      } else if (size.getScaleMode() == Size.ScaleMode.ASPECT_FIT_HEIGHT) {
        op.resize(null, size.getHeight());
      } else if (size.getScaleMode() == Size.ScaleMode.NON_ASPECT_FILL) {
        op.resize(size.getWidth(), size.getHeight(), "!".charAt(0));
      } else if (size.getScaleMode() == Size.ScaleMode.ASPECT_FIT_INSIDE) {
        op.resize(size.getWidth(), size.getHeight());
      } else if (size.getPercent() != null) {
        op.resize(Math.round(size.getPercent()), Math.round(size.getPercent()), "%".charAt(0));
      }
    }

    // rotation transformation
    Rotation rotation = params.getRotation();
    if (rotation.shouldMirror()) {
      op.flop();
    }
    if (rotation.getDegrees() != 0) {
      op.rotate(rotation.getDegrees().doubleValue());
    }

    // quality transformation
    Quality quality = params.getQuality();
    if (quality != Quality.COLOR && quality != Quality.DEFAULT) {
      switch (quality) {
        case GRAY:
          op.colorspace("Gray");
          break;
        case BITONAL:
          op.monochrome();
          break;
      }
    }
  }
コード例 #16
0
ファイル: ImageUtil.java プロジェクト: 354447958/fuc
  /**
   * 添加水印.
   *
   * @param srcFile 源文件
   * @param destFile 目标文件
   * @param watermarkFile 水印文件
   * @param watermarkPosition 水印位置
   * @param alpha 水印透明度(0-100)
   */
  public static void addWatermark(
      File srcFile,
      File destFile,
      File watermarkFile,
      WatermarkPosition watermarkPosition,
      int alpha) {
    if (watermarkFile == null
        || !watermarkFile.exists()
        || watermarkPosition == null
        || watermarkPosition == WatermarkPosition.no) {
      return;
    }
    if (type == Type.jdk) {
      try {
        BufferedImage srcBufferedImage = ImageIO.read(srcFile);
        int srcWidth = srcBufferedImage.getWidth();
        int srcHeight = srcBufferedImage.getHeight();
        BufferedImage destBufferedImage =
            new BufferedImage(srcWidth, srcHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = destBufferedImage.createGraphics();
        graphics2D.setBackground(BACKGROUND_COLOR);
        graphics2D.clearRect(0, 0, srcWidth, srcHeight);
        graphics2D.drawImage(srcBufferedImage, 0, 0, null);
        graphics2D.setComposite(
            AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha / 100.0F));

        BufferedImage watermarkBufferedImage = ImageIO.read(watermarkFile);
        int watermarkImageWidth = watermarkBufferedImage.getWidth();
        int watermarkImageHeight = watermarkBufferedImage.getHeight();
        int x = srcWidth - watermarkImageWidth;
        int y = srcHeight - watermarkImageHeight;
        if (watermarkPosition == WatermarkPosition.topLeft) {
          x = 0;
          y = 0;
        } else if (watermarkPosition == WatermarkPosition.topRight) {
          x = srcWidth - watermarkImageWidth;
          y = 0;
        } else if (watermarkPosition == WatermarkPosition.center) {
          x = (srcWidth - watermarkImageWidth) / 2;
          y = (srcHeight - watermarkImageHeight) / 2;
        } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
          x = 0;
          y = srcHeight - watermarkImageHeight;
        } else if (watermarkPosition == WatermarkPosition.bottomRight) {
          x = srcWidth - watermarkImageWidth;
          y = srcHeight - watermarkImageHeight;
        }
        graphics2D.drawImage(
            watermarkBufferedImage, x, y, watermarkImageWidth, watermarkImageHeight, null);
        graphics2D.dispose();
        ImageIO.write(destBufferedImage, FileUtil.getExtension(destFile), destFile);
      } catch (IOException e) {
        throw new RuntimeException(e);
      }
    } else {
      String gravity = "SouthEast";
      if (watermarkPosition == WatermarkPosition.topLeft) {
        gravity = "NorthWest";
      } else if (watermarkPosition == WatermarkPosition.topRight) {
        gravity = "NorthEast";
      } else if (watermarkPosition == WatermarkPosition.center) {
        gravity = "Center";
      } else if (watermarkPosition == WatermarkPosition.bottomLeft) {
        gravity = "SouthWest";
      } else if (watermarkPosition == WatermarkPosition.bottomRight) {
        gravity = "SouthEast";
      }
      IMOperation operation = new IMOperation();
      operation.gravity(gravity);
      operation.dissolve(alpha);
      operation.quality((double) DEST_QUALITY);
      operation.addImage(watermarkFile.getPath());
      operation.addImage(srcFile.getPath());
      operation.addImage(destFile.getPath());
      if (type == Type.graphicsMagick) {
        CompositeCmd compositeCmd = new CompositeCmd(true);
        if (graphicsMagickPath != null) {
          compositeCmd.setSearchPath(graphicsMagickPath);
        }
        try {
          compositeCmd.run(operation);
        } catch (IOException | InterruptedException | IM4JavaException e) {
          throw new RuntimeException(e);
        }
      } else {
        CompositeCmd compositeCmd = new CompositeCmd(false);
        if (imageMagickPath != null) {
          compositeCmd.setSearchPath(imageMagickPath);
        }
        try {
          compositeCmd.run(operation);
        } catch (IOException | InterruptedException | IM4JavaException e) {
          throw new RuntimeException(e);
        }
      }
    }
  }