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 12KB

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