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

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