1. /*
  2. * @(#)AffineTransformOp.java 1.60 03/01/23
  3. *
  4. * Copyright 2003 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. private 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. * @throws ImagingOpException if the transform is non-invertible.
  120. */
  121. public AffineTransformOp(AffineTransform xform, int interpolationType) {
  122. validateTransform(xform);
  123. this.xform = (AffineTransform)xform.clone();
  124. switch(interpolationType) {
  125. case TYPE_NEAREST_NEIGHBOR:
  126. case TYPE_BILINEAR:
  127. case TYPE_BICUBIC:
  128. break;
  129. default:
  130. throw new IllegalArgumentException("Unknown interpolation type: "+
  131. interpolationType);
  132. }
  133. this.interpolationType = interpolationType;
  134. }
  135. /**
  136. * Returns the interpolation type used by this op.
  137. * @return the interpolation type.
  138. * @see #TYPE_NEAREST_NEIGHBOR
  139. * @see #TYPE_BILINEAR
  140. */
  141. public final int getInterpolationType() {
  142. return interpolationType;
  143. }
  144. /**
  145. * Transforms the source <CODE>BufferedImage</CODE> and stores the results
  146. * in the destination <CODE>BufferedImage</CODE>.
  147. * If the color models for the two images do not match, a color
  148. * conversion into the destination color model is performed.
  149. * If the destination image is null,
  150. * a <CODE>BufferedImage</CODE> is created with the source
  151. * <CODE>ColorModel</CODE>.
  152. * <p>
  153. * The coordinates of the rectangle returned by
  154. * <code>getBounds2D(BufferedImage)</code>
  155. * are not necessarily the same as the coordinates of the
  156. * <code>BufferedImage</code> returned by this method. If the
  157. * upper-left corner coordinates of the rectangle are
  158. * negative then this part of the rectangle is not drawn. If the
  159. * upper-left corner coordinates of the rectangle are positive
  160. * then the filtered image is drawn at that position in the
  161. * destination <code>BufferedImage</code>.
  162. * <p>
  163. * An <CODE>IllegalArgumentException</CODE> is thrown if the source is
  164. * the same as the destination.
  165. *
  166. * @param src The <CODE>BufferedImage</CODE> to transform.
  167. * @param dst The <CODE>BufferedImage</CODE> in which to store the results
  168. * of the transformation.
  169. *
  170. * @return The filtered <CODE>BufferedImage</CODE>.
  171. * @throws IllegalArgumentException if <code>src</code> and
  172. * <code>dst</code> are the same
  173. * @throws ImagingOpException if the image cannot be transformed
  174. * because of a data-processing error that might be
  175. * caused by an invalid image format, tile format, or
  176. * image-processing operation, or any other unsupported
  177. * operation.
  178. */
  179. public final BufferedImage filter(BufferedImage src, BufferedImage dst) {
  180. if (src == null) {
  181. throw new NullPointerException("src image is null");
  182. }
  183. if (src == dst) {
  184. throw new IllegalArgumentException("src image cannot be the "+
  185. "same as the dst image");
  186. }
  187. boolean needToConvert = false;
  188. ColorModel srcCM = src.getColorModel();
  189. ColorModel dstCM;
  190. BufferedImage origDst = dst;
  191. if (dst == null) {
  192. dst = createCompatibleDestImage(src, null);
  193. dstCM = srcCM;
  194. origDst = dst;
  195. }
  196. else {
  197. dstCM = dst.getColorModel();
  198. if (srcCM.getColorSpace().getType() !=
  199. dstCM.getColorSpace().getType())
  200. {
  201. int type = xform.getType();
  202. boolean needTrans = ((type&
  203. (xform.TYPE_MASK_ROTATION|
  204. xform.TYPE_GENERAL_TRANSFORM))
  205. != 0);
  206. if (! needTrans && type != xform.TYPE_TRANSLATION && type != xform.TYPE_IDENTITY)
  207. {
  208. double[] mtx = new double[4];
  209. xform.getMatrix(mtx);
  210. // Check out the matrix. A non-integral scale will force ARGB
  211. // since the edge conditions can't be guaranteed.
  212. needTrans = (mtx[0] != (int)mtx[0] || mtx[3] != (int)mtx[3]);
  213. }
  214. if (needTrans &&
  215. srcCM.getTransparency() == Transparency.OPAQUE)
  216. {
  217. // Need to convert first
  218. ColorConvertOp ccop = new ColorConvertOp(hints);
  219. BufferedImage tmpSrc = null;
  220. int sw = src.getWidth();
  221. int sh = src.getHeight();
  222. if (dstCM.getTransparency() == Transparency.OPAQUE) {
  223. tmpSrc = new BufferedImage(sw, sh,
  224. BufferedImage.TYPE_INT_ARGB);
  225. }
  226. else {
  227. WritableRaster r =
  228. dstCM.createCompatibleWritableRaster(sw, sh);
  229. tmpSrc = new BufferedImage(dstCM, r,
  230. dstCM.isAlphaPremultiplied(),
  231. null);
  232. }
  233. src = ccop.filter(src, tmpSrc);
  234. }
  235. else {
  236. needToConvert = true;
  237. dst = createCompatibleDestImage(src, null);
  238. }
  239. }
  240. }
  241. if (interpolationType != TYPE_NEAREST_NEIGHBOR &&
  242. dst.getColorModel() instanceof IndexColorModel) {
  243. dst = new BufferedImage(dst.getWidth(), dst.getHeight(),
  244. BufferedImage.TYPE_INT_ARGB);
  245. }
  246. if (ImagingLib.filter(this, src, dst) == null) {
  247. throw new ImagingOpException ("Unable to transform src image");
  248. }
  249. if (needToConvert) {
  250. ColorConvertOp ccop = new ColorConvertOp(hints);
  251. ccop.filter(dst, origDst);
  252. }
  253. else if (origDst != dst) {
  254. java.awt.Graphics2D g = origDst.createGraphics();
  255. try {
  256. g.setComposite(AlphaComposite.Src);
  257. g.drawImage(dst, 0, 0, null);
  258. } finally {
  259. g.dispose();
  260. }
  261. }
  262. return origDst;
  263. }
  264. /**
  265. * Transforms the source <CODE>Raster</CODE> and stores the results in
  266. * the destination <CODE>Raster</CODE>. This operation performs the
  267. * transform band by band.
  268. * <p>
  269. * If the destination <CODE>Raster</CODE> is null, a new
  270. * <CODE>Raster</CODE> is created.
  271. * An <CODE>IllegalArgumentException</CODE> may be thrown if the source is
  272. * the same as the destination or if the number of bands in
  273. * the source is not equal to the number of bands in the
  274. * destination.
  275. * <p>
  276. * The coordinates of the rectangle returned by
  277. * <code>getBounds2D(Raster)</code>
  278. * are not necessarily the same as the coordinates of the
  279. * <code>WritableRaster</code> returned by this method. If the
  280. * upper-left corner coordinates of rectangle are negative then
  281. * this part of the rectangle is not drawn. If the coordinates
  282. * of the rectangle are positive then the filtered image is drawn at
  283. * that position in the destination <code>Raster</code>.
  284. * <p>
  285. * @param src The <CODE>Raster</CODE> to transform.
  286. * @param dst The <CODE>Raster</CODE> in which to store the results of the
  287. * transformation.
  288. *
  289. * @return The transformed <CODE>Raster</CODE>.
  290. *
  291. * @throws ImagingOpException if the raster cannot be transformed
  292. * because of a data-processing error that might be
  293. * caused by an invalid image format, tile format, or
  294. * image-processing operation, or any other unsupported
  295. * operation.
  296. */
  297. public final WritableRaster filter(Raster src, WritableRaster dst) {
  298. if (src == null) {
  299. throw new NullPointerException("src image is null");
  300. }
  301. if (dst == null) {
  302. dst = createCompatibleDestRaster(src);
  303. }
  304. if (src == dst) {
  305. throw new IllegalArgumentException("src image cannot be the "+
  306. "same as the dst image");
  307. }
  308. if (src.getNumBands() != dst.getNumBands()) {
  309. throw new IllegalArgumentException("Number of src bands ("+
  310. src.getNumBands()+
  311. ") does not match number of "+
  312. " dst bands ("+
  313. dst.getNumBands()+")");
  314. }
  315. if (ImagingLib.filter(this, src, dst) == null) {
  316. throw new ImagingOpException ("Unable to transform src image");
  317. }
  318. return dst;
  319. }
  320. /**
  321. * Returns the bounding box of the transformed destination. The
  322. * rectangle returned is the actual bounding box of the
  323. * transformed points. The coordinates of the upper-left corner
  324. * of the returned rectangle might not be (0, 0).
  325. *
  326. * @param src The <CODE>BufferedImage</CODE> to be transformed.
  327. *
  328. * @return The <CODE>Rectangle2D</CODE> representing the destination's
  329. * bounding box.
  330. */
  331. public final Rectangle2D getBounds2D (BufferedImage src) {
  332. return getBounds2D(src.getRaster());
  333. }
  334. /**
  335. * Returns the bounding box of the transformed destination. The
  336. * rectangle returned will be the actual bounding box of the
  337. * transformed points. The coordinates of the upper-left corner
  338. * of the returned rectangle might not be (0, 0).
  339. *
  340. * @param src The <CODE>Raster</CODE> to be transformed.
  341. *
  342. * @return The <CODE>Rectangle2D</CODE> representing the destination's
  343. * bounding box.
  344. */
  345. public final Rectangle2D getBounds2D (Raster src) {
  346. int w = src.getWidth();
  347. int h = src.getHeight();
  348. // Get the bounding box of the src and transform the corners
  349. float[] pts = {0, 0, w, 0, w, h, 0, h};
  350. xform.transform(pts, 0, pts, 0, 4);
  351. // Get the min, max of the dst
  352. float fmaxX = pts[0];
  353. float fmaxY = pts[1];
  354. float fminX = pts[0];
  355. float fminY = pts[1];
  356. int maxX;
  357. int maxY;
  358. for (int i=2; i < 8; i+=2) {
  359. if (pts[i] > fmaxX) {
  360. fmaxX = pts[i];
  361. }
  362. else if (pts[i] < fminX) {
  363. fminX = pts[i];
  364. }
  365. if (pts[i+1] > fmaxY) {
  366. fmaxY = pts[i+1];
  367. }
  368. else if (pts[i+1] < fminY) {
  369. fminY = pts[i+1];
  370. }
  371. }
  372. return new Rectangle2D.Float(fminX, fminY, fmaxX-fminX, fmaxY-fminY);
  373. }
  374. /**
  375. * Creates a zeroed destination image with the correct size and number of
  376. * bands. A <CODE>RasterFormatException</CODE> may be thrown if the
  377. * transformed width or height is equal to 0.
  378. * <p>
  379. * If <CODE>destCM</CODE> is null,
  380. * an appropriate <CODE>ColorModel</CODE> is used; this
  381. * <CODE>ColorModel</CODE> may have
  382. * an alpha channel even if the source <CODE>ColorModel</CODE> is opaque.
  383. *
  384. * @param src The <CODE>BufferedImage</CODE> to be transformed.
  385. * @param destCM <CODE>ColorModel</CODE> of the destination. If null,
  386. * an appropriate <CODE>ColorModel</CODE> is used.
  387. *
  388. * @return The zeroed destination image.
  389. */
  390. public BufferedImage createCompatibleDestImage (BufferedImage src,
  391. ColorModel destCM) {
  392. BufferedImage image;
  393. Rectangle r = getBounds2D(src).getBounds();
  394. // If r.x (or r.y) is < 0, then we want to only create an image
  395. // that is in the positive range.
  396. // If r.x (or r.y) is > 0, then we need to create an image that
  397. // includes the translation.
  398. int w = r.x + r.width;
  399. int h = r.y + r.height;
  400. if (w <= 0) {
  401. throw new RasterFormatException("Transformed width ("+w+
  402. ") is less than or equal to 0.");
  403. }
  404. if (h <= 0) {
  405. throw new RasterFormatException("Transformed height ("+h+
  406. ") is less than or equal to 0.");
  407. }
  408. if (destCM == null) {
  409. ColorModel cm = src.getColorModel();
  410. if (interpolationType != TYPE_NEAREST_NEIGHBOR &&
  411. (cm instanceof IndexColorModel ||
  412. cm.getTransparency() == Transparency.OPAQUE))
  413. {
  414. image = new BufferedImage(w, h,
  415. BufferedImage.TYPE_INT_ARGB);
  416. }
  417. else {
  418. image = new BufferedImage(cm,
  419. src.getRaster().createCompatibleWritableRaster(w,h),
  420. cm.isAlphaPremultiplied(), null);
  421. }
  422. }
  423. else {
  424. image = new BufferedImage(destCM,
  425. destCM.createCompatibleWritableRaster(w,h),
  426. destCM.isAlphaPremultiplied(), null);
  427. }
  428. return image;
  429. }
  430. /**
  431. * Creates a zeroed destination <CODE>Raster</CODE> with the correct size
  432. * and number of bands. A <CODE>RasterFormatException</CODE> may be thrown
  433. * if the transformed width or height is equal to 0.
  434. *
  435. * @param src The <CODE>Raster</CODE> to be transformed.
  436. *
  437. * @return The zeroed destination <CODE>Raster</CODE>.
  438. */
  439. public WritableRaster createCompatibleDestRaster (Raster src) {
  440. Rectangle2D r = getBounds2D(src);
  441. return src.createCompatibleWritableRaster((int)r.getX(),
  442. (int)r.getY(),
  443. (int)r.getWidth(),
  444. (int)r.getHeight());
  445. }
  446. /**
  447. * Returns the location of the corresponding destination point given a
  448. * point in the source. If <CODE>dstPt</CODE> is specified, it
  449. * is used to hold the return value.
  450. *
  451. * @param srcPt The <code>Point2D</code> that represents the source
  452. * point.
  453. * @param dstPt The <CODE>Point2D</CODE> in which to store the result.
  454. *
  455. * @return The <CODE>Point2D</CODE> in the destination that corresponds to
  456. * the specified point in the source.
  457. */
  458. public final Point2D getPoint2D (Point2D srcPt, Point2D dstPt) {
  459. return xform.transform (srcPt, dstPt);
  460. }
  461. /**
  462. * Returns the affine transform used by this transform operation.
  463. *
  464. * @return The <CODE>AffineTransform</CODE> associated with this op.
  465. */
  466. public final AffineTransform getTransform() {
  467. return (AffineTransform) xform.clone();
  468. }
  469. /**
  470. * Returns the rendering hints used by this transform operation.
  471. *
  472. * @return The <CODE>RenderingHints</CODE> object associated with this op.
  473. */
  474. public final RenderingHints getRenderingHints() {
  475. if (hints == null) {
  476. Object val;
  477. switch(interpolationType) {
  478. case TYPE_NEAREST_NEIGHBOR:
  479. val = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
  480. break;
  481. case TYPE_BILINEAR:
  482. val = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
  483. break;
  484. case TYPE_BICUBIC:
  485. val = RenderingHints.VALUE_INTERPOLATION_BICUBIC;
  486. break;
  487. default:
  488. // Should never get here
  489. throw new InternalError("Unknown interpolation type "+
  490. interpolationType);
  491. }
  492. hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, val);
  493. }
  494. return hints;
  495. }
  496. // We need to be able to invert the transform if we want to
  497. // transform the image. If the determinant of the matrix is 0,
  498. // then we can't invert the transform.
  499. void validateTransform(AffineTransform xform) {
  500. if (Math.abs(xform.getDeterminant()) <= Double.MIN_VALUE) {
  501. throw new ImagingOpException("Unable to invert transform "+xform);
  502. }
  503. }
  504. }