org.im4java.core.IMOperation Java Examples

The following examples show how to use org.im4java.core.IMOperation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ImageUtil.java    From im4java-util with Artistic License 2.0 6 votes vote down vote up
/**
 * 旋转图片
 * 
 * @param srcImagePath 源图片路径
 * @param destImagePath 目标图片路径
 * @param angle 旋转的角度
 * @return
 * @throws Exception
 */
public static void rotate(String srcImagePath, String destImagePath, Double angle)
        throws Exception {
    File sourceFile = new File(srcImagePath);
    if (!sourceFile.exists() || !sourceFile.canRead() || !sourceFile.isFile()) {
        return;
    }

    BufferedImage buffimg = ImageIO.read(sourceFile);
    int w = buffimg.getWidth();
    int h = buffimg.getHeight();
    // 目标图片
    // if (w > h) { //如果宽度不大于高度则旋转过后图片会变大
    ImageCommand cmd = getImageCommand(CommandType.convert);
    IMOperation operation = new IMOperation();
    operation.addImage(srcImagePath);
    operation.rotate(angle);
    operation.addImage(destImagePath);
    cmd.run(operation);
    // }
}
 
Example #2
Source File: GMBatchCommandTest.java    From gm4java with Apache License 2.0 6 votes vote down vote up
@Test
public void run_handlesBufferedImageAsInput() throws Exception {
    final String command = "convert";
    sut = new GMBatchCommand(service, command);
    BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/a.png"));
    IMOperation op = new IMOperation();
    op.addImage();                        // input
    op.resize(80, 60);
    op.addImage();                        // output

    sut.run(op, image, TARGET_IMAGE);

    @java.lang.SuppressWarnings("unchecked")
    ArgumentCaptor<List<String>> captor = ArgumentCaptor.forClass((Class<List<String>>) (Class<?>) List.class);
    verify(service).execute(captor.capture());
    assertThat(captor.getValue(),
            equalTo(Arrays.asList(command, captor.getValue().get(1), "-resize", "80x60", TARGET_IMAGE)));
}
 
Example #3
Source File: GMBatchCommandTest.java    From gm4java with Apache License 2.0 6 votes vote down vote up
@Test
public void run_returnsResultBack() throws Exception {
    final String command = "identify";
    sut = new GMBatchCommand(service, command);
    IMOperation op = new IMOperation();
    op.ping();
    final String format = "%m\n%W\n%H\n%g\n%z";
    op.format(format);
    op.addImage();
    ArrayListOutputConsumer output = new ArrayListOutputConsumer();
    sut.setOutputConsumer(output);
    when(service.execute(anyListOf(String.class))).thenReturn("JPEG\n800\n600\n800x600\n0\n");

    sut.run(op, SOURCE_IMAGE);

    verify(service).execute(Arrays.asList(command, "-ping", "-format", format, SOURCE_IMAGE));
    // ... and parse result
    ArrayList<String> cmdOutput = output.getOutput();
    Iterator<String> iter = cmdOutput.iterator();
    assertThat(iter.next(), is("JPEG"));
    assertThat(iter.next(), is("800"));
    assertThat(iter.next(), is("600"));
    assertThat(iter.next(), is("800x600"));
    assertThat(iter.next(), is("0"));
}
 
Example #4
Source File: GMBatchCommandTest.java    From gm4java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("NP_NONNULL_PARAM_VIOLATION")
public void run_works_whenOutputConsumerIsNull() throws Exception {
    // create command
    final String command = "convert";
    sut = new GMBatchCommand(service, command);
    // create the operation, add images and operators/options
    IMOperation op = new IMOperation();
    op.addImage(SOURCE_IMAGE);
    op.resize(800, 600);
    op.addImage(TARGET_IMAGE);
    sut.setOutputConsumer(null);

    // execute the operation
    sut.run(op);

    verify(service).execute(Arrays.asList(command, SOURCE_IMAGE, "-resize", "800x600", TARGET_IMAGE));
}
 
Example #5
Source File: GMBatchCommandTest.java    From gm4java with Apache License 2.0 6 votes vote down vote up
@Test
public void run_sendsCommandToService() throws Exception {
    // create command
    final String command = "convert";
    sut = new GMBatchCommand(service, command);
    // create the operation, add images and operators/options
    IMOperation op = new IMOperation();
    op.addImage(SOURCE_IMAGE);
    op.resize(800, 600);
    op.addImage(TARGET_IMAGE);

    // execute the operation
    sut.run(op);

    verify(service).execute(Arrays.asList(command, SOURCE_IMAGE, "-resize", "800x600", TARGET_IMAGE));
}
 
