Project

General

Profile

1
package eu.dnetlib.efg.workflows.nodes.thumbnail;
2

    
3
import java.io.File;
4
import java.io.FileNotFoundException;
5
import java.io.IOException;
6
import java.io.InputStream;
7
import java.nio.file.FileSystems;
8
import java.nio.file.Files;
9
import java.nio.file.Path;
10
import java.nio.file.StandardCopyOption;
11
import java.util.UUID;
12

    
13
import org.apache.tika.Tika;
14
import org.im4java.core.ConvertCmd;
15
import org.im4java.core.IMOperation;
16

    
17
/**
18
 * Created by sandro on 4/8/16.
19
 */
20
public class ThumbnailGenerator {
21

    
22
	private Path baseDirPath;
23

    
24
	private String dirName;
25

    
26
	public ThumbnailGenerator() throws IOException {
27
		dirName = UUID.randomUUID().toString();
28
		baseDirPath = Files.createTempDirectory(dirName);
29
	}
30

    
31
	public static boolean deleteRecursive(File path) throws FileNotFoundException {
32
		if (!path.exists()) throw new FileNotFoundException(path.getAbsolutePath());
33
		boolean ret = true;
34
		if (path.isDirectory()) {
35
			for (File f : path.listFiles()) {
36
				ret = ret && deleteRecursive(f);
37
			}
38
		}
39
		return ret && path.delete();
40
	}
41

    
42
	public InputStream convert(final InputStream input, int width, int height, final String name, boolean deleteBeforeConver) {
43
		try {
44
			destroyFolder();
45
			baseDirPath = Files.createTempDirectory(dirName);
46
			final Path tempFile = baseDirPath.resolve(name + "_orig");
47
			Files.copy(input, tempFile, StandardCopyOption.REPLACE_EXISTING);
48
			final String inputType = guessMimeType(tempFile.toAbsolutePath().toString());
49

    
50
			String inputPath = tempFile.toAbsolutePath().toString();
51
			if (inputType != null && inputType.contains("pdf")) {
52
				inputPath += "[0]";
53
			}
54
			ConvertCmd cmd = new ConvertCmd();
55
			IMOperation op = new IMOperation();
56
			op.addImage(inputPath);
57
			op.define(String.format("jpeg:size=%dx%d", width * 2, height * 2));
58
			op.thumbnail(width, height);
59
			op.unsharp(0.5);
60
			op.background("transparent");
61
			op.gravity("center");
62
			op.extent(width, height);
63
			op.colors(256);
64
			op.addImage(tempFile.toAbsolutePath().toString().replace("orig", "conv.png"));
65
			cmd.run(op);
66
			final Path path = FileSystems.getDefault().getPath(tempFile.toAbsolutePath().toString().replace("orig", "conv.png"));
67
			return Files.newInputStream(path);
68
		} catch (Throwable e) {
69
			System.out.println("Error on convert file" + e.toString());
70
			return null;
71
		}
72
	}
73

    
74
	private String guessMimeType(final String inputPath) throws IOException {
75
		Tika tika = new Tika();
76
		return tika.detect(new File(inputPath));
77
	}
78

    
79
	public boolean destroyFolder() throws FileNotFoundException {
80
		return deleteRecursive(baseDirPath.toFile());
81

    
82
	}
83

    
84
}
(2-2/3)