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.

ImageUtils.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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.ss.util;
  16. import static org.apache.poi.util.Units.EMU_PER_PIXEL;
  17. import java.awt.Dimension;
  18. import java.awt.image.BufferedImage;
  19. import java.io.ByteArrayInputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.util.Iterator;
  23. import java.util.function.Consumer;
  24. import java.util.function.Function;
  25. import javax.imageio.ImageIO;
  26. import javax.imageio.ImageReader;
  27. import javax.imageio.stream.ImageInputStream;
  28. import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
  29. import org.apache.poi.ss.usermodel.ClientAnchor;
  30. import org.apache.poi.ss.usermodel.Picture;
  31. import org.apache.poi.ss.usermodel.PictureData;
  32. import org.apache.poi.ss.usermodel.Row;
  33. import org.apache.poi.ss.usermodel.Sheet;
  34. import org.apache.poi.ss.usermodel.Workbook;
  35. import org.apache.poi.util.POILogFactory;
  36. import org.apache.poi.util.POILogger;
  37. import org.apache.poi.util.Removal;
  38. import org.apache.poi.util.Units;
  39. import org.w3c.dom.Element;
  40. import org.w3c.dom.NodeList;
  41. public final class ImageUtils {
  42. private static final POILogger logger = POILogFactory.getLogger(ImageUtils.class);
  43. /**
  44. * @deprecated use {@link Units#PIXEL_DPI}
  45. */
  46. @Deprecated
  47. @Removal(version = "5.0.0")
  48. public static final int PIXEL_DPI = 96;
  49. private static final int WIDTH_UNITS = 1024;
  50. private static final int HEIGHT_UNITS = 256;
  51. private ImageUtils() {}
  52. /**
  53. * Return the dimension of this image
  54. *
  55. * @param is the stream containing the image data
  56. * @param type type of the picture: {@link org.apache.poi.ss.usermodel.Workbook#PICTURE_TYPE_JPEG},
  57. * {@link org.apache.poi.ss.usermodel.Workbook#PICTURE_TYPE_PNG} or {@link org.apache.poi.ss.usermodel.Workbook#PICTURE_TYPE_DIB}
  58. *
  59. * @return image dimension in pixels
  60. */
  61. public static Dimension getImageDimension(InputStream is, int type) {
  62. Dimension size = new Dimension();
  63. switch (type){
  64. //we can calculate the preferred size only for JPEG, PNG and BMP
  65. //other formats like WMF, EMF and PICT are not supported in Java
  66. case Workbook.PICTURE_TYPE_JPEG:
  67. case Workbook.PICTURE_TYPE_PNG:
  68. case Workbook.PICTURE_TYPE_DIB:
  69. try {
  70. //read the image using javax.imageio.*
  71. try (ImageInputStream iis = ImageIO.createImageInputStream(is)) {
  72. Iterator<ImageReader> i = ImageIO.getImageReaders( iis );
  73. if (i.hasNext()) {
  74. ImageReader r = i.next();
  75. try {
  76. r.setInput( iis );
  77. BufferedImage img = r.read(0);
  78. int[] dpi = getResolution(r);
  79. //if DPI is zero then assume standard 96 DPI
  80. //since cannot divide by zero
  81. if (dpi[0] == 0) dpi[0] = Units.PIXEL_DPI;
  82. if (dpi[1] == 0) dpi[1] = Units.PIXEL_DPI;
  83. size.width = img.getWidth()*Units.PIXEL_DPI/dpi[0];
  84. size.height = img.getHeight()*Units.PIXEL_DPI/dpi[1];
  85. } finally {
  86. r.dispose();
  87. }
  88. } else {
  89. logger.log(POILogger.WARN, "ImageIO found no images");
  90. }
  91. }
  92. } catch (IOException e) {
  93. //silently return if ImageIO failed to read the image
  94. logger.log(POILogger.WARN, e);
  95. }
  96. break;
  97. default:
  98. logger.log(POILogger.WARN, "Only JPEG, PNG and DIB pictures can be automatically sized");
  99. }
  100. return size;
  101. }
  102. /**
  103. * The metadata of PNG and JPEG can contain the width of a pixel in millimeters.
  104. * Return the the "effective" dpi calculated as <code>25.4/HorizontalPixelSize</code>
  105. * and <code>25.4/VerticalPixelSize</code>. Where 25.4 is the number of mm in inch.
  106. *
  107. * @return array of two elements: <code>{horizontalDpi, verticalDpi}</code>.
  108. * {96, 96} is the default.
  109. */
  110. public static int[] getResolution(ImageReader r) throws IOException {
  111. int hdpi=96, vdpi=96;
  112. double mm2inch = 25.4;
  113. NodeList lst;
  114. Element node = (Element)r.getImageMetadata(0).getAsTree("javax_imageio_1.0");
  115. lst = node.getElementsByTagName("HorizontalPixelSize");
  116. if(lst != null && lst.getLength() == 1) {
  117. hdpi = (int)(mm2inch/Float.parseFloat(((Element)lst.item(0)).getAttribute("value")));
  118. }
  119. lst = node.getElementsByTagName("VerticalPixelSize");
  120. if(lst != null && lst.getLength() == 1) {
  121. vdpi = (int)(mm2inch/Float.parseFloat(((Element)lst.item(0)).getAttribute("value")));
  122. }
  123. return new int[]{hdpi, vdpi};
  124. }
  125. /**
  126. * Calculate and set the preferred size (anchor) for this picture.
  127. *
  128. * @param scaleX the amount by which image width is multiplied relative to the original width.
  129. * @param scaleY the amount by which image height is multiplied relative to the original height.
  130. * @return the new Dimensions of the scaled picture in EMUs
  131. */
  132. public static Dimension setPreferredSize(Picture picture, double scaleX, double scaleY){
  133. ClientAnchor anchor = picture.getClientAnchor();
  134. boolean isHSSF = (anchor instanceof HSSFClientAnchor);
  135. PictureData data = picture.getPictureData();
  136. Sheet sheet = picture.getSheet();
  137. // in pixel
  138. final Dimension imgSize = (scaleX == Double.MAX_VALUE || scaleY == Double.MAX_VALUE)
  139. ? getImageDimension(new ByteArrayInputStream(data.getData()), data.getPictureType())
  140. : new Dimension();
  141. // in emus
  142. final Dimension anchorSize = (scaleX != Double.MAX_VALUE || scaleY != Double.MAX_VALUE)
  143. ? ImageUtils.getDimensionFromAnchor(picture)
  144. : new Dimension();
  145. final double scaledWidth = (scaleX == Double.MAX_VALUE)
  146. ? imgSize.getWidth() : anchorSize.getWidth()/EMU_PER_PIXEL * scaleX;
  147. final double scaledHeight = (scaleY == Double.MAX_VALUE)
  148. ? imgSize.getHeight() : anchorSize.getHeight()/EMU_PER_PIXEL * scaleY;
  149. scaleCell(scaledWidth, anchor.getCol1(), anchor.getDx1(), anchor::setCol2, anchor::setDx2,
  150. isHSSF ? WIDTH_UNITS : 0, sheet::getColumnWidthInPixels);
  151. scaleCell(scaledHeight, anchor.getRow1(), anchor.getDy1(), anchor::setRow2, anchor::setDy2,
  152. isHSSF ? HEIGHT_UNITS : 0, (row) -> getRowHeightInPixels(sheet, row));
  153. return new Dimension(
  154. (int)Math.round(scaledWidth*EMU_PER_PIXEL),
  155. (int)Math.round(scaledHeight*EMU_PER_PIXEL)
  156. );
  157. }
  158. /**
  159. * Calculates the dimensions in EMUs for the anchor of the given picture
  160. *
  161. * @param picture the picture containing the anchor
  162. * @return the dimensions in EMUs
  163. */
  164. public static Dimension getDimensionFromAnchor(Picture picture) {
  165. ClientAnchor anchor = picture.getClientAnchor();
  166. boolean isHSSF = (anchor instanceof HSSFClientAnchor);
  167. Sheet sheet = picture.getSheet();
  168. // default to image size (in pixel), if the anchor is only specified for Col1/Row1
  169. Dimension imgSize = null;
  170. if (anchor.getCol2() < anchor.getCol1() || anchor.getRow2() < anchor.getRow1()) {
  171. PictureData data = picture.getPictureData();
  172. imgSize = getImageDimension(new ByteArrayInputStream(data.getData()), data.getPictureType());
  173. }
  174. int w = getDimFromCell(imgSize == null ? 0 : imgSize.getWidth(), anchor.getCol1(), anchor.getDx1(), anchor.getCol2(), anchor.getDx2(),
  175. isHSSF ? WIDTH_UNITS : 0, sheet::getColumnWidthInPixels);
  176. int h = getDimFromCell(imgSize == null ? 0 : imgSize.getHeight(), anchor.getRow1(), anchor.getDy1(), anchor.getRow2(), anchor.getDy2(),
  177. isHSSF ? HEIGHT_UNITS : 0, (row) -> getRowHeightInPixels(sheet, row));
  178. return new Dimension(w, h);
  179. }
  180. public static double getRowHeightInPixels(Sheet sheet, int rowNum) {
  181. Row r = sheet.getRow(rowNum);
  182. double points = (r == null) ? sheet.getDefaultRowHeightInPoints() : r.getHeightInPoints();
  183. return Units.toEMU(points)/(double)EMU_PER_PIXEL;
  184. }
  185. private static void scaleCell(final double targetSize,
  186. final int startCell,
  187. final int startD,
  188. Consumer<Integer> endCell,
  189. Consumer<Integer> endD,
  190. final int hssfUnits,
  191. Function<Integer,Number> nextSize) {
  192. if (targetSize < 0) {
  193. throw new IllegalArgumentException("target size < 0");
  194. }
  195. int cellIdx = startCell;
  196. double dim, delta;
  197. for (double totalDim = 0, remDim;; cellIdx++, totalDim += remDim) {
  198. dim = nextSize.apply(cellIdx).doubleValue();
  199. remDim = dim;
  200. if (cellIdx == startCell) {
  201. if (hssfUnits > 0) {
  202. remDim *= 1 - startD/(double)hssfUnits;
  203. } else {
  204. remDim -= startD/(double)EMU_PER_PIXEL;
  205. }
  206. }
  207. delta = targetSize - totalDim;
  208. if (delta < remDim) {
  209. break;
  210. }
  211. }
  212. double endDval;
  213. if (hssfUnits > 0) {
  214. endDval = delta/dim * (double)hssfUnits;
  215. } else {
  216. endDval = delta * EMU_PER_PIXEL;
  217. }
  218. if (cellIdx == startCell) {
  219. endDval += startD;
  220. }
  221. endCell.accept(cellIdx);
  222. endD.accept((int)Math.rint(endDval));
  223. }
  224. private static int getDimFromCell(double imgSize, int startCell, int startD, int endCell, int endD, int hssfUnits,
  225. Function<Integer,Number> nextSize) {
  226. double targetSize;
  227. if (endCell < startCell) {
  228. targetSize = imgSize * EMU_PER_PIXEL;
  229. } else {
  230. targetSize = 0;
  231. for (int cellIdx = startCell; cellIdx<=endCell; cellIdx++) {
  232. final double dim = nextSize.apply(cellIdx).doubleValue() * EMU_PER_PIXEL;
  233. double leadSpace = 0;
  234. if (cellIdx == startCell) {
  235. //space in the leftmost cell
  236. leadSpace = (hssfUnits > 0)
  237. ? dim * startD/(double)hssfUnits
  238. : startD;
  239. }
  240. double trailSpace = 0;
  241. if (cellIdx == endCell) {
  242. // space after the rightmost cell
  243. trailSpace = (hssfUnits > 0)
  244. ? dim * (hssfUnits-endD)/(double)hssfUnits
  245. : dim - endD;
  246. }
  247. targetSize += dim - leadSpace - trailSpace;
  248. }
  249. }
  250. return (int)Math.rint(targetSize);
  251. }
  252. }