Example #6
Source File: GMBatchCommandTest.java    From gm4java with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("NP_NONNULL_PARAM_VIOLATION")
public void run_chokes_whenErrorConsumerIsNull() throws Exception {
    // create command
    final String command = "bad";
    sut = new GMBatchCommand(service, command);
    // create the operation, add images and operators/options
    IMOperation op = new IMOperation();
    op.addImage(SOURCE_IMAGE);
    op.resize(800, 600);
    op.addImage(TARGET_IMAGE);
    final String message = "bad command";
    when(service.execute(anyListOf(String.class))).thenThrow(new GMException(message));
    exception.expect(CommandException.class);
    exception.expectMessage(message);
    sut.setErrorConsumer(null);

    // execute the operation
    sut.run(op);
}
 
Example #7
Source File: GMBatchCommandTest.java    From gm4java with Apache License 2.0 6 votes vote down vote up
@Test
public void run_chokes_whenServiceChokes() throws Exception {
    // create command
    final String command = "bad";
    sut = new GMBatchCommand(service, command);
    // create the operation, add images and operators/options
    IMOperation op = new IMOperation();
    op.addImage(SOURCE_IMAGE);
    op.resize(800, 600);
    op.addImage(TARGET_IMAGE);
    final String message = "bad command";
    when(service.execute(anyListOf(String.class))).thenThrow(new GMException(message));
    exception.expect(CommandException.class);
    exception.expectMessage(message);

    // execute the operation
    sut.run(op);
}
 
Example #8
Source File: ImageUtil.java    From im4java-util with Artistic License 2.0 6 votes vote down vote up
/**
 * 图片水印
 * 
 * @param srcImagePath 源图片路径
 * @param destImagePath 目标图片路径
 * @param dissolve 透明度(0-100)
 * @throws Exception
 */
public static void addImgWatermark(String srcImagePath, String destImagePath, Integer dissolve)
        throws Exception {
    // 原始图片信息
    BufferedImage buffimg = ImageIO.read(new File(srcImagePath));
    int w = buffimg.getWidth();
    int h = buffimg.getHeight();

    IMOperation op = new IMOperation();
    // 水印图片位置
    op.geometry(watermarkImage.getWidth(null), watermarkImage.getHeight(null), w
            - watermarkImage.getWidth(null) - 10, h - watermarkImage.getHeight(null) - 10);
    // 水印透明度
    op.dissolve(dissolve);
    // 水印
    op.addImage(watermarkImagePath);
    // 原图
    op.addImage(srcImagePath);
    // 目标
    op.addImage(createDirectory(destImagePath));
    ImageCommand cmd = getImageCommand(CommandType.compositecmd);
    cmd.run(op);
}
 
Example #9
Source File: ImageUtil.java    From im4java-util with Artistic License 2.0 6 votes vote down vote up
/**
 * 文字水印
 * 
 * @param srcImagePath 源图片路径
 * @param destImagePath 目标图片路径
 * @param content 文字内容(不支持汉字)
 * @throws Exception
 */
public static void addTextWatermark(String srcImagePath, String destImagePath, String content)
        throws Exception {
    IMOperation op = new IMOperation();
    op.font("微软雅黑");
    // 文字方位-东南
    op.gravity("southeast");
    // 文字信息
    op.pointsize(18).fill("#BCBFC8").draw("text 10,10 " + content);
    // 原图
    op.addImage(srcImagePath);
    // 目标
    op.addImage(createDirectory(destImagePath));
    ImageCommand cmd = getImageCommand(CommandType.convert);
    cmd.run(op);
}
 
Example #10
Source File: ImageUtil.java    From im4java-util with Artistic License 2.0 6 votes vote down vote up
/**
 * 获取图片信息
 * 
 * @param srcImagePath 图片路径
 * @return Map {height=, filelength=, directory=, width=, filename=}
 */
public static Map<String, Object> getImageInfo(String srcImagePath) {
    IMOperation op = new IMOperation();
    op.format("%w,%h,%d,%f,%b");
    op.addImage(srcImagePath);
    IdentifyCmd identifyCmd = (IdentifyCmd) getImageCommand(CommandType.identify);
    ArrayListOutputConsumer output = new ArrayListOutputConsumer();
    identifyCmd.setOutputConsumer(output);
    try {
        identifyCmd.run(op);
    } catch (Exception e) {
        e.printStackTrace();
    }
    ArrayList<String> cmdOutput = output.getOutput();
    if (cmdOutput.size() != 1)
        return null;
    String line = cmdOutput.get(0);
    String[] arr = line.split(",");
    Map<String, Object> info = new HashMap<String, Object>();
    info.put("width", Integer.parseInt(arr[0]));
    info.put("height", Integer.parseInt(arr[1]));
    info.put("directory", arr[2]);
    info.put("filename", arr[3]);
    info.put("filelength", Integer.parseInt(arr[4]));
    return info;
}
 
