Debian Codegraph @

src/com/github/weisj/jsvg/util/ResourceUtil.java

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 /*
2 * MIT License
3 *
4 * Copyright (c) 2022-2025 Jannis Weis
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7 * associated documentation files (the "Software"), to deal in the Software without restriction,
8 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
9 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in all copies or
13 * substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
16 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 *
21 */
22 package com.github.weisj.jsvg.util;
23
24 import java.awt.image.BufferedImage;
25 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.net.URI;
29 import java.nio.charset.StandardCharsets;
30 import java.util.*;
31 import java.util.stream.Collectors;
32
33 import javax.imageio.ImageIO;
34 import javax.imageio.ImageReadParam;
35 import javax.imageio.ImageReader;
36 import javax.imageio.stream.ImageInputStream;
37
38 import org.jetbrains.annotations.NotNull;
39 import org.jetbrains.annotations.Nullable;
40
41 import com.github.weisj.jsvg.SVGDocument;
42 import com.github.weisj.jsvg.logging.Logger;
43 import com.github.weisj.jsvg.logging.Logger.Level;
44 import com.github.weisj.jsvg.logging.impl.LogFactory;
45 import com.github.weisj.jsvg.parser.DomDocument;
46 import com.github.weisj.jsvg.parser.SVGLoader;
47 import com.github.weisj.jsvg.parser.resources.RenderableResource;
48 import com.github.weisj.jsvg.parser.resources.impl.ImageResource;
49 import com.github.weisj.jsvg.parser.resources.impl.SVGResource;
50
51 public final class ResourceUtil {
52
53 private static final Logger LOGGER = LogFactory.createLogger(ResourceUtil.class);
54
55 private ResourceUtil() {}
56
57 private static final Set<String> SUPPORTED_MIME_TYPES = Arrays
58 .stream(ImageIO.getReaderFormatNames())
59 .map(s -> "image/" + s.toLowerCase(Locale.ENGLISH))
60 .collect(Collectors.toSet());
61
62 public static @Nullable RenderableResource loadImage(@NotNull DomDocument document, @NotNull URI uri)
63 throws IOException {
64 URI resourceUri = document
65 .loaderContext()
66 .externalResourcePolicy()
67 .resolveResourceURI(document.rootURI(), uri);
68 if (resourceUri == null) return null;
69
70 String path = resourceUri.getPath();
71 if (path != null && path.endsWith(".svg")) {
72 SVGLoader loader = new SVGLoader();
73 try {
74 SVGDocument imageDocument = loader.load(uri.toURL(), document.loaderContext());
75 if (imageDocument != null) {
76 return new SVGResource(imageDocument);
77 }
78 } catch (Exception e) {
79 LOGGER.log(Level.WARNING, "Could not load svg resource", e);
80 }
81 }
82
83 BufferedImage img = loadToBufferedImage(uri);
84 if (img == null) return null;
85 return new ImageResource(img);
86 }
87
88 private static @Nullable BufferedImage loadToBufferedImage(@NotNull URI uri) throws IOException {
89 String scheme = uri.getScheme();
90 if ("data".equals(scheme)) {
91 DataUri dataUri = DataUri.parse(uri.toString(), StandardCharsets.UTF_8);
92 if (!isSupportedMimeType(dataUri.mime())) throw new IOException("Unsupported Mime type " + dataUri.mime());
93 try (ByteArrayInputStream in = new ByteArrayInputStream(dataUri.data())) {
94 return readPossiblyCorruptedFile(in);
95 }
96 }
97 return ImageIO.read(uri.toURL());
98 }
99
100 private static boolean isSupportedMimeType(@NotNull String mimeType) {
101 return SUPPORTED_MIME_TYPES.contains(mimeType.toLowerCase(Locale.ENGLISH));
102 }
103
104 private static @Nullable BufferedImage readPossiblyCorruptedFile(@NotNull InputStream inputStream)
105 throws IOException {
106 ImageInputStream input = ImageIO.createImageInputStream(inputStream);
107 Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
108 if (!readers.hasNext()) return null;
109
110 ImageReader reader = readers.next();
111 reader.setInput(input);
112
113 // Create destination image to hold possibly partially decoded result
114 ImageReadParam param = reader.getDefaultReadParam();
115 BufferedImage image = reader.getImageTypes(0).next()
116 .createBufferedImage(reader.getWidth(0), reader.getHeight(0));
117 param.setDestination(image);
118
119 try {
120 image = reader.read(0, param);
121 // Don't really need the return value here, as it will always be same value
122 // as "image"
123 } catch (Exception e) {
124 // Ignore this exception or display a warning or similar, for exceptions happening during decoding
125 LOGGER.log(Level.WARNING, e.getMessage(), e);
126 }
127 return image;
128 }
129 }