-
Notifications
You must be signed in to change notification settings - Fork 6.3k
Expand file tree
/
Copy pathAffineTransformOp.java
More file actions
625 lines (581 loc) · 24 KB
/
AffineTransformOp.java
File metadata and controls
625 lines (581 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/*
* Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt.image;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Point2D;
import java.awt.AlphaComposite;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.lang.annotation.Native;
import sun.awt.image.ImagingLib;
/**
* This class uses an affine transform to perform a linear mapping from
* 2D coordinates in the source image or {@code Raster} to 2D coordinates
* in the destination image or {@code Raster}.
* The type of interpolation that is used is specified through a constructor,
* either by a {@code RenderingHints} object or by one of the integer
* interpolation types defined in this class.
* <p>
* If a {@code RenderingHints} object is specified in the constructor, the
* interpolation hint and the rendering quality hint are used to set
* the interpolation type for this operation. The color rendering hint
* and the dithering hint can be used when color conversion is required.
* <p>
* Note that the following constraints have to be met:
* <ul>
* <li>The source and destination must be different.
* <li>For {@code Raster} objects, the number of bands in the source must
* be equal to the number of bands in the destination.
* </ul>
* @see AffineTransform
* @see BufferedImageFilter
* @see java.awt.RenderingHints#KEY_INTERPOLATION
* @see java.awt.RenderingHints#KEY_RENDERING
* @see java.awt.RenderingHints#KEY_COLOR_RENDERING
* @see java.awt.RenderingHints#KEY_DITHERING
*/
public class AffineTransformOp implements BufferedImageOp, RasterOp {
private AffineTransform xform;
RenderingHints hints;
/**
* Nearest-neighbor interpolation type.
*/
@Native public static final int TYPE_NEAREST_NEIGHBOR = 1;
/**
* Bilinear interpolation type.
*/
@Native public static final int TYPE_BILINEAR = 2;
/**
* Bicubic interpolation type.
*/
@Native public static final int TYPE_BICUBIC = 3;
int interpolationType = TYPE_NEAREST_NEIGHBOR;
/**
* Constructs an {@code AffineTransformOp} given an affine transform.
* The interpolation type is determined from the
* {@code RenderingHints} object. If the interpolation hint is
* defined, it will be used. Otherwise, if the rendering quality hint is
* defined, the interpolation type is determined from its value. If no
* hints are specified ({@code hints} is null),
* the interpolation type is {@link #TYPE_NEAREST_NEIGHBOR
* TYPE_NEAREST_NEIGHBOR}.
*
* @param xform The {@code AffineTransform} to use for the
* operation.
*
* @param hints The {@code RenderingHints} object used to specify
* the interpolation type for the operation.
*
* @throws ImagingOpException if the transform is non-invertible.
* @see java.awt.RenderingHints#KEY_INTERPOLATION
* @see java.awt.RenderingHints#KEY_RENDERING
*/
public AffineTransformOp(AffineTransform xform, RenderingHints hints){
validateTransform(xform);
this.xform = (AffineTransform) xform.clone();
this.hints = hints;
if (hints != null) {
Object value = hints.get(RenderingHints.KEY_INTERPOLATION);
if (value == null) {
value = hints.get(RenderingHints.KEY_RENDERING);
if (value == RenderingHints.VALUE_RENDER_SPEED) {
interpolationType = TYPE_NEAREST_NEIGHBOR;
}
else if (value == RenderingHints.VALUE_RENDER_QUALITY) {
interpolationType = TYPE_BILINEAR;
}
}
else if (value == RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR) {
interpolationType = TYPE_NEAREST_NEIGHBOR;
}
else if (value == RenderingHints.VALUE_INTERPOLATION_BILINEAR) {
interpolationType = TYPE_BILINEAR;
}
else if (value == RenderingHints.VALUE_INTERPOLATION_BICUBIC) {
interpolationType = TYPE_BICUBIC;
}
}
else {
interpolationType = TYPE_NEAREST_NEIGHBOR;
}
}
/**
* Constructs an {@code AffineTransformOp} given an affine transform
* and the interpolation type.
*
* @param xform The {@code AffineTransform} to use for the operation.
* @param interpolationType One of the integer
* interpolation type constants defined by this class:
* {@link #TYPE_NEAREST_NEIGHBOR TYPE_NEAREST_NEIGHBOR},
* {@link #TYPE_BILINEAR TYPE_BILINEAR},
* {@link #TYPE_BICUBIC TYPE_BICUBIC}.
* @throws ImagingOpException if the transform is non-invertible.
*/
public AffineTransformOp(AffineTransform xform, int interpolationType) {
validateTransform(xform);
this.xform = (AffineTransform)xform.clone();
switch(interpolationType) {
case TYPE_NEAREST_NEIGHBOR:
case TYPE_BILINEAR:
case TYPE_BICUBIC:
break;
default:
throw new IllegalArgumentException("Unknown interpolation type: "+
interpolationType);
}
this.interpolationType = interpolationType;
}
/**
* Returns the interpolation type used by this op.
* @return the interpolation type.
* @see #TYPE_NEAREST_NEIGHBOR
* @see #TYPE_BILINEAR
* @see #TYPE_BICUBIC
*/
public final int getInterpolationType() {
return interpolationType;
}
/**
* Transforms the source {@code BufferedImage} and stores the results
* in the destination {@code BufferedImage}.
* If the color models for the two images do not match, a color
* conversion into the destination color model is performed.
* If the destination image is null,
* a {@code BufferedImage} is created with the source
* {@code ColorModel}.
* <p>
* The coordinates of the rectangle returned by
* {@code getBounds2D(BufferedImage)}
* are not necessarily the same as the coordinates of the
* {@code BufferedImage} returned by this method. If the
* application provides a {@code dst} that is always returned.
* If {@code dst} is {@code null} and a destination {@code BufferedImage}
* with the transformed dimensions cannot be created, the {@code src}
* dimensions will be substituted.
*
* <p>
* If the upper-left corner coordinates of the rectangle are
* negative then this part of the rectangle is not drawn. If the
* upper-left corner coordinates of the rectangle are positive
* then the filtered image is drawn at that position in the
* destination {@code BufferedImage}.
* <p>
* An {@code IllegalArgumentException} is thrown if the source is
* the same as the destination.
*
* @param src The {@code BufferedImage} to transform.
* @param dst The {@code BufferedImage} in which to store the results
* of the transformation.
*
* @return The filtered {@code BufferedImage}.
* @throws IllegalArgumentException if {@code src} and
* {@code dst} are the same
* @throws ImagingOpException if the image cannot be transformed
* because of a data-processing error that might be
* caused by an invalid image format, tile format, or
* image-processing operation, or any other unsupported
* operation.
*/
public final BufferedImage filter(BufferedImage src, BufferedImage dst) {
if (src == null) {
throw new NullPointerException("src image is null");
}
if (src == dst) {
throw new IllegalArgumentException("src image cannot be the "+
"same as the dst image");
}
boolean needToConvert = false;
ColorModel srcCM = src.getColorModel();
ColorModel dstCM;
BufferedImage origDst = dst;
if (dst == null) {
dst = createCompatibleDestImageInt(src, null);
dstCM = srcCM;
origDst = dst;
}
else {
dstCM = dst.getColorModel();
if (srcCM.getColorSpace().getType() !=
dstCM.getColorSpace().getType())
{
int type = xform.getType();
boolean needTrans = ((type&
(AffineTransform.TYPE_MASK_ROTATION|
AffineTransform.TYPE_GENERAL_TRANSFORM))
!= 0);
if (! needTrans &&
type != AffineTransform.TYPE_TRANSLATION &&
type != AffineTransform.TYPE_IDENTITY)
{
double[] mtx = new double[4];
xform.getMatrix(mtx);
// Check out the matrix. A non-integral scale will force ARGB
// since the edge conditions can't be guaranteed.
needTrans = (mtx[0] != (int)mtx[0] || mtx[3] != (int)mtx[3]);
}
if (needTrans &&
srcCM.getTransparency() == Transparency.OPAQUE)
{
// Need to convert first
ColorConvertOp ccop = new ColorConvertOp(hints);
BufferedImage tmpSrc = null;
int sw = src.getWidth();
int sh = src.getHeight();
if (dstCM.getTransparency() == Transparency.OPAQUE) {
tmpSrc = new BufferedImage(sw, sh,
BufferedImage.TYPE_INT_ARGB);
}
else {
WritableRaster r =
dstCM.createCompatibleWritableRaster(sw, sh);
tmpSrc = new BufferedImage(dstCM, r,
dstCM.isAlphaPremultiplied(),
null);
}
src = ccop.filter(src, tmpSrc);
}
else {
needToConvert = true;
dst = createCompatibleDestImageInt(src, null);
}
}
}
if (interpolationType != TYPE_NEAREST_NEIGHBOR &&
dst.getColorModel() instanceof IndexColorModel) {
dst = new BufferedImage(dst.getWidth(), dst.getHeight(),
BufferedImage.TYPE_INT_ARGB);
}
if (ImagingLib.filter(this, src, dst) == null) {
throw new ImagingOpException ("Unable to transform src image");
}
if (needToConvert) {
ColorConvertOp ccop = new ColorConvertOp(hints);
ccop.filter(dst, origDst);
}
else if (origDst != dst) {
java.awt.Graphics2D g = origDst.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(dst, 0, 0, null);
} finally {
g.dispose();
}
}
return origDst;
}
/**
* Transforms the source {@code Raster} and stores the results in
* the destination {@code Raster}. This operation performs the
* transform band by band.
* <p>
* If the destination {@code Raster} is null, a new
* {@code Raster} is created.
* An {@code IllegalArgumentException} may be thrown if the source is
* the same as the destination or if the number of bands in
* the source is not equal to the number of bands in the
* destination.
* <p>
* The coordinates of the rectangle returned by
* {@code getBounds2D(Raster)}
* are not necessarily the same as the coordinates of the
* {@code WritableRaster} returned by this method. If the
* application provides a {@code dst} that is always returned.
* If {@code dst} is {@code null} and a destination {@code Raster}
* with the transformed dimensions cannot be created, the {@code src}
* dimensions will be substituted.
* <p>
* If the upper-left corner coordinates of rectangle are negative then
* this part of the rectangle is not drawn. If the coordinates
* of the rectangle are positive then the filtered image is drawn at
* that position in the destination {@code Raster}.
*
* @param src The {@code Raster} to transform.
* @param dst The {@code Raster} in which to store the results of the
* transformation.
*
* @return The transformed {@code Raster}.
*
* @throws ImagingOpException if the raster cannot be transformed
* because of a data-processing error that might be
* caused by an invalid image format, tile format, or
* image-processing operation, or any other unsupported
* operation.
*/
public final WritableRaster filter(Raster src, WritableRaster dst) {
if (src == null) {
throw new NullPointerException("src image is null");
}
if (dst == null) {
dst = createCompatibleDestRasterInt(src);
}
if (src == dst) {
throw new IllegalArgumentException("src image cannot be the "+
"same as the dst image");
}
if (src.getNumBands() != dst.getNumBands()) {
throw new IllegalArgumentException("Number of src bands ("+
src.getNumBands()+
") does not match number of "+
" dst bands ("+
dst.getNumBands()+")");
}
if (ImagingLib.filter(this, src, dst) == null) {
throw new ImagingOpException ("Unable to transform src image");
}
return dst;
}
/**
* Returns the bounding box of the transformed destination. The
* rectangle returned is the actual bounding box of the
* transformed points. The coordinates of the upper-left corner
* of the returned rectangle might not be (0, 0).
*
* @param src The {@code BufferedImage} to be transformed.
*
* @return The {@code Rectangle2D} representing the destination's
* bounding box.
*/
public final Rectangle2D getBounds2D (BufferedImage src) {
return getBounds2D(src.getRaster());
}
/**
* Returns the bounding box of the transformed destination. The
* rectangle returned will be the actual bounding box of the
* transformed points. The coordinates of the upper-left corner
* of the returned rectangle might not be (0, 0).
*
* @param src The {@code Raster} to be transformed.
*
* @return The {@code Rectangle2D} representing the destination's
* bounding box.
*/
public final Rectangle2D getBounds2D (Raster src) {
int w = src.getWidth();
int h = src.getHeight();
// Get the bounding box of the src and transform the corners
float[] pts = {0, 0, w, 0, w, h, 0, h};
xform.transform(pts, 0, pts, 0, 4);
// Get the min, max of the dst
float fmaxX = pts[0];
float fmaxY = pts[1];
float fminX = pts[0];
float fminY = pts[1];
for (int i=2; i < 8; i+=2) {
if (pts[i] > fmaxX) {
fmaxX = pts[i];
}
else if (pts[i] < fminX) {
fminX = pts[i];
}
if (pts[i+1] > fmaxY) {
fmaxY = pts[i+1];
}
else if (pts[i+1] < fminY) {
fminY = pts[i+1];
}
}
return new Rectangle2D.Float(fminX, fminY, fmaxX-fminX, fmaxY-fminY);
}
/**
* Creates a zeroed destination image with the correct size and number of
* bands. A {@code RasterFormatException} may be thrown if the
* transformed width or height is less than or equal to 0, or too large.
* <p>
* If {@code destCM} is null,
* an appropriate {@code ColorModel} is used; this
* {@code ColorModel} may have
* an alpha channel even if the source {@code ColorModel} is opaque.
*
* @param src The {@code BufferedImage} to be transformed.
* @param destCM {@code ColorModel} of the destination. If null,
* an appropriate {@code ColorModel} is used.
*
* @return The zeroed destination image.
*/
public BufferedImage createCompatibleDestImage (BufferedImage src,
ColorModel destCM) {
Rectangle r = getBounds2D(src).getBounds();
try {
return createCompatibleDestImage(src, destCM, r);
} catch (Exception e) {
if (e instanceof RasterFormatException) {
throw e;
} else {
RasterFormatException re =
new RasterFormatException("Could not create transformed image of size " + r);
re.initCause(e);
throw re;
}
}
}
private BufferedImage createCompatibleDestImageInt(BufferedImage src,
ColorModel destCM) {
try {
return createCompatibleDestImage(src, destCM);
} catch (Exception e) {
return createCompatibleDestImage(src, destCM, src.getRaster().getBounds());
}
}
private BufferedImage createCompatibleDestImage(BufferedImage src,
ColorModel destCM,
Rectangle r) {
BufferedImage image;
// If r.x (or r.y) is < 0, then we want to only create an image
// that is in the positive range.
// If r.x (or r.y) is > 0, then we need to create an image that
// includes the translation.
int w = r.x + r.width;
int h = r.y + r.height;
if (w <= 0) {
throw new RasterFormatException("Transformed width ("+w+
") is less than or equal to 0.");
}
if (h <= 0) {
throw new RasterFormatException("Transformed height ("+h+
") is less than or equal to 0.");
}
if (destCM == null) {
ColorModel cm = src.getColorModel();
if (interpolationType != TYPE_NEAREST_NEIGHBOR &&
(cm instanceof IndexColorModel ||
cm.getTransparency() == Transparency.OPAQUE))
{
image = new BufferedImage(w, h,
BufferedImage.TYPE_INT_ARGB);
}
else {
image = new BufferedImage(cm,
src.getRaster().createCompatibleWritableRaster(w,h),
cm.isAlphaPremultiplied(), null);
}
}
else {
image = new BufferedImage(destCM,
destCM.createCompatibleWritableRaster(w,h),
destCM.isAlphaPremultiplied(), null);
}
return image;
}
/**
* Creates a zeroed destination {@code Raster} with the correct size
* and number of bands. A {@code RasterFormatException} may be thrown
* if the transformed width or height is less than or equal to 0, or too large.
*
* @param src The {@code Raster} to be transformed.
*
* @return The zeroed destination {@code Raster}.
*/
public WritableRaster createCompatibleDestRaster (Raster src) {
Rectangle r = getBounds2D(src).getBounds();
try {
return createCompatibleDestRaster(src, r);
} catch (Exception e) {
if (e instanceof RasterFormatException) {
throw e;
} else {
RasterFormatException re =
new RasterFormatException("Could not create transformed raster of size " + r);
re.initCause(e);
throw re;
}
}
}
private WritableRaster createCompatibleDestRasterInt(Raster src) {
try {
return createCompatibleDestRaster(src);
} catch (Exception e) {
Rectangle r = src.getBounds();
return createCompatibleDestRaster(src, r);
}
}
private WritableRaster createCompatibleDestRaster (Raster src, Rectangle r) {
return src.createCompatibleWritableRaster((int)r.getX(),
(int)r.getY(),
(int)r.getWidth(),
(int)r.getHeight());
}
/**
* Returns the location of the corresponding destination point given a
* point in the source. If {@code dstPt} is specified, it
* is used to hold the return value.
*
* @param srcPt The {@code Point2D} that represents the source
* point.
* @param dstPt The {@code Point2D} in which to store the result.
*
* @return The {@code Point2D} in the destination that corresponds to
* the specified point in the source.
*/
public final Point2D getPoint2D (Point2D srcPt, Point2D dstPt) {
return xform.transform (srcPt, dstPt);
}
/**
* Returns the affine transform used by this transform operation.
*
* @return The {@code AffineTransform} associated with this op.
*/
public final AffineTransform getTransform() {
return (AffineTransform) xform.clone();
}
/**
* Returns the rendering hints used by this transform operation.
*
* @return The {@code RenderingHints} object associated with this op.
*/
public final RenderingHints getRenderingHints() {
if (hints == null) {
Object val;
switch(interpolationType) {
case TYPE_NEAREST_NEIGHBOR:
val = RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR;
break;
case TYPE_BILINEAR:
val = RenderingHints.VALUE_INTERPOLATION_BILINEAR;
break;
case TYPE_BICUBIC:
val = RenderingHints.VALUE_INTERPOLATION_BICUBIC;
break;
default:
// Should never get here
throw new InternalError("Unknown interpolation type "+
interpolationType);
}
hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION, val);
}
return hints;
}
// We need to be able to invert the transform if we want to
// transform the image. If the determinant of the matrix is 0,
// then we can't invert the transform.
void validateTransform(AffineTransform xform) {
if (Math.abs(xform.getDeterminant()) <= Double.MIN_VALUE) {
throw new ImagingOpException("Unable to invert transform "+xform);
}
}
}