Example #11
Source File: ImageUtil.java    From im4java-util with Artistic License 2.0 5 votes vote down vote up
/**
 * 将图片分割为若干小图
 * 
 * @param srcImagePath 源图片路径
 * @param destImagePath 目标图片路径
 * @param width 指定宽度(默认为完整宽度)
 * @param height 指定高度(默认为完整高度)
 * @return 小图路径
 * @throws Exception
 */
public static List<String> subsection(String srcImagePath, String destImagePath, Integer width,
        Integer height) throws Exception {
    IMOperation op = new IMOperation();
    op.addImage(srcImagePath);
    op.crop(width, height);
    op.addImage(createDirectory(destImagePath));

    ImageCommand cmd = getImageCommand(CommandType.convert);
    cmd.run(op);

    return getSubImages(destImagePath);
}
 
Example #12
Source File: MagickImgUtils.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 压缩图片   ---暂时不使用
 *
 * @param orgImg            图片源地址 local or network url.
 * @param destImg           图片输入地址
 * @param destWidth         图片目标宽度
 * @param destHeight        图片目标高度
 * @param isDistortion      是否保留视觉比例,true则强行改变宽高尺寸匹配使用给定的宽和高
 * @param methodChoice      如果使用ImageMagick,设为false,使用GraphicsMagick,就设为true,默认为false
 * @param windowsMagickPath 若系统为windows则,必须指定GraphicsMagick的安装路径,例如:S:/Program Files (x86)/GraphicsMagick-1.3.21-Q8,其他系统为空
 * @return void 输出到目标地址
 */
@Deprecated
public static final void compressImg(String orgImg, String destImg, int destWidth, int destHeight, boolean isDistortion, boolean methodChoice, String windowsMagickPath) throws TSException {
    try {
        IMOperation imop = new IMOperation();  // or IMOperation GMOperation
        imop.addImage(orgImg);
        //图片压缩比,有效值范围是0.0-100.0,数值越大,缩略图越清晰
        imop.quality(75.0);
        //width 和height可以是原图的尺寸,也可以是按比例处理后的尺寸
        if (isDistortion) {
            imop.addRawArgs("-resize", destWidth + "x" + destHeight + "!");
        } else {
            imop.addRawArgs("-resize", destWidth + "x" + destHeight);
        }
        imop.addRawArgs("-gravity", "center");
        imop.addImage(destImg);
        // 如果使用ImageMagick,设为false,使用GraphicsMagick,就设为true,默认为false
        //环境变量ok
        //未安装装GraphicsMagick java.io.FileNotFoundException: gm
        //未安装了ImageMagick java.io.FileNotFoundException: convert
        ConvertCmd convert = new ConvertCmd(methodChoice);
        // linux下不要设置此值,不然会报错
        String os = System.getProperty("os.name").toLowerCase();
        if (os.indexOf("windows") >= 0) {
            String msg = "GraphicsMagick";
            if (!methodChoice) msg = "ImageMagick";
            if (StringUtils.isEmpty(windowsMagickPath)) {
                throw new TSException(TSEDictionary.SYSTEM_EXCEPTION.getCode(), "If the system for Windows, " + msg + "'s path cannot be empty.");
            }
            convert.setSearchPath(windowsMagickPath);
        }
        convert.run(imop);
    } catch (Exception e) {
        throw new TSException(TSEDictionary.UNDEFINED_FAIL.getCode(), "Image compress failure." + e.getMessage());
    }
}
 
Example #13
Source File: ImageUtils.java    From AppiumTestDistribution with GNU General Public License v3.0 5 votes vote down vote up
public void wrapDeviceFrames(String deviceFrame, String deviceScreenToBeFramed,
                             String framedDeviceScreen)
        throws InterruptedException, IOException, IM4JavaException {
    IMOperation op = new IMOperation();
    op.addImage(deviceFrame);
    op.addImage(deviceScreenToBeFramed);
    op.gravity("center");
    op.composite();
    op.opaque("none");
    op.addImage(framedDeviceScreen);
    ConvertCmd cmd = new ConvertCmd();
    cmd.run(op);
}
 
