RescaleOp.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /* Copyright (C) 2004, 2006 Free Software Foundation
  2. This file is part of GNU Classpath.
  3. GNU Classpath is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. GNU Classpath is distributed in the hope that it will be useful, but
  8. WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with GNU Classpath; see the file COPYING. If not, write to the
  13. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  14. 02110-1301 USA.
  15. Linking this library statically or dynamically with other modules is
  16. making a combined work based on this library. Thus, the terms and
  17. conditions of the GNU General Public License cover the whole
  18. combination.
  19. As a special exception, the copyright holders of this library give you
  20. permission to link this library with independent modules to produce an
  21. executable, regardless of the license terms of these independent
  22. modules, and to copy and distribute the resulting executable under
  23. terms of your choice, provided that you also meet, for each linked
  24. independent module, the terms and conditions of the license of that
  25. module. An independent module is a module which is not derived from
  26. or based on this library. If you modify this library, you may extend
  27. this exception to your version of the library, but you are not
  28. obligated to do so. If you do not wish to do so, delete this
  29. exception statement from your version. */
  30. package java.awt.image;
  31. import java.awt.RenderingHints;
  32. import java.awt.geom.Point2D;
  33. import java.awt.geom.Rectangle2D;
  34. import java.util.Arrays;
  35. /**
  36. * RescaleOp is a filter that changes each pixel by a scaling factor and offset.
  37. *
  38. * For filtering Rasters, either one scaling factor and offset can be specified,
  39. * which will be applied to all bands; or a scaling factor and offset can be
  40. * specified for each band.
  41. *
  42. * For BufferedImages, the scaling may apply to both color and alpha components.
  43. * If only one scaling factor is provided, or if the number of factors provided
  44. * equals the number of color components, the scaling is performed on all color
  45. * components. Otherwise, the scaling is performed on all components including
  46. * alpha. Alpha premultiplication is ignored.
  47. *
  48. * After filtering, if color conversion is necessary, the conversion happens,
  49. * taking alpha premultiplication into account.
  50. *
  51. * @author Jerry Quinn (jlquinn@optonline.net)
  52. * @author Francis Kung (fkung@redhat.com)
  53. */
  54. public class RescaleOp implements BufferedImageOp, RasterOp
  55. {
  56. private float[] scale;
  57. private float[] offsets;
  58. private RenderingHints hints = null;
  59. /**
  60. * Create a new RescaleOp object using the given scale factors and offsets.
  61. *
  62. * The length of the arrays must be equal to the number of bands (or number of
  63. * data or color components) of the raster/image that this Op will be used on,
  64. * otherwise an IllegalArgumentException will be thrown when calling the
  65. * filter method.
  66. *
  67. * @param scaleFactors an array of scale factors.
  68. * @param offsets an array of offsets.
  69. * @param hints any rendering hints to use (can be null).
  70. * @throws NullPointerException if the scaleFactors or offsets array is null.
  71. */
  72. public RescaleOp(float[] scaleFactors,
  73. float[] offsets,
  74. RenderingHints hints)
  75. {
  76. int length = Math.min(scaleFactors.length, offsets.length);
  77. scale = new float[length];
  78. System.arraycopy(scaleFactors, 0, this.scale, 0, length);
  79. this.offsets = new float[length];
  80. System.arraycopy(offsets, 0, this.offsets, 0, length);
  81. this.hints = hints;
  82. }
  83. /**
  84. * Create a new RescaleOp object using the given scale factor and offset.
  85. *
  86. * The same scale factor and offset will be used on all bands/components.
  87. *
  88. * @param scaleFactor the scale factor to use.
  89. * @param offset the offset to use.
  90. * @param hints any rendering hints to use (can be null).
  91. */
  92. public RescaleOp(float scaleFactor,
  93. float offset,
  94. RenderingHints hints)
  95. {
  96. scale = new float[]{ scaleFactor };
  97. offsets = new float[]{offset};
  98. this.hints = hints;
  99. }
  100. /**
  101. * Returns the scaling factors. This method accepts an optional array, which
  102. * will be used to store the factors if not null (this avoids allocating a
  103. * new array). If this array is too small to hold all the scaling factors,
  104. * the array will be filled and the remaining factors discarded.
  105. *
  106. * @param scaleFactors array to store the scaling factors in (can be null).
  107. * @return an array of scaling factors.
  108. */
  109. public final float[] getScaleFactors(float[] scaleFactors)
  110. {
  111. if (scaleFactors == null)
  112. scaleFactors = new float[scale.length];
  113. System.arraycopy(scale, 0, scaleFactors, 0, Math.min(scale.length,
  114. scaleFactors.length));
  115. return scaleFactors;
  116. }
  117. /**
  118. * Returns the offsets. This method accepts an optional array, which
  119. * will be used to store the offsets if not null (this avoids allocating a
  120. * new array). If this array is too small to hold all the offsets, the array
  121. * will be filled and the remaining factors discarded.
  122. *
  123. * @param offsets array to store the offsets in (can be null).
  124. * @return an array of offsets.
  125. */
  126. public final float[] getOffsets(float[] offsets)
  127. {
  128. if (offsets == null)
  129. offsets = new float[this.offsets.length];
  130. System.arraycopy(this.offsets, 0, offsets, 0, Math.min(this.offsets.length,
  131. offsets.length));
  132. return offsets;
  133. }
  134. /**
  135. * Returns the number of scaling factors / offsets.
  136. *
  137. * @return the number of scaling factors / offsets.
  138. */
  139. public final int getNumFactors()
  140. {
  141. return scale.length;
  142. }
  143. /* (non-Javadoc)
  144. * @see java.awt.image.BufferedImageOp#getRenderingHints()
  145. */
  146. public final RenderingHints getRenderingHints()
  147. {
  148. return hints;
  149. }
  150. /**
  151. * Converts the source image using the scale factors and offsets specified in
  152. * the constructor. The resulting image is stored in the destination image if
  153. * one is provided; otherwise a new BufferedImage is created and returned.
  154. *
  155. * The source image cannot use an IndexColorModel, and the destination image
  156. * (if one is provided) must have the same size.
  157. *
  158. * If the final value of a sample is beyond the range of the color model, it
  159. * will be clipped to the appropriate maximum / minimum.
  160. *
  161. * @param src The source image.
  162. * @param dst The destination image.
  163. * @throws IllegalArgumentException if the rasters and/or color spaces are
  164. * incompatible.
  165. * @return The rescaled image.
  166. */
  167. public final BufferedImage filter(BufferedImage src, BufferedImage dst)
  168. {
  169. // Initial checks
  170. if (scale.length != 1
  171. && scale.length != src.getColorModel().getNumComponents()
  172. && (scale.length != src.getColorModel().getNumColorComponents()))
  173. throw new IllegalArgumentException("Source image has wrong number of "
  174. + "bands for these scaling factors.");
  175. if (dst == null)
  176. dst = createCompatibleDestImage(src, null);
  177. else if (src.getHeight() != dst.getHeight()
  178. || src.getWidth() != dst.getWidth())
  179. throw new IllegalArgumentException("Source and destination images are "
  180. + "different sizes.");
  181. // Prepare for possible colorspace conversion
  182. BufferedImage dst2 = dst;
  183. if (dst.getColorModel().getColorSpace().getType() != src.getColorModel().getColorSpace().getType())
  184. dst2 = createCompatibleDestImage(src, src.getColorModel());
  185. // Figure out how many bands to scale
  186. int numBands = scale.length;
  187. if (scale.length == 1)
  188. numBands = src.getColorModel().getNumColorComponents();
  189. boolean[] bands = new boolean[numBands];
  190. // this assumes the alpha, if present, is the last band
  191. Arrays.fill(bands, true);
  192. // Perform rescaling
  193. filter(src.getRaster(), dst2.getRaster(), bands);
  194. // Copy alpha band if needed (ie if it exists and wasn't scaled)
  195. // NOTE: This assumes the alpha component is the last band!
  196. if (src.getColorModel().hasAlpha()
  197. && numBands == src.getColorModel().getNumColorComponents())
  198. {
  199. dst2.getRaster().setSamples(0, 0, src.getWidth(), src.getHeight(),
  200. numBands,
  201. src.getRaster().getSamples(0, 0,
  202. src.getWidth(),
  203. src.getHeight(),
  204. numBands,
  205. (int[]) null));
  206. }
  207. // Perform colorspace conversion if needed
  208. if (dst != dst2)
  209. new ColorConvertOp(hints).filter(dst2, dst);
  210. return dst;
  211. }
  212. /* (non-Javadoc)
  213. * @see java.awt.image.RasterOp#filter(java.awt.image.Raster, java.awt.image.WritableRaster)
  214. */
  215. public final WritableRaster filter(Raster src, WritableRaster dest)
  216. {
  217. // Required sanity checks
  218. if (scale.length != 1 && scale.length != src.numBands)
  219. throw new IllegalArgumentException("Number of rasters is incompatible "
  220. + "with the number of scaling "
  221. + "factors provided.");
  222. if (dest == null)
  223. dest = src.createCompatibleWritableRaster();
  224. else if (src.getHeight() != dest.getHeight()
  225. || src.getWidth() != dest.getWidth())
  226. throw new IllegalArgumentException("Source and destination rasters are "
  227. + "different sizes.");
  228. else if (src.numBands != dest.numBands)
  229. throw new IllegalArgumentException("Source and destination rasters "
  230. + "are incompatible.");
  231. // Filter all bands
  232. boolean[] bands = new boolean[src.getNumBands()];
  233. Arrays.fill(bands, true);
  234. return filter(src, dest, bands);
  235. }
  236. /**
  237. * Perform raster-based filtering on a selected number of bands.
  238. *
  239. * The length of the bands array should equal the number of bands; a true
  240. * element indicates filtering should happen on the corresponding band, while
  241. * a false element will skip the band.
  242. *
  243. * The rasters are assumed to be compatible and non-null.
  244. *
  245. * @param src the source raster.
  246. * @param dest the destination raster.
  247. * @param bands an array indicating which bands to filter.
  248. * @throws NullPointerException if any parameter is null.
  249. * @throws ArrayIndexOutOfBoundsException if the bands array is too small.
  250. * @return the destination raster.
  251. */
  252. private WritableRaster filter(Raster src, WritableRaster dest, boolean[] bands)
  253. {
  254. int[] values = new int[src.getHeight() * src.getWidth()];
  255. float scaleFactor, offset;
  256. // Find max sample value, to be used for clipping later
  257. int[] maxValue = src.getSampleModel().getSampleSize();
  258. for (int i = 0; i < maxValue.length; i++)
  259. maxValue[i] = (int)Math.pow(2, maxValue[i]) - 1;
  260. // TODO: can this be optimized further?
  261. // Filter all samples of all requested bands
  262. for (int band = 0; band < bands.length; band++)
  263. if (bands[band])
  264. {
  265. values = src.getSamples(src.getMinX(), src.getMinY(), src.getWidth(),
  266. src.getHeight(), band, values);
  267. if (scale.length == 1)
  268. {
  269. scaleFactor = scale[0];
  270. offset = offsets[0];
  271. }
  272. else
  273. {
  274. scaleFactor = scale[band];
  275. offset = offsets[band];
  276. }
  277. for (int i = 0; i < values.length; i++)
  278. {
  279. values[i] = (int) (values[i] * scaleFactor + offset);
  280. // Clip if needed
  281. if (values[i] < 0)
  282. values[i] = 0;
  283. if (values[i] > maxValue[band])
  284. values[i] = maxValue[band];
  285. }
  286. dest.setSamples(dest.getMinX(), dest.getMinY(), dest.getWidth(),
  287. dest.getHeight(), band, values);
  288. }
  289. return dest;
  290. }
  291. /*
  292. * (non-Javadoc)
  293. *
  294. * @see java.awt.image.BufferedImageOp#createCompatibleDestImage(java.awt.image.BufferedImage,
  295. * java.awt.image.ColorModel)
  296. */
  297. public BufferedImage createCompatibleDestImage(BufferedImage src,
  298. ColorModel dstCM)
  299. {
  300. if (dstCM == null)
  301. return new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
  302. return new BufferedImage(dstCM,
  303. src.getRaster().createCompatibleWritableRaster(),
  304. src.isAlphaPremultiplied(), null);
  305. }
  306. /* (non-Javadoc)
  307. * @see java.awt.image.RasterOp#createCompatibleDestRaster(java.awt.image.Raster)
  308. */
  309. public WritableRaster createCompatibleDestRaster(Raster src)
  310. {
  311. return src.createCompatibleWritableRaster();
  312. }
  313. /* (non-Javadoc)
  314. * @see java.awt.image.BufferedImageOp#getBounds2D(java.awt.image.BufferedImage)
  315. */
  316. public final Rectangle2D getBounds2D(BufferedImage src)
  317. {
  318. return src.getRaster().getBounds();
  319. }
  320. /* (non-Javadoc)
  321. * @see java.awt.image.RasterOp#getBounds2D(java.awt.image.Raster)
  322. */
  323. public final Rectangle2D getBounds2D(Raster src)
  324. {
  325. return src.getBounds();
  326. }
  327. /* (non-Javadoc)
  328. * @see java.awt.image.BufferedImageOp#getPoint2D(java.awt.geom.Point2D, java.awt.geom.Point2D)
  329. */
  330. public final Point2D getPoint2D(Point2D src, Point2D dst)
  331. {
  332. if (dst == null)
  333. dst = (Point2D) src.clone();
  334. else
  335. dst.setLocation(src);
  336. return dst;
  337. }
  338. }