de.fhg.iais.asc.xslt.binaries.scale.ImageMagickScaler.java Source code

Java tutorial

Introduction

Here is the source code for de.fhg.iais.asc.xslt.binaries.scale.ImageMagickScaler.java

Source

package de.fhg.iais.asc.xslt.binaries.scale;

/******************************************************************************
 * Copyright 2011 (c) Fraunhofer IAIS Netmedia  http://www.iais.fraunhofer.de *
 * ************************************************************************** *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License.                   *
 * You may obtain a copy of the License at                                    *
 * http://www.apache.org/licenses/LICENSE-2.0                                 *
 * Unless required by applicable law or agreed to in writing,                 *
 * software distributed under the License is distributed on an "AS IS" BASIS, *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 ******************************************************************************/

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.NullOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.fhg.iais.asc.commons.ParentDirectoryUtils;
import de.fhg.iais.asc.xslt.binaries.scale.conf.PreviewImageType;

public class ImageMagickScaler {
    private static final Logger LOG = LoggerFactory.getLogger(ImageMagickScaler.class);
    private static final NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream();

    private final String convertPath;

    public ImageMagickScaler(String convertPath) {
        this.convertPath = convertPath;
    }

    public boolean scale(File source, File target, PreviewImageType previewType, String mimetype) {
        String extentGeometry = previewType.getTargetSize().toString();
        String resizeGeometry = extentGeometry + ">";

        List<String> command = null;

        if (mimetype.startsWith("image/")) {
            command = new ArrayList<String>(Arrays.asList(this.convertPath, formatFileParameter(source), "-resize",
                    resizeGeometry, "-background", "white", "-gravity", "center", "-alpha", "remove"));
        }

        if (mimetype.equals("application/pdf")) {
            command = new ArrayList<String>(Arrays.asList(this.convertPath, formatFileParameter(source) + "[0]",
                    "-thumbnail", resizeGeometry, "-flatten"));
        }

        if (previewType.shouldUseWhiteFrame()) {
            command.addAll(Arrays.asList("-extent", extentGeometry));
        }

        command.add(formatFileParameter(target));

        return scale(source, target, command);
    }

    private boolean scale(File source, File target, List<String> command) {
        File incomplete = target;

        // Execute convert
        try {
            ParentDirectoryUtils.forceCreateParentDirectoryOf(target);

            Process process = new ProcessBuilder(command).redirectErrorStream(true).start();

            IOUtils.copyLarge(process.getInputStream(), NULL_OUTPUT_STREAM);

            if (process.waitFor() == 0) {
                incomplete = null;
                if (target.isFile()) {
                    return true;
                } else {
                    System.out.println(target);
                }
            }

            LOG.error(createErrorPrefix(source, target) + ": convert failed");
        } catch (IOException e) {
            LOG.error(createErrorPrefix(source, target), e);
        } catch (InterruptedException e) {
            throw new RuntimeException();
        } finally {
            if (incomplete != null) {
                incomplete.delete();
            }
        }

        return false;
    }

    private String createErrorPrefix(File source, File target) {
        return String.format("Can't create scaled image \"%s\" from \"%s\"", target.getAbsolutePath(),
                source.getAbsolutePath());
    }

    private String formatFileParameter(File f) {
        return f.getAbsolutePath();
    }
}