1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.imaging.internal;
19
20 import java.io.IOException;
21 import java.util.function.Predicate;
22 import java.util.function.Supplier;
23
24 import org.apache.commons.imaging.AbstractImageParser;
25 import org.apache.commons.imaging.ImageFormat;
26 import org.apache.commons.imaging.ImageFormats;
27 import org.apache.commons.imaging.Imaging;
28 import org.apache.commons.imaging.ImagingParameters;
29 import org.apache.commons.imaging.bytesource.ByteSource;
30
31
32
33
34
35
36 public final class ImageParserFactory {
37
38 public static <T extends ImagingParameters<T>> AbstractImageParser<T> getImageParser(final ByteSource byteSource) throws IOException {
39
40 final ImageFormat format = Imaging.guessFormat(byteSource);
41 if (!format.equals(ImageFormats.UNKNOWN)) {
42 return getImageParser(format);
43 }
44 final String fileName = byteSource.getFileName();
45 if (fileName != null) {
46 return getImageParser(fileName);
47 }
48 throw new IllegalArgumentException("Can't parse this format.");
49 }
50
51 public static <T extends ImagingParameters<T>> AbstractImageParser<T> getImageParser(final ImageFormat format) {
52 return getImageParser(parser -> parser.canAcceptType(format), () -> new IllegalArgumentException("Unknown ImageFormat: " + format));
53 }
54
55
56
57 @SuppressWarnings("unchecked")
58 private static <T extends ImagingParameters<T>> AbstractImageParser<T> getImageParser(final Predicate<AbstractImageParser<?>> pred,
59 final Supplier<? extends RuntimeException> supplier) {
60 return (AbstractImageParser<T>) AbstractImageParser.getAllImageParsers().stream().filter(pred).findFirst().orElseThrow(supplier);
61 }
62
63 public static <T extends ImagingParameters<T>> AbstractImageParser<T> getImageParser(final String fileExtension) {
64 return getImageParser(parser -> parser.canAcceptExtension(fileExtension), () -> new IllegalArgumentException("Unknown extension: " + fileExtension));
65 }
66
67 private ImageParserFactory() {
68 }
69 }