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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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.AlphaComposite;
  17. import java.awt.Dimension;
  18. import java.awt.Graphics;
  19. import java.awt.Graphics2D;
  20. import java.awt.Insets;
  21. import java.awt.Shape;
  22. import java.awt.geom.AffineTransform;
  23. import java.awt.geom.Rectangle2D;
  24. import java.awt.image.AffineTransformOp;
  25. import java.awt.image.BufferedImage;
  26. import java.awt.image.RescaleOp;
  27. import java.io.ByteArrayInputStream;
  28. import java.io.IOException;
  29. import java.io.InputStream;
  30. import java.util.Iterator;
  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.poi.util.POILogFactory;
  38. import org.apache.poi.util.POILogger;
  39. /**
  40. * For now this class renders only images supported by the javax.imageio.ImageIO framework.
  41. **/
  42. public class BitmapImageRenderer implements ImageRenderer {
  43. private final static POILogger LOG = POILogFactory.getLogger(ImageRenderer.class);
  44. protected BufferedImage img;
  45. @Override
  46. public void loadImage(InputStream data, String contentType) throws IOException {
  47. img = readImage(data, contentType);
  48. }
  49. @Override
  50. public void loadImage(byte data[], String contentType) throws IOException {
  51. img = readImage(new ByteArrayInputStream(data), contentType);
  52. }
  53. /**
  54. * Read the image data via ImageIO and optionally try to workaround metadata errors.
  55. * The resulting image is of image type {@link BufferedImage#TYPE_INT_ARGB}
  56. *
  57. * @param data the data stream
  58. * @param contentType the content type
  59. * @return the bufferedImage or null, if there was no image reader for this content type
  60. * @throws IOException thrown if there was an error while processing the image
  61. */
  62. private static BufferedImage readImage(InputStream data, String contentType) throws IOException {
  63. IOException lastException = null;
  64. BufferedImage img = null;
  65. if (data.markSupported()) {
  66. data.mark(data.available());
  67. }
  68. // currently don't use FileCacheImageInputStream,
  69. // because of the risk of filling the file handles (see #59166)
  70. ImageInputStream iis = new MemoryCacheImageInputStream(data);
  71. try {
  72. iis = new MemoryCacheImageInputStream(data);
  73. iis.mark();
  74. Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
  75. while (img==null && iter.hasNext()) {
  76. ImageReader reader = iter.next();
  77. ImageReadParam param = reader.getDefaultReadParam();
  78. // 0:default mode, 1:fallback mode
  79. for (int mode=0; img==null && mode<3; mode++) {
  80. lastException = null;
  81. try {
  82. iis.reset();
  83. } catch (IOException e) {
  84. if (data.markSupported()) {
  85. data.reset();
  86. data.mark(data.available());
  87. iis.close();
  88. iis = new MemoryCacheImageInputStream(data);
  89. } else {
  90. // can't restore the input stream, so we need to stop processing here
  91. lastException = e;
  92. break;
  93. }
  94. }
  95. iis.mark();
  96. try {
  97. switch (mode) {
  98. case 0:
  99. reader.setInput(iis, false, true);
  100. img = reader.read(0, param);
  101. break;
  102. case 1: {
  103. // try to load picture in gray scale mode
  104. // fallback mode for invalid image band metadata
  105. // see http://stackoverflow.com/questions/10416378
  106. Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);
  107. while (imageTypes.hasNext()) {
  108. ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
  109. int bufferedImageType = imageTypeSpecifier.getBufferedImageType();
  110. if (bufferedImageType == BufferedImage.TYPE_BYTE_GRAY) {
  111. param.setDestinationType(imageTypeSpecifier);
  112. break;
  113. }
  114. }
  115. reader.setInput(iis, false, true);
  116. img = reader.read(0, param);
  117. break;
  118. }
  119. case 2: {
  120. // try to load truncated pictures by supplying a BufferedImage
  121. // and use the processed data up till the point of error
  122. reader.setInput(iis, false, true);
  123. int height = reader.getHeight(0);
  124. int width = reader.getWidth(0);
  125. Iterator<ImageTypeSpecifier> imageTypes = reader.getImageTypes(0);
  126. if (imageTypes.hasNext()) {
  127. ImageTypeSpecifier imageTypeSpecifier = imageTypes.next();
  128. img = imageTypeSpecifier.createBufferedImage(width, height);
  129. param.setDestination(img);
  130. } else {
  131. lastException = new IOException("unable to load even a truncated version of the image.");
  132. break;
  133. }
  134. try {
  135. reader.read(0, param);
  136. } finally {
  137. if (img.getType() != BufferedImage.TYPE_INT_ARGB) {
  138. int y = findTruncatedBlackBox(img, width, height);
  139. if (y < height) {
  140. BufferedImage argbImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
  141. Graphics2D g = argbImg.createGraphics();
  142. g.clipRect(0, 0, width, y);
  143. g.drawImage(img, 0, 0, null);
  144. g.dispose();
  145. img.flush();
  146. img = argbImg;
  147. }
  148. }
  149. }
  150. break;
  151. }
  152. }
  153. } catch (IOException e) {
  154. if (mode < 2) {
  155. lastException = e;
  156. }
  157. } catch (RuntimeException e) {
  158. if (mode < 2) {
  159. lastException = new IOException("ImageIO runtime exception - "+(mode==0 ? "normal" : "fallback"), e);
  160. }
  161. }
  162. }
  163. reader.dispose();
  164. }
  165. } finally {
  166. iis.close();
  167. }
  168. // If you don't have an image at the end of all readers
  169. if (img == null) {
  170. if (lastException != null) {
  171. // rethrow exception - be aware that the exception source can be in
  172. // multiple locations above ...
  173. throw lastException;
  174. }
  175. LOG.log(POILogger.WARN, "Content-type: "+contentType+" is not support. Image ignored.");
  176. return null;
  177. }
  178. // add alpha channel
  179. if (img.getType() != BufferedImage.TYPE_INT_ARGB) {
  180. BufferedImage argbImg = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
  181. Graphics g = argbImg.getGraphics();
  182. g.drawImage(img, 0, 0, null);
  183. g.dispose();
  184. return argbImg;
  185. }
  186. return img;
  187. }
  188. private static int findTruncatedBlackBox(BufferedImage img, int width, int height) {
  189. // scan through the image to find the black box after the truncated data
  190. int h = height-1;
  191. for (; h > 0; h--) {
  192. for (int w = width-1; w > 0; w-=width/10) {
  193. int p = img.getRGB(w, h);
  194. if (p != 0xff000000) {
  195. return h+1;
  196. }
  197. }
  198. }
  199. return 0;
  200. }
  201. @Override
  202. public BufferedImage getImage() {
  203. return img;
  204. }
  205. @Override
  206. public BufferedImage getImage(Dimension dim) {
  207. double w_old = img.getWidth();
  208. double h_old = img.getHeight();
  209. BufferedImage scaled = new BufferedImage((int)w_old, (int)h_old, BufferedImage.TYPE_INT_ARGB);
  210. double w_new = dim.getWidth();
  211. double h_new = dim.getHeight();
  212. AffineTransform at = new AffineTransform();
  213. at.scale(w_new/w_old, h_new/h_old);
  214. AffineTransformOp scaleOp = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
  215. scaleOp.filter(img, scaled);
  216. return scaled;
  217. }
  218. @Override
  219. public Dimension getDimension() {
  220. return (img == null)
  221. ? new Dimension(0,0)
  222. : new Dimension(img.getWidth(),img.getHeight());
  223. }
  224. @Override
  225. public void setAlpha(double alpha) {
  226. if (img == null) return;
  227. Dimension dim = getDimension();
  228. BufferedImage newImg = new BufferedImage((int)dim.getWidth(), (int)dim.getHeight(), BufferedImage.TYPE_INT_ARGB);
  229. Graphics2D g = newImg.createGraphics();
  230. RescaleOp op = new RescaleOp(new float[]{1.0f, 1.0f, 1.0f, (float)alpha}, new float[]{0,0,0,0}, null);
  231. g.drawImage(img, op, 0, 0);
  232. g.dispose();
  233. img = newImg;
  234. }
  235. @Override
  236. public boolean drawImage(
  237. Graphics2D graphics,
  238. Rectangle2D anchor) {
  239. return drawImage(graphics, anchor, null);
  240. }
  241. @Override
  242. public boolean drawImage(
  243. Graphics2D graphics,
  244. Rectangle2D anchor,
  245. Insets clip) {
  246. if (img == null) return false;
  247. boolean isClipped = true;
  248. if (clip == null) {
  249. isClipped = false;
  250. clip = new Insets(0,0,0,0);
  251. }
  252. int iw = img.getWidth();
  253. int ih = img.getHeight();
  254. double cw = (100000-clip.left-clip.right) / 100000.0;
  255. double ch = (100000-clip.top-clip.bottom) / 100000.0;
  256. double sx = anchor.getWidth()/(iw*cw);
  257. double sy = anchor.getHeight()/(ih*ch);
  258. double tx = anchor.getX()-(iw*sx*clip.left/100000.0);
  259. double ty = anchor.getY()-(ih*sy*clip.top/100000.0);
  260. AffineTransform at = new AffineTransform(sx, 0, 0, sy, tx, ty) ;
  261. Shape clipOld = graphics.getClip();
  262. if (isClipped) graphics.clip(anchor.getBounds2D());
  263. graphics.drawRenderedImage(img, at);
  264. graphics.setClip(clipOld);
  265. return true;
  266. }
  267. }