Example #14
Source File: ImageUtil.java    From im4java-util with Artistic License 2.0 5 votes vote down vote up
/**
 * 等比缩放图片(如果width为空,则按height缩放; 如果height为空,则按width缩放)
 * 
 * @param srcImagePath 源图片路径
 * @param destImagePath 目标图片路径
 * @param width 缩放后的宽度
 * @param height 缩放后的高度
 * @throws Exception
 */
public static void scaleResize(String srcImagePath, String destImagePath, Integer width,
        Integer height) throws Exception {
    IMOperation op = new IMOperation();
    op.addImage(srcImagePath);
    op.sample(width, height);
    op.addImage(createDirectory(destImagePath));
    ImageCommand cmd = getImageCommand(CommandType.convert);
    cmd.run(op);
}
 
Example #15
Source File: ImageUtil.java    From im4java-util with Artistic License 2.0 5 votes vote down vote up
/**
 * 去除Exif信息,可减小文件大小
 * 
 * @param srcImagePath 源图片路径
 * @param destImagePath 目标图片路径
 * @throws Exception
 */
public static void removeProfile(String srcImagePath, String destImagePath) throws Exception {
    IMOperation op = new IMOperation();
    op.addImage(srcImagePath);
    op.profile("*");
    op.addImage(createDirectory(destImagePath));
    ImageCommand cmd = getImageCommand(CommandType.convert);
    cmd.run(op);
}
 
Example #16
Source File: ImageResource.java    From entando-components with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Resize images using im4Java
 */
private void saveResizedImage(ResourceDataBean bean, ImageResourceDimension dimension) throws ApsSystemException {
    if (dimension.getIdDim() == 0) {
        // skips element with id zero that shouldn't be resized
        return;
    }
    String imageName = this.getNewInstanceFileName(bean.getFileName(), dimension.getIdDim(), null);
    String subPath = super.getDiskSubFolder() + imageName;
    try {
        this.getStorageManager().deleteFile(subPath, this.isProtectedResource());
        ResourceInstance resizedInstance = new ResourceInstance();
        resizedInstance.setSize(dimension.getIdDim());
        resizedInstance.setFileName(imageName);
        resizedInstance.setMimeType(bean.getMimeType());
        String tempFilePath = System.getProperty("java.io.tmpdir") + File.separator + "temp_" + imageName;
        File tempFile = new File(tempFilePath);
        long realLength = tempFile.length() / 1000;
        resizedInstance.setFileLength(realLength + " Kb");
        this.addInstance(resizedInstance);
        // create command
        ConvertCmd convertCmd = new ConvertCmd();
        //Is it a windows system?
        if (this.isImageMagickWindows()) {
            //yes so configure the path where ImagicMagick is installed
            convertCmd.setSearchPath(this.getImageMagickPath());
        }

        //svg files won't resize correctly via the image processor so save them directly
        if(bean.getMimeType().contains("svg")) {
            FileUtils.copyFile(bean.getFile(), tempFile);
            this.getStorageManager().saveFile(subPath, this.isProtectedResource(), new FileInputStream(tempFile));
        }else {
            // create the operation, add images and operators/options
            IMOperation imOper = new IMOperation();
            imOper.addImage();
            imOper.resize(dimension.getDimx(), dimension.getDimy());
            imOper.addImage();
            convertCmd.run(imOper, bean.getFile().getAbsolutePath(), tempFile.getAbsolutePath());
            this.getStorageManager().saveFile(subPath, this.isProtectedResource(), new FileInputStream(tempFile));
        }

        boolean deleted = tempFile.delete();

        if (!deleted) {
            logger.warn(FAILED_TO_DELETE_TEMP_FILE, tempFile);
        }
    } catch (Throwable t) {
        logger.error("Error creating resource file instance '{}'", subPath, t);
        throw new ApsSystemException("Error creating resource file instance '" + subPath + "'", t);
    }
}
 
Example #17
Source File: ImageUtil.java    From im4java-util with Artistic License 2.0 3 votes vote down vote up
/**
 * 从原图中裁剪出新图
 * 
 * @param srcImagePath 源图片路径
 * @param destImagePath 目标图片路径
 * @param x 原图左上角
 * @param y 原图左上角
 * @param width 新图片宽度
 * @param height 新图片高度
 * @throws Exception
 */
public static void crop(String srcImagePath, String destImagePath, int x, int y, int width,
        int height) throws Exception {
    IMOperation op = new IMOperation();
    op.addImage(srcImagePath);
    op.crop(width, height, x, y);
    op.addImage(createDirectory(destImagePath));
    ImageCommand cmd = getImageCommand(CommandType.convert);
    cmd.run(op);
}