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.

DrawPictureShape.java 7.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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.Graphics2D;
  18. import java.awt.Insets;
  19. import java.awt.Paint;
  20. import java.awt.geom.Rectangle2D;
  21. import java.io.IOException;
  22. import java.util.ServiceLoader;
  23. import java.util.function.Supplier;
  24. import java.util.stream.StreamSupport;
  25. import org.apache.logging.log4j.LogManager;
  26. import org.apache.logging.log4j.Logger;
  27. import org.apache.poi.common.usermodel.PictureType;
  28. import org.apache.poi.poifs.filesystem.FileMagic;
  29. import org.apache.poi.sl.usermodel.PictureData;
  30. import org.apache.poi.sl.usermodel.PictureShape;
  31. import org.apache.poi.sl.usermodel.RectAlign;
  32. public class DrawPictureShape extends DrawSimpleShape {
  33. private static final Logger LOG = LogManager.getLogger(DrawPictureShape.class);
  34. public DrawPictureShape(PictureShape<?,?> shape) {
  35. super(shape);
  36. }
  37. @Override
  38. public void drawContent(Graphics2D graphics) {
  39. PictureShape<?,?> ps = getShape();
  40. Rectangle2D anchor = getAnchor(graphics, ps);
  41. Insets insets = ps.getClipping();
  42. PictureData[] pics = { ps.getAlternativePictureData(), ps.getPictureData() };
  43. for (PictureData data : pics) {
  44. if (data == null) {
  45. continue;
  46. }
  47. try {
  48. byte[] dataBytes = data.getData();
  49. PictureType type = PictureType.valueOf(FileMagic.valueOf(dataBytes));
  50. String ct = (type == PictureType.UNKNOWN) ? data.getContentType() : type.getContentType();
  51. ImageRenderer renderer = getImageRenderer(graphics, ct);
  52. if (renderer.canRender(ct)) {
  53. renderer.loadImage(dataBytes, ct);
  54. renderer.drawImage(graphics, anchor, insets);
  55. return;
  56. }
  57. } catch (IOException e) {
  58. LOG.atError().withThrowable(e).log("image can't be loaded/rendered.");
  59. }
  60. }
  61. }
  62. /**
  63. * Returns an ImageRenderer for the PictureData
  64. *
  65. * @param graphics the graphics context
  66. * @return the image renderer
  67. */
  68. public static ImageRenderer getImageRenderer(Graphics2D graphics, String contentType) {
  69. final ImageRenderer renderer = (graphics != null) ? (ImageRenderer)graphics.getRenderingHint(Drawable.IMAGE_RENDERER) : null;
  70. if (renderer != null && renderer.canRender(contentType)) {
  71. return renderer;
  72. }
  73. final BitmapImageRenderer fallback = new BitmapImageRenderer();
  74. if (fallback.canRender(contentType)) {
  75. return fallback;
  76. }
  77. // the fallback is the BitmapImageRenderer, at least it gracefully handles invalid images
  78. final Supplier<ImageRenderer> getFallback = () -> {
  79. LOG.atWarn().log("No suitable image renderer found for content-type '{}' - include " +
  80. "poi-scratchpad (for wmf/emf) or poi-ooxml (for svg) jars!", contentType);
  81. return fallback;
  82. };
  83. ClassLoader cl = DrawPictureShape.class.getClassLoader();
  84. return StreamSupport
  85. .stream(ServiceLoader.load(ImageRenderer.class, cl).spliterator(), false)
  86. .filter(ir -> ir.canRender(contentType))
  87. .findFirst()
  88. .orElseGet(getFallback)
  89. ;
  90. }
  91. @Override
  92. protected Paint getFillPaint(Graphics2D graphics) {
  93. return null;
  94. }
  95. @Override
  96. protected PictureShape<?,?> getShape() {
  97. return (PictureShape<?,?>)shape;
  98. }
  99. /**
  100. * Resize this picture to the default size.
  101. *
  102. * For PNG and JPEG resizes the image to 100%,
  103. * for other types, if the size can't be determined it will be 200x200 pixels.
  104. */
  105. public void resize() {
  106. PictureShape<?,?> ps = getShape();
  107. Dimension dim = ps.getPictureData().getImageDimension();
  108. Rectangle2D origRect = ps.getAnchor();
  109. double x = origRect.getX();
  110. double y = origRect.getY();
  111. double w = dim.getWidth();
  112. double h = dim.getHeight();
  113. ps.setAnchor(new Rectangle2D.Double(x, y, w, h));
  114. }
  115. /**
  116. * Fit picture shape into the target rectangle, maintaining the aspect ratio
  117. * and repositioning within the target rectangle with a centered alignment.
  118. *
  119. * @param target The target rectangle
  120. */
  121. public void resize(Rectangle2D target) {
  122. resize(target, RectAlign.CENTER);
  123. }
  124. /**
  125. * Fit picture shape into the target rectangle, maintaining the aspect ratio
  126. * and repositioning within the target rectangle based on the specified
  127. * alignment (gravity).
  128. *
  129. * @param target The target rectangle
  130. * @param align
  131. * The alignment within the target rectangle when resizing.
  132. * A null value corresponds to RectAlign.CENTER
  133. */
  134. public void resize(Rectangle2D target, RectAlign align) {
  135. PictureShape<?,?> ps = getShape();
  136. Dimension dim = ps.getPictureData().getImageDimension();
  137. if (dim.width <= 0 || dim.height <= 0) {
  138. // nothing useful to be done for this case
  139. ps.setAnchor(target);
  140. return;
  141. }
  142. double w = target.getWidth();
  143. double h = target.getHeight();
  144. // scaling
  145. double sx = w / dim.width;
  146. double sy = h / dim.height;
  147. // position adjustments
  148. double dx = 0, dy = 0;
  149. if (sx > sy) {
  150. // use y-scaling for both, reposition x accordingly
  151. w = sy * dim.width;
  152. dx = target.getWidth() - w;
  153. } else if (sy > sx) {
  154. // use x-scaling for both, reposition y accordingly
  155. h = sx * dim.height;
  156. dy = target.getHeight() - h;
  157. } else {
  158. // uniform scaling, can use target values directly
  159. ps.setAnchor(target);
  160. return;
  161. }
  162. // the positioning
  163. double x = target.getX();
  164. double y = target.getY();
  165. switch (align) {
  166. case TOP: // X=balance, Y=ok
  167. x += dx/2;
  168. break;
  169. case TOP_RIGHT: // X=shift, Y=ok
  170. x += dx;
  171. break;
  172. case RIGHT: // X=shift, Y=balance
  173. x += dx;
  174. y += dy/2;
  175. break;
  176. case BOTTOM_RIGHT: // X=shift, Y=shift
  177. x += dx;
  178. y += dy;
  179. break;
  180. case BOTTOM: // X=balance, Y=shift
  181. x += dx/2;
  182. y += dy;
  183. break;
  184. case BOTTOM_LEFT: // X=ok, Y=shift
  185. y += dy;
  186. break;
  187. case LEFT: // X=ok, Y=balance
  188. y += dy/2;
  189. break;
  190. case TOP_LEFT: // X=ok, Y=ok
  191. /* no-op */
  192. break;
  193. default: // CENTER: X=balance, Y=balance
  194. x += dx/2;
  195. y += dy/2;
  196. break;
  197. }
  198. ps.setAnchor(new Rectangle2D.Double(x, y, w, h));
  199. }
  200. }