You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BitmapImageRenderer.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.sl.draw;
  16. import java.awt.Graphics;
  17. import java.awt.Graphics2D;
  18. import java.awt.Insets;
  19. import java.awt.Shape;
  20. import java.awt.geom.AffineTransform;
  21. import java.awt.geom.Dimension2D;
  22. import java.awt.geom.Rectangle2D;
  23. import java.awt.image.AffineTransformOp;
  24. import java.awt.image.BufferedImage;
  25. import java.awt.image.RescaleOp;
  26. import java.io.IOException;
  27. import java.io.InputStream;
  28. import java.util.Iterator;
  29. import java.util.stream.Stream;
  30. import java.util.stream.StreamSupport;
  31. import javax.imageio.ImageIO;
  32. import javax.imageio.ImageReadParam;
  33. import javax.imageio.ImageReader;
  34. import javax.imageio.ImageTypeSpecifier;
  35. import javax.imageio.stream.ImageInputStream;
  36. import javax.imageio.stream.MemoryCacheImageInputStream;
  37. import org.apache.commons.collections4.iterators.IteratorIterable;
  38. import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream;
  39. import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
  40. import org.apache.logging.log4j.LogManager;
  41. import org.apache.logging.log4j.Logger;
  42. import org.apache.poi.sl.usermodel.PictureData.PictureType;
  43. import org.apache.poi.util.IOUtils;
  44. /**
  45. * For now this class renders only images supported by the javax.imageio.ImageIO framework.
  46. **/
  47. public class BitmapImageRenderer implements ImageRenderer {
  48. private static final Logger LOG = LogManager.getLogger(BitmapImageRenderer.class);
  49. private static final ImageLoader[] IMAGE_LOADERS = {
  50. BitmapImageRenderer::loadColored,
  51. BitmapImageRenderer::loadGrayScaled,
  52. BitmapImageRenderer::loadTruncated
  53. };
  54. private static final String UNSUPPORTED_IMAGE_TYPE = "Unsupported Image Type";
  55. private static final PictureType[] ALLOWED_TYPES = {
  56. PictureType.JPEG,
  57. PictureType.PNG,
  58. PictureType.BMP,
  59. PictureType.GIF
  60. };
  61. protected BufferedImage img;
  62. private boolean doCache;
  63. private byte[] cachedImage;
  64. private String cachedContentType;
  65. private interface ImageLoader {
  66. BufferedImage load(ImageReader reader, ImageInputStream iis, ImageReadParam param) throws IOException;
  67. }
  68. @Override
  69. public boolean canRender(String contentType) {
  70. return Stream.of(ALLOWED_TYPES).anyMatch(t -> t.contentType.equalsIgnoreCase(contentType));
  71. }
  72. @Override
  73. public void loadImage(InputStream data, String contentType) throws IOException {
  74. InputStream in = data;
  75. if (doCache) {
  76. UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream();
  77. IOUtils.copy(data, bos);
  78. cachedImage = bos.toByteArray();
  79. cachedContentType = contentType;
  80. in = bos.toInputStream();
  81. }
  82. img = readImage(in, contentType);
  83. }
  84. @Override
  85. public void loadImage(byte[] data, String contentType) throws IOException {
  86. if (data == null) {
  87. return;
  88. }
  89. if (doCache) {
  90. cachedImage = data.clone();
  91. cachedContentType = contentType;
  92. }
  93. img = readImage(new UnsynchronizedByteArrayInputStream(data), contentType);
  94. }
  95. /**
  96. * Read the image data via ImageIO and optionally try to workaround metadata errors.
  97. * The resulting image is of image type {@link BufferedImage#TYPE_INT_ARGB}
  98. *
  99. * @param data the data stream
  100. * @param contentType the content type
  101. * @return the bufferedImage or null, if there was no image reader for this content type
  102. * @throws IOException thrown if there was an error while processing the image
  103. */
  104. private static BufferedImage readImage(final InputStream data, final String contentType) throws IOException {
  105. IOException lastException = null;
  106. BufferedImage img = null;
  107. // currently don't use FileCacheImageInputStream,
  108. // because of the risk of filling the file handles (see #59166)
  109. try (ImageInputStream iis = new MemoryCacheImageInputStream(data)) {
  110. Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
  111. while (img==null && iter.hasNext()) {
  112. lastException = null;
  113. ImageReader reader = iter.next();
  114. ImageReadParam param = reader.getDefaultReadParam();
  115. for (ImageLoader il : IMAGE_LOADERS) {
  116. iis.reset();
  117. iis.mark();
  118. try {
  119. img = il.load(reader, iis, param);
  120. if (img != null) {
  121. break;
  122. }
  123. } catch (IOException e) {
  124. lastException = e;
  125. if (UNSUPPORTED_IMAGE_TYPE.equals(e.getMessage())) {
  126. // fail early
  127. break;
  128. }
  129. } catch (RuntimeException e) {
  130. lastException = new IOException("ImageIO runtime exception", e);
  131. }
  132. }
  133. reader.dispose();
  134. }
  135. }
  136. // If you don't have an image at the end of all readers
  137. if (img == null) {
  138. if (lastException != null) {
  139. // rethrow exception - be aware that the exception source can be in
  140. // multiple locations above ...
  141. throw lastException;
  142. }
  143. LOG.atWarn().log("Content-type: {} is not supported. Image ignored.", contentType);
  144. return null;
  145. }
  146. if (img.getColorModel().hasAlpha()) {
  147. return img;
  148. }
  149. // add alpha channel
  150. BufferedImage argbImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
  151. Graphics g = argbImg.getGraphics();
  152. g.drawImage(img, 0, 0, null);
  153. g.dispose();
  154. return argbImg;
  155. }
  156. private static BufferedImage loadColored(ImageReader reader, ImageInputStream iis, ImageReadParam param) throws IOException {
  157. reader.setInput(iis, false, true);
  158. return reader.read(0, param);
  159. }
  160. private static BufferedImage loadGrayScaled(ImageReader reader, ImageInputStream iis, ImageReadParam param) throws IOException {
  161. // try to load picture in gray scale mode
  162. // fallback mode for invalid image band metadata
  163. Iterable<ImageTypeSpecifier> specs = new IteratorIterable<>(reader.getImageTypes(0));
  164. StreamSupport.stream(specs.spliterator(), false).
  165. filter(its -> its.getBufferedImageType() == BufferedImage.TYPE_BYTE_GRAY).findFirst().
  166. ifPresent(param::setDestinationType);
  167. reader.setInput(iis, false, true);
  168. return reader.read(0, param);
  169. }
  170. private static BufferedImage loadTruncated(ImageReader reader, ImageInputStream iis, ImageReadParam param) throws IOException {
  171. // try to load truncated pictures by supplying a BufferedImage
  172. // and use the processed data up till the point of error
  173. reader.setInput(iis, false, true);
  174. int height = reader.getHeight(0);
  175. int width = reader.getWidth(0);
  176. Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);
  177. if (!imageTypes.hasNext()) {
  178. // unable to load even a truncated version of the image
  179. // implicitly throwing previous error
  180. return null;
  181. }
  182. ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
  183. BufferedImage img = imageTypeSpecifier.createBufferedImage(width, height);
  184. param.setDestination(img);
  185. try {
  186. reader.read(0, param);
  187. } catch (IOException ignored) {
  188. }
  189. if (img.getColorModel().hasAlpha()) {
  190. return img;
  191. }
  192. int y = findTruncatedBlackBox(img, width, height);
  193. if (y >= height) {
  194. return img;
  195. }
  196. BufferedImage argbImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
  197. Graphics2D g = argbImg.createGraphics();
  198. g.clipRect(0, 0, width, y);
  199. g.drawImage(img, 0, 0, null);
  200. g.dispose();
  201. img.flush();
  202. return argbImg;
  203. }
  204. private static int findTruncatedBlackBox(BufferedImage img, int width, int height) {
  205. // scan through the image to find the black box after the truncated data
  206. int h = height-1;
  207. for (; h > 0; h--) {
  208. for (int w = width-1; w > 0; w-=width/10) {
  209. int p = img.getRGB(w, h);
  210. if (p != 0xff000000) {
  211. return h+1;
  212. }
  213. }
  214. }
  215. return 0;
  216. }
  217. @Override
  218. public BufferedImage getImage() {
  219. return img;
  220. }
  221. @Override
  222. public BufferedImage getImage(Dimension2D dim) {
  223. if (img == null) {
  224. return null;
  225. }
  226. double w_old = img.getWidth();
  227. double h_old = img.getHeight();
  228. double w_new = dim.getWidth();
  229. double h_new = dim.getHeight();
  230. if (w_old == w_new && h_old == h_new) {
  231. return img;
  232. }
  233. BufferedImage scaled = new BufferedImage((int)w_new, (int)h_new, BufferedImage.TYPE_INT_ARGB);
  234. AffineTransform at = new AffineTransform();
  235. at.scale(w_new/w_old, h_new/h_old);
  236. AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
  237. scaleOp.filter(img, scaled);
  238. return scaled;
  239. }
  240. @Override
  241. public Rectangle2D getBounds() {
  242. return (img == null)
  243. ? new Rectangle2D.Double()
  244. : new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight());
  245. }
  246. @Override
  247. public void setAlpha(double alpha) {
  248. img = setAlpha(img, alpha);
  249. }
  250. public static BufferedImage setAlpha(BufferedImage image, double alpha) {
  251. if (image == null) {
  252. return new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
  253. }
  254. if (alpha == 0) {
  255. return image;
  256. }
  257. float[] scalefactors = {1, 1, 1, (float)alpha};
  258. float[] offsets = {0,0,0,0};
  259. RescaleOp op = new RescaleOp(scalefactors, offsets, null);
  260. return op.filter(image, null);
  261. }
  262. @Override
  263. public boolean drawImage(
  264. Graphics2D graphics,
  265. Rectangle2D anchor) {
  266. return drawImage(graphics, anchor, null);
  267. }
  268. @Override
  269. public boolean drawImage(
  270. Graphics2D graphics,
  271. Rectangle2D anchor,
  272. Insets clip) {
  273. if (img == null) return false;
  274. boolean isClipped = true;
  275. if (clip == null) {
  276. isClipped = false;
  277. clip = new Insets(0,0,0,0);
  278. }
  279. int iw = img.getWidth();
  280. int ih = img.getHeight();
  281. double cw = (100000-clip.left-clip.right) / 100000.0;
  282. double ch = (100000-clip.top-clip.bottom) / 100000.0;
  283. double sx = anchor.getWidth()/(iw*cw);
  284. double sy = anchor.getHeight()/(ih*ch);
  285. double tx = anchor.getX()-(iw*sx*clip.left/100000.0);
  286. double ty = anchor.getY()-(ih*sy*clip.top/100000.0);
  287. AffineTransform at = new AffineTransform(sx, 0, 0, sy, tx, ty) ;
  288. Shape clipOld = graphics.getClip();
  289. if (isClipped) {
  290. graphics.clip(anchor.getBounds2D());
  291. }
  292. graphics.drawRenderedImage(img, at);
  293. graphics.setClip(clipOld);
  294. return true;
  295. }
  296. @Override
  297. public Rectangle2D getNativeBounds() {
  298. return new Rectangle2D.Double(0, 0, img.getWidth(), img.getHeight());
  299. }
  300. @Override
  301. public void setCacheInput(boolean enable) {
  302. doCache = enable;
  303. if (!enable) {
  304. cachedContentType = null;
  305. cachedImage = null;
  306. }
  307. }
  308. @Override
  309. public byte[] getCachedImage() {
  310. return cachedImage;
  311. }
  312. @Override
  313. public String getCachedContentType() {
  314. return cachedContentType;
  315. }
  316. }