1. /*
  2. * @(#)AffineTransformOp.java 1.62 03/12/19
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.awt.image;
  8. import java.awt.geom.AffineTransform;
  9. import java.awt.geom.NoninvertibleTransformException;
  10. import java.awt.geom.Rectangle2D;
  11. import java.awt.geom.Point2D;
  12. import java.awt.AlphaComposite;
  13. import java.awt.GraphicsEnvironment;
  14. import java.awt.Rectangle;
  15. import java.awt.RenderingHints;
  16. import java.awt.Transparency;
  17. import sun.awt.image.ImagingLib;
  18. /**
  19. * This class uses an affine transform to perform a linear mapping from
  20. * 2D coordinates in the source image or <CODE>Raster</CODE> to 2D coordinates
  21. * in the destination image or <CODE>Raster</CODE>.
  22. * The type of interpolation that is used is specified through a constructor,
  23. * either by a <CODE>RenderingHints</CODE> object or by one of the integer
  24. * interpolation types defined in this class.
  25. * <p>
  26. * If a <CODE>RenderingHints</CODE> object is specified in the constructor, the
  27. * interpolation hint and the rendering quality hint are used to set
  28. * the interpolation type for this operation. The color rendering hint
  29. * and the dithering hint can be used when color conversion is required.
  30. * <p>
  31. * Note that the following constraints have to be met:
  32. * <ul>
  33. * <li>The source and destination must be different.
  34. * <li>For <CODE>Raster</CODE> objects, the number of bands in the source must
  35. * be equal to the number of bands in the destination.
  36. * </ul>
  37. * @see AffineTransform
  38. * @see BufferedImageFilter
  39. * @see java.awt.RenderingHints#KEY_INTERPOLATION
  40. * @see java.awt.RenderingHints#KEY_RENDERING
  41. * @see java.awt.RenderingHints#KEY_COLOR_RENDERING
  42. * @see java.awt.RenderingHints#KEY_DITHERING
  43. * @version 16 Apr 1998
  44. */
  45. public class AffineTransformOp implements BufferedImageOp, RasterOp {
  46. private AffineTransform xform;
  47. RenderingHints hints;
  48. /**
  49. * Nearest-neighbor interpolation type.
  50. */
  51. public static final int TYPE_NEAREST_NEIGHBOR = 1;
  52. /**
  53. * Bilinear interpolation type.
  54. */
  55. public static final int TYPE_BILINEAR = 2;
  56. /**
  57. * Bicubic interpolation type.
  58. */
  59. public static final int TYPE_BICUBIC = 3;
  60. int interpolationType = TYPE_NEAREST_NEIGHBOR;
  61. /**
  62. * Constructs an <CODE>AffineTransformOp</CODE> given an affine transform.
  63. * The interpolation type is determined from the
  64. * <CODE>RenderingHints</CODE> object. If the interpolation hint is
  65. * defined, it will be used. Otherwise, if the rendering quality hint is
  66. * defined, the interpolation type is determined from its value. If no
  67. * hints are specified (<CODE>hints</CODE> is null),
  68. * the interpolation type is {@link #TYPE_NEAREST_NEIGHBOR
  69. * TYPE_NEAREST_NEIGHBOR}.
  70. *
  71. * @param xform The <CODE>AffineTransform</CODE> to use for the
  72. * operation.
  73. *
  74. * @param hints The <CODE>RenderingHints</CODE> object used to specify
  75. * the interpolation type for the operation.
  76. *
  77. * @throws ImagingOpException if the transform is non-invertible.
  78. * @see java.awt.RenderingHints#KEY_INTERPOLATION
  79. * @see java.awt.RenderingHints#KEY_RENDERING
  80. */
  81. public AffineTransformOp(AffineTransform xform, RenderingHints hints){
  82. validateTransform(xform);
  83. this.xform = (AffineTransform) xform.clone();
  84. this.hints = hints;
  85. if (hints != null) {
  86. Object value = hints.get(hints.KEY_INTERPOLATION);
  87. if (value == null) {
  88. value = hints.get(hints.KEY_RENDERING);
  89. if (value == hints.VALUE_RENDER_SPEED) {
  90. interpolationType = TYPE_NEAREST_NEIGHBOR;
  91. }
  92. else if (value == hints.VALUE_RENDER_QUALITY) {
  93. interpolationType = TYPE_BILINEAR;
  94. }
  95. }
  96. else if (value == hints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR) {
  97. interpolationType = TYPE_NEAREST_NEIGHBOR;
  98. }
  99. else if (value == hints.VALUE_INTERPOLATION_BILINEAR) {
  100. interpolationType = TYPE_BILINEAR;
  101. }
  102. else if (value == hints.VALUE_INTERPOLATION_BICUBIC) {
  103. interpolationType = TYPE_BICUBIC;
  104. }
  105. }
  106. else {
  107. interpolationType = TYPE_NEAREST_NEIGHBOR;
  108. }
  109. }
  110. /**
  111. * Constructs an <CODE>AffineTransformOp</CODE> given an affine transform
  112. * and the interpolation type.
  113. *
  114. * @param xform The <CODE>AffineTransform</CODE> to use for the operation.
  115. * @param interpolationType One of the integer
  116. * interpolation type constants defined by this class:
  117. * {@link #TYPE_NEAREST_NEIGHBOR TYPE_NEAREST_NEIGHBOR},
  118. * {@link #TYPE_BILINEAR TYPE_BILINEAR},
  119. * {@link #TYPE_BICUBIC TYPE_BICUBIC}.
  120. * @throws ImagingOpException if the transform is non-invertible.
  121. */
  122. public AffineTransformOp(AffineTransform xform, int interpolationType) {
  123. validateTransform(xform);
  124. this.xform = (AffineTransform)xform.clone();
  125. switch(interpolationType) {
  126. case TYPE_NEAREST_NEIGHBOR:
  127. case TYPE_BILINEAR:
  128. case TYPE_BICUBIC:
  129. break;
  130. default:
  131. throw new IllegalArgumentException("Unknown interpolation type: "+
  132. interpolationType);
  133. }
  134. this.interpolationType = interpolationType;
  135. }
  136. /**
  137. * Returns the interpolation type used by this op.
  138. * @return the interpolation type.
  139. * @see #TYPE_NEAREST_NEIGHBOR
  140. * @see #TYPE_BILINEAR
  141. * @see #TYPE_BICUBIC
  142. */
  143. public final int getInterpolationType() {
  144. return interpolationType;
  145. }
  146. /**
  147. * Transforms the source <CODE>BufferedImage</CODE> and stores the results
  148. * in the destination <CODE>BufferedImage</CODE>.
  149. * If the color models for the two images do not match, a color
  150. * conversion into the destination color model is performed.
  151. * If the destination image is null,
  152. * a <CODE>BufferedImage</CODE> is created with the source
  153. * <CODE>ColorModel</CODE>.
  154. * <p>
  155. * The coordinates of the rectangle returned by
  156. * <code>getBounds2D(BufferedImage)</code>
  157. * are not necessarily the same as the coordinates of the
  158. * <code>BufferedImage</code> returned by this method. If the
  159. * upper-left corner coordinates of the rectangle are
  160. * negative then this part of the rectangle is not drawn. If the
  161. * upper-left corner coordinates of the rectangle are positive
  162. * then the filtered image is drawn at that position in the
  163. * destination <code>BufferedImage</code>.
  164. * <p>
  165. * An <CODE>IllegalArgumentException</CODE> is thrown if the source is
  166. * the same as the destination.
  167. *
  168. * @param src The <CODE>BufferedImage</CODE> to transform.
  169. * @param dst The <CODE>BufferedImage</CODE> in which to store the results
  170. * of the transformation.
  171. *
  172. * @return The filtered <CODE>BufferedImage</CODE>.
  173. * @throws IllegalArgumentException if <code>src</code> and
  174. * <code>dst</code> are the same
  175. * @throws ImagingOpException if the image cannot be transformed
  176. * because of a data-processing error that might be
  177. * caused by an invalid image format, tile format, or
  178. * image-processing operation, or any other unsupported
  179. * operation.
  180. */
  181. public final BufferedImage filter(BufferedImage src, BufferedImage dst) {
  182. if (src == null) {
  183. throw new NullPointerException("src image is null");
  184. }
  185. if (src == dst) {
  186. throw new IllegalArgumentException("src image cannot be the "+
  187. "same as the dst image");
  188. }
  189. boolean needToConvert = false;
  190. ColorModel srcCM = src.getColorModel();
  191. ColorModel dstCM;
  192. BufferedImage origDst = dst;
  193. if (dst == null) {
  194. dst = createCompatibleDestImage(src, null);
  195. dstCM = srcCM;
  196. origDst = dst;
  197. }
  198. else {
  199. dstCM = dst.getColorModel();
  200. if (srcCM.getColorSpace().getType() !=
  201. dstCM.getColorSpace().getType())
  202. {
  203. int type = xform.getType();
  204. boolean needTrans = ((type&
  205. (xform.TYPE_MASK_ROTATION|
  206. xform.TYPE_GENERAL_TRANSFORM))
  207. != 0);
  208. if (! needTrans && type != xform.TYPE_TRANSLATION && type != xform.TYPE_IDENTITY)
  209. {
  210. double[] mtx = new double[4];
  211. xform.getMatrix(mtx);
  212. // Check out the matrix. A non-integral scale will force ARGB
  213. // since the edge conditions can't be guaranteed.
  214. needTrans = (mtx[0] != (int)mtx[0] || mtx[3] != (int)mtx[3]);
  215. }
  216. if (needTrans &&
  217. srcCM.getTransparency() == Transparency.OPAQUE)
  218. {
  219. // Need to convert first
  220. ColorConvertOp ccop = new ColorConvertOp(hints);
  221. BufferedImage tmpSrc = null;
  222. int sw = src.getWidth();
  223. int sh = src.getHeight();
  224. if (dstCM.getTransparency() == Transparency.OPAQUE) {
  225. tmpSrc = new BufferedImage(sw, sh,
  226. BufferedImage.TYPE_INT_ARGB);
  227. }
  228. else {
  229. WritableRaster r =
  230. dstCM.createCompatibleWritableRaster(sw, sh);
  231. tmpSrc = new BufferedImage(dstCM, r,
  232. dstCM.isAlphaPremultiplied(),
  233. null);
  234. }
  235. src = ccop.filter(src, tmpSrc);
  236. }
  237. else {
  238. needToConvert = true;
  239. dst = createCompatibleDestImage(src, null);
  240. }
  241. }
  242. }
  243. if (interpolationType != TYPE_NEAREST_NEIGHBOR &&
  244. dst.getColorModel() instanceof IndexColorModel) {
  245. dst = new BufferedImage(dst.getWidth(), dst.getHeight(),
  246. BufferedImage.TYPE_INT_ARGB);
  247. }
  248. if (ImagingLib.filter(this, src, dst) == null) {
  249. throw new ImagingOpException ("Unable to transform src image");
  250. }
  251. if (needToConvert) {
  252. ColorConvertOp ccop = new ColorConvertOp(hints);
  253. ccop.filter(dst, origDst);
  254. }
  255. else if (origDst != dst) {
  256. java.awt.Graphics2D g = origDst.createGraphics();
  257. try {
  258. g.setComposite(AlphaComposite.Src);
  259. g.drawImage(dst, 0, 0, null);
  260. } finally {
  261. g.dispose();
  262. }
  263. }
  264. return origDst;
  265. }
  266. /**
  267. * Transforms the source <CODE>Raster</CODE> and stores the results in
  268. * the destination <CODE>Raster</CODE>. This operation performs the
  269. * transform band by band.
  270. * <p>
  271. * If the destination <CODE>Raster</CODE> is null, a new
  272. * <CODE>Raster</CODE> is created.
  273. * An <CODE>IllegalArgumentException</CODE> may be thrown if the source is
  274. * the same as the destination or if the number of bands in
  275. * the source is not equal to the number of bands in the
  276. * destination.
  277. * <p>
  278. * The coordinates of the rectangle returned by
  279. * <code>getBounds2D(Raster)</code>
  280. * are not necessarily the same as the coordinates of the
  281. * <code>WritableRaster</code> returned by this method. If the
  282. * upper-left corner coordinates of rectangle are negative then
  283. * this part of the rectangle is not drawn. If the coordinates
  284. * of the rectangle are positive then the filtered image is drawn at
  285. * that position in the destination <code>Raster</code>.
  286. * <p>
  287. * @param src The <CODE>Raster</CODE> to transform.
  288. * @param dst The <CODE>Raster</CODE> in which to store the results of the
  289. * transformation.
  290. *
  291. * @return The transformed <CODE>Raster</CODE>.
  292. *
  293. * @throws ImagingOpException if the raster cannot be transformed
  294. * because of a data-processing error that might be
  295. * caused by an invalid image format, tile format, or
  296. * image-processing operation, or any other unsupported
  297. * operation.
  298. */
  299. public final WritableRaster filter(Raster src, WritableRaster dst) {
  300. if (src == null) {
  301. throw new NullPointerException("src image is null");
  302. }
  303. if (dst == null) {
  304. dst = createCompatibleDestRaster(src);
  305. }
  306. if (src == dst) {
  307. throw new IllegalArgumentException("src image cannot be the "+
  308. "same as the dst image");
  309. }
  310. if (src.getNumBands() != dst.getNumBands()) {
  311. throw new IllegalArgumentException("Number of src bands ("+
  312. src.getNumBands()+
  313. ") does not match number of "+
  314. " dst bands ("+
  315. dst.getNumBands()+")");
  316. }
  317. if (ImagingLib.filter(this, src, dst) == null) {
  318. throw new ImagingOpException ("Unable to transform src image");
  319. }
  320. return dst;
  321. }
  322. /**
  323. * Returns the bounding box of the transformed destination. The
  324. * rectangle returned is the actual bounding box of the
  325. * transformed points. The coordinates of the upper-left corner
  326. * of the returned rectangle might not be (0, 0).
  327. *
  328. * @param src The <CODE>BufferedImage</CODE> to be transformed.
  329. *
  330. * @return The <CODE>Rectangle2D</CODE> representing the destination's
  331. * bounding box.
  332. */
  333. public final Rectangle2D getBounds2D (BufferedImage src) {
  334. return getBounds2D(src.getRaster());
  335. }
  336. /**
  337. * Returns the bounding box of the transformed destination. The
  338. * rectangle returned will be the actual bounding box of the
  339. * transformed points. The coordinates of the upper-left corner
  340. * of the returned rectangle might not be (0, 0).
  341. *
  342. * @param src The <CODE>Raster</CODE> to be transformed.
  343. *
  344. * @return The <CODE>Rectangle2D</CODE> representing the destination's
  345. * bounding box.
  346. */
  347. public final Rectangle2D getBounds2D (Raster src) {
  348. int w = src.getWidth();
  349. int h = src.getHeight();
  350. // Get the bounding box of the src and transform the corners
  351. float[] pts = {0, 0, w, 0, w, h, 0, h};
  352. xform.transform(pts, 0, pts, 0, 4);
  353. // Get the min, max of the dst
  354. float fmaxX = pts[0];
  355. float fmaxY = pts[1];
  356. float fminX = pts[0];
  357. float fminY = pts[1];
  358. int maxX;
  359. int maxY;
  360. for (int i=2; i < 8; i+=2) {
  361. if (pts[i] > fmaxX) {
  362. fmaxX = pts[i];
  363. }
  364. else if (pts[i] < fminX) {
  365. fminX = pts[i];
  366. }
  367. if (pts[i+1] > fmaxY) {
  368. fmaxY = pts[i+1];
  369. }
  370. else if (pts[i+1] < fminY) {
  371. fminY = pts[i+1];
  372. }
  373. }
  374. return new Rectangle2D.Float(fminX, fminY, fmaxX-fminX, fmaxY-fminY);
  375. }
  376. /**
  377. * Creates a zeroed destination image with the correct size and number of
  378. * bands. A <CODE>RasterFormatException</CODE> may be thrown if the
  379. * transformed width or height is equal to 0.
  380. * <p>
  381. * If <CODE>destCM</CODE> is null,
  382. * an appropriate <CODE>ColorModel</CODE> is used; this
  383. * <CODE>ColorModel</CODE> may have
  384. * an alpha channel even if the source <CODE>ColorModel</CODE> is opaque.
  385. *
  386. * @param src The <CODE>BufferedImage</CODE> to be transformed.
  387. * @param destCM <CODE>ColorModel</CODE> of the destination. If null,
  388. * an appropriate <CODE>ColorModel</CODE> is used.
  389. *
  390. * @return The zeroed destination image.
  391. */
  392. public BufferedImage createCompatibleDestImage (BufferedImage src,
  393. ColorModel destCM) {
  394. BufferedImage image;
  395. Rectangle r = getBounds2D(src).getBounds();
  396. // If r.x (or r.y) is < 0, then we want to only create an image
  397. // that is in the positive range.
  398. // If r.x (or r.y) is > 0, then we need to create an image that
  399. // includes the translation.
  400. int w = r.x + r.width;
  401. int h = r.y + r.height;
  402. if (w <= 0) {
  403. throw new RasterFormatException("Transformed width ("+w+
  404. ") is less than or equal to 0.");
  405. }
  406. if (h <= 0) {
  407. throw new RasterFormatException("Transformed height ("+h+
  408. ") is less than or equal to 0.");
  409. }
  410. if (destCM == null) {
  411. ColorModel cm = src.getColorModel();
  412. if (interpolationType != TYPE_NEAREST_NEIGHBOR &&
  413. (cm instanceof IndexColorModel ||
  414. cm.getTransparency() == Transparency.OPAQUE))
  415. {
  416. image = new BufferedImage(w, h,
  417. BufferedImage.TYPE_INT_ARGB);
  418. }
  419. else {
  420. image = new BufferedImage(cm,
  421. src.getRaster().createCompatibleWritableRaster(w,h),
  422. cm.isAlphaPremultiplied(), null);
  423. }
  424. }
  425. else {
  426. image = new BufferedImage(destCM,
  427. destCM.createCompatibleWritableRaster(w,h),
  428. destCM.isAlphaPremultiplied(), null);
  429. }
  430. return image;
  431. }
  432. /**
  433. * Creates a zeroed destination <CODE>Raster</CODE> with the correct size
  434. * and number of bands. A <CODE>RasterFormatException</CODE> may be thrown
  435. * if the transformed width or height is equal to 0.
  436. *
  437. * @param src The <CODE>Raster</CODE> to be transformed.
  438. *
  439. * @return The zeroed destination <CODE>Raster</CODE>.
  440. */
  441. public WritableRaster createCompatibleDestRaster (Raster src) {
  442. Rectangle2D r = getBounds2D(src);
  443. return src.createCompatibleWritableRaster((int)r.getX(),
  444. (int)r.getY(),
  445. (int)r.getWidth(),
  446. (int)r.getHeight());
  447. }
  448. /**
  449. * Returns the location of the corresponding destination point given a
  450. * point in the source. If <CODE>dstPt</CODE> is specified, it
  451. * is used to hold the return value.
  452. *
  453. * @param srcPt The <code>Point2D</code> that represents the source
  454. * point.
  455. * @param dstPt The <CODE>Point2D</CODE> in which to store the result.
  456. *
  457. * @return The <CODE>Point2D</CODE> in the destination that corresponds to
  458. * the specified point in the source.
  459. */
  460. public final Point2D getPoint2D (Point2D srcPt, Point2D dstPt) {
  461. return xform.transform (srcPt, dstPt);
  462. }
  463. /**
  464. * Returns the affine transform used by this transform operation.
  465. *
  466. * @return The <CODE>AffineTransform</CODE> associated with this op.
  467. */
  468. public final AffineTransform getTransform() {
  469. return (AffineTransform) xform.clone();
  470. }
  471. /**
  472. * Returns the rendering hints used by this transform operation.
  473. *
  474. * @return The <CODE>RenderingHints</CODE> object associated with this op.
  475. */
  476. public final RenderingHints getRenderingHints() {
  477. if (hints == null) {
  478. Object val;
  479. switch(interpolationType) {
  480. case TYPE_NEAREST_NEIGHBOR:
  481. val = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
  482. break;
  483. case TYPE_BILINEAR:
  484. val = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
  485. break;
  486. case TYPE_BICUBIC:
  487. val = RenderingHints.VALUE_INTERPOLATION_BICUBIC;
  488. break;
  489. default:
  490. // Should never get here
  491. throw new InternalError("Unknown interpolation type "+
  492. interpolationType);
  493. }
  494. hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, val);
  495. }
  496. return hints;
  497. }
  498. // We need to be able to invert the transform if we want to
  499. // transform the image. If the determinant of the matrix is 0,
  500. // then we can't invert the transform.
  501. void validateTransform(AffineTransform xform) {
  502. if (Math.abs(xform.getDeterminant()) <= Double.MIN_VALUE) {
  503. throw new ImagingOpException("Unable to invert transform "+xform);
  504. }
  505. }
  506. }