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

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