-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImage.java
More file actions
3022 lines (2483 loc) · 104 KB
/
Image.java
File metadata and controls
3022 lines (2483 loc) · 104 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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package javaxt.io;
import java.io.*;
import javax.imageio.*;
import javax.imageio.metadata.*;
import java.awt.image.*;
import java.awt.color.ColorSpace;
import java.awt.geom.AffineTransform;
import java.awt.*;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
//Imports for JPEG
//import com.sun.image.codec.jpeg.*; //<-- Not always available in newer versions
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
//Imports for JP2
//import javax.media.jai.RenderedOp;
//import com.sun.media.imageio.plugins.jpeg2000.J2KImageReadParam;
//******************************************************************************
//** Image Class
//******************************************************************************
/**
* Used to open, resize, rotate, crop and save images.
*
******************************************************************************/
public class Image {
private BufferedImage bufferedImage = null;
private java.util.ArrayList corners = null;
private float outputQuality = 1f; //0.9f; //0.5f;
private static final boolean useSunCodec = getSunCodec();
private static Class JPEGCodec;
private static Class JPEGEncodeParam;
private Graphics2D g2d = null;
public static String[] InputFormats = getFormats(ImageIO.getReaderFormatNames());
public static String[] OutputFormats = getFormats(ImageIO.getWriterFormatNames());
private IIOMetadata metadata;
private HashMap<Integer, Object> exif;
private HashMap<Integer, Object> iptc;
private HashMap<Integer, Object> gps;
private boolean saveMetadata = false;
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using an existing image */
public Image(String PathToImageFile){
this(new java.io.File(PathToImageFile));
}
public Image(java.io.File file){
if (!file.exists()) throw new IllegalArgumentException("Input file not found.");
try{ createBufferedImage(new FileInputStream(file)); }
catch(Exception e){}
}
public Image(java.io.InputStream InputStream){
createBufferedImage(InputStream);
}
public Image(byte[] byteArray){
this(new ByteArrayInputStream(byteArray));
}
public Image(int width, int height){
this.bufferedImage =
new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
this.g2d = getGraphics();
}
public Image(BufferedImage bufferedImage){
this.bufferedImage = bufferedImage;
}
public Image(RenderedImage img) {
if (img instanceof BufferedImage) {
this.bufferedImage = (BufferedImage) img;
}
else{
java.awt.image.ColorModel cm = img.getColorModel();
java.awt.image.WritableRaster raster =
cm.createCompatibleWritableRaster(img.getWidth(), img.getHeight());
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
java.util.Hashtable properties = new java.util.Hashtable();
String[] keys = img.getPropertyNames();
if (keys!=null) {
for (int i = 0; i < keys.length; i++) {
properties.put(keys[i], img.getProperty(keys[i]));
}
}
BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties);
img.copyData(raster);
this.bufferedImage = result;
}
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a block of text.
* @param fontName Name of the font you with to use. Note that you can get
* a list of available fonts like this:
<pre>
for (String fontName : GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()){
System.out.println(fontName);
}
</pre>
*/
public Image(String text, String fontName, int fontSize, int r, int g, int b){
this(text, new Font(fontName, Font.TRUETYPE_FONT, fontSize), r,g,b);
}
public Image(String text, Font font, int r, int g, int b){
//Get Font Metrics
Graphics2D t = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB).createGraphics();
t.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
FontMetrics fm = t.getFontMetrics(font);
int width = fm.stringWidth(text);
int height = fm.getHeight();
int descent = fm.getDescent();
t.dispose();
//Create Image
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2d = bufferedImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//Add Text
float alpha = 1.0f; //Set alpha. 0.0f is 100% transparent and 1.0f is 100% opaque.
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2d.setColor(new Color(r, g, b));
g2d.setFont(font);
g2d.drawString(text, 0, height-descent);
}
//**************************************************************************
//** setBackgroundColor
//**************************************************************************
/** Used to set the background color. Creates an image layer and inserts it
* under the existing graphic. This method should only be called once.
*/
public void setBackgroundColor(int r, int g, int b){
/*
Color org = g2d.getColor();
g2d.setColor(new Color(r,g,b));
g2d.fillRect(1,1,width-2,height-2); //g2d.fillRect(0,0,width,height);
g2d.setColor(org);
*/
int imageType = bufferedImage.getType();
if (imageType == 0) {
imageType = BufferedImage.TYPE_INT_ARGB;
}
int width = this.getWidth();
int height = this.getHeight();
BufferedImage bi = new BufferedImage(width, height, imageType);
Graphics2D g2d = bi.createGraphics();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
g2d.setColor(new Color(r,g,b));
g2d.fillRect(0,0,width,height);
java.awt.Image img = bufferedImage;
g2d.drawImage(img, 0, 0, null);
this.bufferedImage = bi;
g2d.dispose();
}
//**************************************************************************
//** getInputFormats
//**************************************************************************
/** Used to retrieve a list of supported input (read) formats. */
public String[] getInputFormats(){
return getFormats(ImageIO.getReaderFormatNames());
}
//**************************************************************************
//** getOutputFormats
//**************************************************************************
/** Used to retrieve a list of supported output (write) formats. */
public String[] getOutputFormats(){
return getFormats(ImageIO.getWriterFormatNames());
}
//**************************************************************************
//** getFormats
//**************************************************************************
/** Used to trim the list of formats. */
private static String[] getFormats(String[] inputFormats){
//Build a unique list of file formats
HashSet<String> formats = new HashSet<String> ();
for (int i=0; i<inputFormats.length; i++){
String format = inputFormats[i].toUpperCase();
if (format.contains("JPEG") && format.contains("2000")){
formats.add("JP2");
formats.add("J2C");
formats.add("J2K");
formats.add("JPX");
}
else if (format.equals("JPEG") || format.equals("JPG")){
formats.add("JPE");
formats.add("JFF");
formats.add(format);
}
else{
formats.add(format);
}
}
//Sort and return the hashset as an array
inputFormats = formats.toArray(new String[formats.size()]);
java.util.Collections.sort(java.util.Arrays.asList(inputFormats));
return inputFormats;
}
//**************************************************************************
//** getSunCodec
//**************************************************************************
/** Attempts to load classes from the com.sun.image.codec.jpeg package used
* to compress jpeg images. These classes are marked as deprecated in Java
* 1.7 and several distributions of Java no longer include these classes
* (e.g. "IcedTea" OpenJDK 7). Returns true of the classes are available.
*/
private static boolean getSunCodec(){
try{
JPEGCodec = Class.forName("com.sun.image.codec.jpeg.JPEGCodec");
JPEGEncodeParam = Class.forName("com.sun.image.codec.jpeg.JPEGEncodeParam");
return true;
}
catch(Exception e){
return false;
}
}
//**************************************************************************
//** getWidth
//**************************************************************************
/** Returns the width of the image, in pixels. */
public int getWidth(){
return bufferedImage.getWidth();
}
//**************************************************************************
//** getHeight
//**************************************************************************
/** Returns the height of the image, in pixels.
*/
public int getHeight(){
return bufferedImage.getHeight();
}
//**************************************************************************
//** getGraphics
//**************************************************************************
private Graphics2D getGraphics(){
if (g2d==null){
g2d = this.bufferedImage.createGraphics();
//Enable anti-alias
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
return g2d;
}
//**************************************************************************
//** addText
//**************************************************************************
/** Used to add text to the image at a given position.
* @param x Lower left coordinate of the text
* @param y Lower left coordinate of the text
*/
public void addText(String text, int x, int y){
addText(text, x, y, new Font ("SansSerif",Font.TRUETYPE_FONT,12), 0, 0, 0);
}
//**************************************************************************
//** addText
//**************************************************************************
/** Used to add text to the image at a given position.
* @param x Lower left coordinate of the text
* @param y Lower left coordinate of the text
* @param fontName Name of the font face (e.g. "Tahoma", "Helvetica", etc.)
* @param fontSize Size of the font
* @param r Value for the red channel (0-255)
* @param g Value for the green channel (0-255)
* @param b Value for the blue channel (0-255)
*/
public void addText(String text, int x, int y, String fontName, int fontSize, int r, int g, int b){
addText(text, x, y, new Font(fontName, Font.TRUETYPE_FONT, fontSize), r,g,b);
}
//**************************************************************************
//** addText
//**************************************************************************
/** Used to add text to the image at a given position.
* @param x Lower left coordinate of the text
* @param y Lower left coordinate of the text
* @param font Font
* @param r Value for the red channel (0-255)
* @param g Value for the green channel (0-255)
* @param b Value for the blue channel (0-255)
*/
public void addText(String text, int x, int y, Font font, int r, int g, int b){
g2d = getGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(r, g, b));
g2d.setFont(font);
g2d.drawString(text, x, y);
}
//**************************************************************************
//** addPoint
//**************************************************************************
/** Simple drawing function used to set color of a specific pixel in the
* image.
*/
public void addPoint(int x, int y, int r, int g, int b){
setColor(x,y,new Color(r,g,b));
}
//**************************************************************************
//** setColor
//**************************************************************************
/** Used to set the color (ARGB value) for a specific pixel in the image.
* Note that input x,y values are relative to the upper left corner of the
* image, starting at 0,0.
*/
public void setColor(int x, int y, Color color){
g2d = getGraphics();
Color org = g2d.getColor();
g2d.setColor(color);
g2d.fillRect(x,y,1,1);
g2d.setColor(org);
}
//**************************************************************************
//** getColor
//**************************************************************************
/** Used to retrieve the color (ARGB) values for a specific pixel in the
* image. Returns a java.awt.Color object. Note that input x,y values are
* relative to the upper left corner of the image, starting at 0,0.
*/
public Color getColor(int x, int y){
//return new Color(bufferedImage.getRGB(x, y)); //<--This will return an incorrect alpha value
int pixel = bufferedImage.getRGB(x, y);
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
return new java.awt.Color(red, green, blue, alpha);
}
//**************************************************************************
//** getHistogram
//**************************************************************************
/** Returns an array with 4 histograms: red, green, blue, and average
<pre>
ArrayList<int[]> histogram = image.getHistogram();
int[] red = histogram.get(0);
int[] green = histogram.get(1);
int[] blue = histogram.get(2);
int[] average = histogram.get(3);
</pre>
*/
public java.util.ArrayList<int[]> getHistogram(){
//Create empty histograms
int[] red = new int[256];
int[] green = new int[256];
int[] blue = new int[256];
int[] average = new int[256];
for (int i=0; i<red.length; i++) red[i] = 0;
for (int i=0; i<green.length; i++) green[i] = 0;
for (int i=0; i<blue.length; i++) blue[i] = 0;
for (int i=0; i<average.length; i++) average[i] = 0;
//Populate the histograms
for (int i=0; i<this.getWidth(); i++){
for (int j=0; j<this.getHeight(); j++){
Color color = this.getColor(i, j);
int r = color.getRed();
int g = color.getGreen();
int b = color.getBlue();
red[r] = red[r]+1;
green[g] = green[g]+1;
blue[b] = blue[b]+1;
int avg = Math.round((r+g+b)/3);
average[avg] = average[avg]+1;
}
}
java.util.ArrayList<int[]> hist = new java.util.ArrayList<int[]>();
hist.add(red);
hist.add(green);
hist.add(blue);
hist.add(average);
return hist;
}
//**************************************************************************
//** addImage
//**************************************************************************
/** Used to add an image "overlay" to the existing image at a given
* position. This method can also be used to create image mosiacs.
*/
public void addImage(BufferedImage in, int x, int y, boolean expand){
int x2 = 0;
int y2 = 0;
int w = bufferedImage.getWidth();
int h = bufferedImage.getHeight();
if (expand){
//Update Width and Horizontal Position of the Original Image
if (x<0) {
w = w + -x;
if (in.getWidth()>w){
w = w + (in.getWidth()-w);
}
x2 = -x;
x = 0;
}
else if (x>w) {
w = (w + (x-w)) + in.getWidth();
}
else{
if ((x+in.getWidth())>w){
w = w + ((x+in.getWidth())-w);
}
}
//Update Height and Vertical Position of the Original Image
if (y<0){
h = h + -y;
if (in.getHeight()>h){
h = h + (in.getHeight()-h);
}
y2 = -y;
y = 0;
}
else if(y>h){
h = (h + (y-h)) + in.getHeight();
}
else{
if ((y+in.getHeight())>h){
h = h + ((y+in.getHeight())-h);
}
}
}
//Create new image "collage"
if (w>bufferedImage.getWidth() || h>bufferedImage.getHeight()){
BufferedImage bi = new BufferedImage(w, h, getImageType());
Graphics2D g2d = bi.createGraphics();
java.awt.Image img = bufferedImage;
g2d.drawImage(img, x2, y2, null);
img = in;
g2d.drawImage(img, x, y, null);
g2d.dispose();
bufferedImage = bi;
}
else{
Graphics2D g2d = bufferedImage.createGraphics();
java.awt.Image img = in;
g2d.drawImage(img, x, y, null);
g2d.dispose();
}
}
//**************************************************************************
//** addImage
//**************************************************************************
/** Used to add an image "overlay" to the existing image at a given
* position. This method can also be used to create image mosiacs.
*/
public void addImage(javaxt.io.Image in, int x, int y, boolean expand){
addImage(in.getBufferedImage(),x,y,expand);
}
//**************************************************************************
//** createBufferedImage
//**************************************************************************
/** Used to create a BufferedImage from a InputStream
*/
private void createBufferedImage(java.io.InputStream input) {
try{
//bufferedImage = ImageIO.read(input);
javax.imageio.stream.ImageInputStream stream = ImageIO.createImageInputStream(input);
Iterator iter = ImageIO.getImageReaders(stream);
if (!iter.hasNext()) {
return;
}
ImageReader reader = (ImageReader)iter.next();
ImageReadParam param = reader.getDefaultReadParam();
reader.setInput(stream, true, true);
try {
bufferedImage = reader.read(0, param);
metadata = reader.getImageMetadata(0);
}
finally {
reader.dispose();
stream.close();
}
input.close();
}
catch(Exception e){
//e.printStackTrace();
}
}
//**************************************************************************
//** Rotate
//**************************************************************************
/** Used to rotate the image (clockwise). Rotation angle is specified in
* degrees relative to the top of the image.
*/
public void rotate(double Degrees){
//Define Image Center (Axis of Rotation)
int width = this.getWidth();
int height = this.getHeight();
int cx = width/2;
int cy = height/2;
//create an array containing the corners of the image (TL,TR,BR,BL)
int[] corners = { 0, 0, width, 0, width, height, 0, height };
//Define bounds of the image
int minX, minY, maxX, maxY;
minX = maxX = cx;
minY = maxY = cy;
double theta = Math.toRadians(Degrees);
for (int i=0; i<corners.length; i+=2){
//Rotates the given point theta radians around (cx,cy)
int x = (int) Math.round(
Math.cos(theta)*(corners[i]-cx) -
Math.sin(theta)*(corners[i+1]-cy)+cx
);
int y = (int) Math.round(
Math.sin(theta)*(corners[i]-cx) +
Math.cos(theta)*(corners[i+1]-cy)+cy
);
//Update our bounds
if(x>maxX) maxX = x;
if(x<minX) minX = x;
if(y>maxY) maxY = y;
if(y<minY) minY = y;
}
//Update Image Center Coordinates
cx = (int)(cx-minX);
cy = (int)(cy-minY);
//Create Buffered Image
BufferedImage result = new BufferedImage(maxX-minX, maxY-minY,
BufferedImage.TYPE_INT_ARGB);
//Create Graphics
Graphics2D g2d = result.createGraphics();
//Enable anti-alias and Cubic Resampling
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
//Rotate the image
AffineTransform xform = new AffineTransform();
xform.rotate(theta,cx,cy);
g2d.setTransform(xform);
g2d.drawImage(bufferedImage,-minX,-minY,null);
g2d.dispose();
//Update Class Variables
this.bufferedImage = result;
//Delete Heavy Objects
result = null;
xform = null;
}
//**************************************************************************
//** rotateClockwise
//**************************************************************************
/** Rotates the image 90 degrees clockwise
*/
public void rotateClockwise(){
rotate(90);
}
//**************************************************************************
//** rotateCounterClockwise
//**************************************************************************
/** Rotates the image -90 degrees
*/
public void rotateCounterClockwise(){
rotate(-90);
}
//**************************************************************************
//** rotate
//**************************************************************************
/** Used to automatically rotate the image based on the image metadata
* (e.g. EXIF Orientation tag)
*/
public void rotate(){
try {
Integer orientation = (Integer) getExifTags().get(0x0112);
switch (orientation) {
case 1: return; //"Top, left side (Horizontal / normal)"
case 2: flip(); break; //"Top, right side (Mirror horizontal)";
case 3: rotate(180); break; //"Bottom, right side (Rotate 180)";
case 4: {flip(); rotate(180);} break; //"Bottom, left side (Mirror vertical)";
case 5: {flip(); rotate(270);} break; //"Left side, top (Mirror horizontal and rotate 270 CW)";
case 6: rotate(90); break; //"Right side, top (Rotate 90 CW)";
case 7: {flip(); rotate(90);} break; //"Right side, bottom (Mirror horizontal and rotate 90 CW)";
case 8: rotate(270); break; //"Left side, bottom (Rotate 270 CW)";
}
}
catch(Exception e){
//Failed to parse exif orientation.
}
}
//**************************************************************************
//** setWidth
//**************************************************************************
/** Resizes the image to a given width. The original aspect ratio is
* maintained.
*/
public void setWidth(int Width){
double ratio = (double)Width/(double)this.getWidth();
double dw = this.getWidth() * ratio;
double dh = this.getHeight() * ratio;
int outputWidth = (int)Math.round(dw);
int outputHeight = (int)Math.round(dh);
resize(outputWidth,outputHeight);
}
//**************************************************************************
//** setHeight
//**************************************************************************
/** Resizes the image to a given height. The original aspect ratio is
* maintained.
*/
public void setHeight(int Height){
double ratio = (double)Height/(double)this.getHeight();
double dw = this.getWidth() * ratio;
double dh = this.getHeight() * ratio;
int outputWidth = (int)Math.round(dw);
int outputHeight = (int)Math.round(dh);
resize(outputWidth,outputHeight);
}
//**************************************************************************
//** resize (Overloaded Member)
//**************************************************************************
/** Used to resize an image. Does NOT automatically retain the original
* aspect ratio.
*/
public void resize(int width, int height){
resize(width, height, false);
}
//**************************************************************************
//** resize
//**************************************************************************
/** Used to resize an image. Provides the option to maintain the original
* aspect ratio.
* @param maintainRatio If true, will interpret the given width and height
* as maximum desired width and height
*/
public void resize(int width, int height, boolean maintainRatio){
if (maintainRatio){
int maxWidth = width;
int maxHeight = height;
if (maxHeight<maxWidth){
//Set height
double ratio = (double)maxHeight/(double)this.getHeight();
width = (int)Math.round(this.getWidth() * ratio);
height = (int)Math.round(this.getHeight() * ratio);
if (width>maxWidth){
//Set width
ratio = (double)maxWidth/(double)width;
width = (int)Math.round(width * ratio);
height = (int)Math.round(height * ratio);
}
}
else{
//Set width
double ratio = (double)maxWidth/(double)this.getWidth();
width = (int)Math.round(this.getWidth() * ratio);
height = (int)Math.round(this.getHeight() * ratio);
if (height>maxHeight){
//Set height
ratio = (double)maxHeight/(double)height;
width = (int)Math.round(width * ratio);
height = (int)Math.round(height * ratio);
}
}
}
//Resize the image (create new buffered image)
java.awt.Image outputImage = bufferedImage.getScaledInstance(width, height, BufferedImage.SCALE_AREA_AVERAGING);
BufferedImage bi = new BufferedImage(width, height, getImageType());
Graphics2D g2d = bi.createGraphics( );
g2d.drawImage(outputImage, 0, 0, null);
g2d.dispose();
this.bufferedImage = bi;
outputImage = null;
bi = null;
g2d = null;
}
//**************************************************************************
//** Set/Update Corners (Skew)
//**************************************************************************
/** Used to skew an image by updating the corner coordinates. Coordinates
* are supplied in clockwise order starting from the upper left corner.
*/
public void setCorners(float x0, float y0, //UL
float x1, float y1, //UR
float x2, float y2, //LR
float x3, float y3){ //LL
Skew skew = new Skew(this.bufferedImage);
this.bufferedImage = skew.setCorners(x0,y0,x1,y1,x2,y2,x3,y3);
if (corners==null) corners = new java.util.ArrayList();
else corners.clear();
corners.add((Float)x0); corners.add((Float)y0);
corners.add((Float)x1); corners.add((Float)y1);
corners.add((Float)x2); corners.add((Float)y2);
corners.add((Float)x3); corners.add((Float)y3);
}
//**************************************************************************
//** Get Corners
//**************************************************************************
/** Used to retrieve the corner coordinates of the image. Coordinates are
* supplied in clockwise order starting from the upper left corner. This
* information is particularly useful for generating drop shadows, inner
* and outer glow, and reflections.
* NOTE: Coordinates are not updated after resize(), rotate(), or addImage()
*/
public float[] getCorners(){
if (corners==null){
float w = getWidth();
float h = getHeight();
corners = new java.util.ArrayList();
corners.add((Float)0f); corners.add((Float)0f);
corners.add((Float)w); corners.add((Float)0f);
corners.add((Float)w); corners.add((Float)h);
corners.add((Float)0f); corners.add((Float)h);
}
Object[] arr = corners.toArray();
float[] ret = new float[arr.length];
for (int i=0; i<arr.length; i++){
Float f = (Float) arr[i];
ret[i] = f.floatValue();
}
return ret;
}
//**************************************************************************
//** Sharpen
//**************************************************************************
/** Used to sharpen the image using a 3x3 kernel.
*/
public void sharpen(){
int width = this.getWidth();
int height = this.getHeight();
//define kernel
Kernel kernel = new Kernel(3, 3,
new float[] {
0.0f, -0.2f, 0.0f,
-0.2f, 1.8f, -0.2f,
0.0f, -0.2f, 0.0f });
//apply convolution
BufferedImage out = new BufferedImage(width, height, getImageType());
BufferedImageOp op = new ConvolveOp(kernel);
out = op.filter(bufferedImage, out);
//replace 2 pixel border created via convolution
java.awt.Image overlay = out.getSubimage(2,2,width-4,height-4);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.drawImage(overlay,2,2,null);
g2d.dispose();
}
//**************************************************************************
//** blur
//**************************************************************************
/** Used to blur the image using a Gaussian kernel.
*/
public void blur(float radius){
//Create kernel
int r = (int)Math.ceil(radius);
int rows = r*2+1;
float[] matrix = new float[rows];
float sigma = radius/3;
float sigma22 = 2*sigma*sigma;
float sigmaPi2 = (float)(2*Math.PI*sigma);
float sqrtSigmaPi2 = (float)Math.sqrt(sigmaPi2);
float radius2 = radius*radius;
float total = 0;
int index = 0;
for (int row = -r; row <= r; row++) {
float distance = row*row;
if (distance > radius2)
matrix[index] = 0;
else
matrix[index] = (float)Math.exp(-(distance)/sigma22) / sqrtSigmaPi2;
total += matrix[index];
index++;
}
for (int i = 0; i < rows; i++)
matrix[i] /= total;
Kernel kernel = new Kernel(rows, 1, matrix);
//
int width = this.getWidth();
int height = this.getHeight();
int[] inPixels = new int[width*height];
int[] outPixels = new int[width*height];
bufferedImage.getRGB( 0, 0, width, height, inPixels, 0, width );
convolveAndTranspose(kernel, inPixels, outPixels, width, height, true, CLAMP_EDGES);
convolveAndTranspose(kernel, outPixels, inPixels, height, width, true, CLAMP_EDGES);
bufferedImage.setRGB( 0, 0, width, height, inPixels, 0, width );
}
private static int CLAMP_EDGES = 1;
private static int WRAP_EDGES = 2;
//**************************************************************************
//** convolveAndTranspose
//**************************************************************************
/** Applies 1D Gaussian kernel used to blur an image. This filter should be
* applied twice, once horizontally and once vertically.
* @author Jerry Huxtable
*/
private static void convolveAndTranspose(Kernel kernel, int[] inPixels, int[] outPixels,
int width, int height, boolean alpha, int edgeAction) {
float[] matrix = kernel.getKernelData( null );
int cols = kernel.getWidth();
int cols2 = cols/2;
for (int y = 0; y < height; y++) {
int index = y;
int ioffset = y*width;
for (int x = 0; x < width; x++) {
float r = 0, g = 0, b = 0, a = 0;
int moffset = cols2;
for (int col = -cols2; col <= cols2; col++) {
float f = matrix[moffset+col];
if (f != 0) {
int ix = x+col;
if ( ix < 0 ) {
if ( edgeAction == CLAMP_EDGES )
ix = 0;
else if ( edgeAction == WRAP_EDGES )
ix = (x+width) % width;
} else if ( ix >= width) {
if ( edgeAction == CLAMP_EDGES )
ix = width-1;
else if ( edgeAction == WRAP_EDGES )
ix = (x+width) % width;
}
int rgb = inPixels[ioffset+ix];
a += f * ((rgb >> 24) & 0xff);
r += f * ((rgb >> 16) & 0xff);
g += f * ((rgb >> 8) & 0xff);
b += f * (rgb & 0xff);
}
}
int ia = alpha ? clamp((int)(a+0.5)) : 0xff;