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

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