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.

XSSFPicture.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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.xssf.usermodel;
  16. import java.awt.Dimension;
  17. import java.io.IOException;
  18. import org.apache.poi.POIXMLDocumentPart;
  19. import org.apache.poi.openxml4j.opc.PackagePart;
  20. import org.apache.poi.openxml4j.opc.PackageRelationship;
  21. import org.apache.poi.ss.usermodel.Picture;
  22. import org.apache.poi.ss.usermodel.Workbook;
  23. import org.apache.poi.ss.util.ImageUtils;
  24. import org.apache.poi.util.POILogFactory;
  25. import org.apache.poi.util.POILogger;
  26. import org.apache.poi.util.Internal;
  27. import org.openxmlformats.schemas.drawingml.x2006.main.CTBlipFillProperties;
  28. import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
  29. import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureProperties;
  30. import org.openxmlformats.schemas.drawingml.x2006.main.CTPoint2D;
  31. import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
  32. import org.openxmlformats.schemas.drawingml.x2006.main.CTPresetGeometry2D;
  33. import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties;
  34. import org.openxmlformats.schemas.drawingml.x2006.main.CTTransform2D;
  35. import org.openxmlformats.schemas.drawingml.x2006.main.STShapeType;
  36. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPicture;
  37. import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTPictureNonVisual;
  38. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
  39. /**
  40. * Represents a picture shape in a SpreadsheetML drawing.
  41. *
  42. * @author Yegor Kozlov
  43. */
  44. public final class XSSFPicture extends XSSFShape implements Picture {
  45. private static final POILogger logger = POILogFactory.getLogger(XSSFPicture.class);
  46. /**
  47. * Column width measured as the number of characters of the maximum digit width of the
  48. * numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin
  49. * padding (two on each side), plus 1 pixel padding for the gridlines.
  50. *
  51. * This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial)
  52. */
  53. private static float DEFAULT_COLUMN_WIDTH = 9.140625f;
  54. /**
  55. * A default instance of CTShape used for creating new shapes.
  56. */
  57. private static CTPicture prototype = null;
  58. /**
  59. * This object specifies a picture object and all its properties
  60. */
  61. private CTPicture ctPicture;
  62. /**
  63. * Construct a new XSSFPicture object. This constructor is called from
  64. * {@link XSSFDrawing#createPicture(XSSFClientAnchor, int)}
  65. *
  66. * @param drawing the XSSFDrawing that owns this picture
  67. */
  68. protected XSSFPicture(XSSFDrawing drawing, CTPicture ctPicture){
  69. this.drawing = drawing;
  70. this.ctPicture = ctPicture;
  71. }
  72. /**
  73. * Returns a prototype that is used to construct new shapes
  74. *
  75. * @return a prototype that is used to construct new shapes
  76. */
  77. protected static CTPicture prototype(){
  78. if(prototype == null) {
  79. CTPicture pic = CTPicture.Factory.newInstance();
  80. CTPictureNonVisual nvpr = pic.addNewNvPicPr();
  81. CTNonVisualDrawingProps nvProps = nvpr.addNewCNvPr();
  82. nvProps.setId(1);
  83. nvProps.setName("Picture 1");
  84. nvProps.setDescr("Picture");
  85. CTNonVisualPictureProperties nvPicProps = nvpr.addNewCNvPicPr();
  86. nvPicProps.addNewPicLocks().setNoChangeAspect(true);
  87. CTBlipFillProperties blip = pic.addNewBlipFill();
  88. blip.addNewBlip().setEmbed("");
  89. blip.addNewStretch().addNewFillRect();
  90. CTShapeProperties sppr = pic.addNewSpPr();
  91. CTTransform2D t2d = sppr.addNewXfrm();
  92. CTPositiveSize2D ext = t2d.addNewExt();
  93. //should be original picture width and height expressed in EMUs
  94. ext.setCx(0);
  95. ext.setCy(0);
  96. CTPoint2D off = t2d.addNewOff();
  97. off.setX(0);
  98. off.setY(0);
  99. CTPresetGeometry2D prstGeom = sppr.addNewPrstGeom();
  100. prstGeom.setPrst(STShapeType.RECT);
  101. prstGeom.addNewAvLst();
  102. prototype = pic;
  103. }
  104. return prototype;
  105. }
  106. /**
  107. * Link this shape with the picture data
  108. *
  109. * @param rel relationship referring the picture data
  110. */
  111. protected void setPictureReference(PackageRelationship rel){
  112. ctPicture.getBlipFill().getBlip().setEmbed(rel.getId());
  113. }
  114. /**
  115. * Return the underlying CTPicture bean that holds all properties for this picture
  116. *
  117. * @return the underlying CTPicture bean
  118. */
  119. @Internal
  120. public CTPicture getCTPicture(){
  121. return ctPicture;
  122. }
  123. /**
  124. * Reset the image to the original size.
  125. *
  126. * <p>
  127. * Please note, that this method works correctly only for workbooks
  128. * with the default font size (Calibri 11pt for .xlsx).
  129. * If the default font is changed the resized image can be streched vertically or horizontally.
  130. * </p>
  131. */
  132. public void resize(){
  133. resize(1.0);
  134. }
  135. /**
  136. * Reset the image to the original size.
  137. * <p>
  138. * Please note, that this method works correctly only for workbooks
  139. * with the default font size (Calibri 11pt for .xlsx).
  140. * If the default font is changed the resized image can be streched vertically or horizontally.
  141. * </p>
  142. *
  143. * @param scale the amount by which image dimensions are multiplied relative to the original size.
  144. * <code>resize(1.0)</code> sets the original size, <code>resize(0.5)</code> resize to 50% of the original,
  145. * <code>resize(2.0)</code> resizes to 200% of the original.
  146. */
  147. public void resize(double scale){
  148. XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor();
  149. XSSFClientAnchor pref = getPreferredSize(scale);
  150. int row2 = anchor.getRow1() + (pref.getRow2() - pref.getRow1());
  151. int col2 = anchor.getCol1() + (pref.getCol2() - pref.getCol1());
  152. anchor.setCol2(col2);
  153. anchor.setDx1(0);
  154. anchor.setDx2(pref.getDx2());
  155. anchor.setRow2(row2);
  156. anchor.setDy1(0);
  157. anchor.setDy2(pref.getDy2());
  158. }
  159. /**
  160. * Calculate the preferred size for this picture.
  161. *
  162. * @return XSSFClientAnchor with the preferred size for this image
  163. */
  164. public XSSFClientAnchor getPreferredSize(){
  165. return getPreferredSize(1);
  166. }
  167. /**
  168. * Calculate the preferred size for this picture.
  169. *
  170. * @param scale the amount by which image dimensions are multiplied relative to the original size.
  171. * @return XSSFClientAnchor with the preferred size for this image
  172. */
  173. public XSSFClientAnchor getPreferredSize(double scale){
  174. XSSFClientAnchor anchor = (XSSFClientAnchor)getAnchor();
  175. XSSFPictureData data = getPictureData();
  176. Dimension size = getImageDimension(data.getPackagePart(), data.getPictureType());
  177. double scaledWidth = size.getWidth() * scale;
  178. double scaledHeight = size.getHeight() * scale;
  179. float w = 0;
  180. int col2 = anchor.getCol1();
  181. int dx2 = 0;
  182. for (;;) {
  183. w += getColumnWidthInPixels(col2);
  184. if(w > scaledWidth) break;
  185. col2++;
  186. }
  187. if(w > scaledWidth) {
  188. double cw = getColumnWidthInPixels(col2 );
  189. double delta = w - scaledWidth;
  190. dx2 = (int)(EMU_PER_PIXEL*(cw-delta));
  191. }
  192. anchor.setCol2(col2);
  193. anchor.setDx2(dx2);
  194. double h = 0;
  195. int row2 = anchor.getRow1();
  196. int dy2 = 0;
  197. for (;;) {
  198. h += getRowHeightInPixels(row2);
  199. if(h > scaledHeight) break;
  200. row2++;
  201. }
  202. if(h > scaledHeight) {
  203. double ch = getRowHeightInPixels(row2);
  204. double delta = h - scaledHeight;
  205. dy2 = (int)(EMU_PER_PIXEL*(ch-delta));
  206. }
  207. anchor.setRow2(row2);
  208. anchor.setDy2(dy2);
  209. CTPositiveSize2D size2d = ctPicture.getSpPr().getXfrm().getExt();
  210. size2d.setCx((long)(scaledWidth*EMU_PER_PIXEL));
  211. size2d.setCy((long)(scaledHeight*EMU_PER_PIXEL));
  212. return anchor;
  213. }
  214. private float getColumnWidthInPixels(int columnIndex){
  215. XSSFSheet sheet = (XSSFSheet)getDrawing().getParent();
  216. CTCol col = sheet.getColumnHelper().getColumn(columnIndex, false);
  217. double numChars = col == null || !col.isSetWidth() ? DEFAULT_COLUMN_WIDTH : col.getWidth();
  218. return (float)numChars*XSSFWorkbook.DEFAULT_CHARACTER_WIDTH;
  219. }
  220. private float getRowHeightInPixels(int rowIndex){
  221. XSSFSheet sheet = (XSSFSheet)getDrawing().getParent();
  222. XSSFRow row = sheet.getRow(rowIndex);
  223. float height = row != null ? row.getHeightInPoints() : sheet.getDefaultRowHeightInPoints();
  224. return height*PIXEL_DPI/POINT_DPI;
  225. }
  226. /**
  227. * Return the dimension of this image
  228. *
  229. * @param part the package part holding raw picture data
  230. * @param type type of the picture: {@link Workbook#PICTURE_TYPE_JPEG},
  231. * {@link Workbook#PICTURE_TYPE_PNG} or {@link Workbook#PICTURE_TYPE_DIB}
  232. *
  233. * @return image dimension in pixels
  234. */
  235. protected static Dimension getImageDimension(PackagePart part, int type){
  236. try {
  237. return ImageUtils.getImageDimension(part.getInputStream(), type);
  238. } catch (IOException e){
  239. //return a "singulariry" if ImageIO failed to read the image
  240. logger.log(POILogger.WARN, e);
  241. return new Dimension();
  242. }
  243. }
  244. /**
  245. * Return picture data for this shape
  246. *
  247. * @return picture data for this shape
  248. */
  249. public XSSFPictureData getPictureData() {
  250. String blipId = ctPicture.getBlipFill().getBlip().getEmbed();
  251. return (XSSFPictureData)getDrawing().getRelationById(blipId);
  252. }
  253. protected CTShapeProperties getShapeProperties(){
  254. return ctPicture.getSpPr();
  255. }
  256. }