/
Image.java
1812 lines (1511 loc) · 60.6 KB
/
Image.java
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 railo.runtime.img;
import java.awt.AWTException;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.font.TextAttribute;
import java.awt.geom.AffineTransform;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.QuadCurve2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBufferInt;
import java.awt.image.DirectColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.PackedColorModel;
import java.awt.image.PixelGrabber;
import java.awt.image.Raster;
import java.awt.image.SampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.ParameterBlock;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.AttributedString;
import java.util.Iterator;
import java.util.Locale;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import javax.media.jai.BorderExtender;
import javax.media.jai.BorderExtenderConstant;
import javax.media.jai.Interpolation;
import javax.media.jai.JAI;
import javax.media.jai.LookupTableJAI;
import javax.media.jai.operator.ShearDir;
import javax.media.jai.operator.TransposeType;
import javax.swing.ImageIcon;
import org.apache.commons.codec.binary.Base64;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import railo.commons.io.IOUtil;
import railo.commons.io.res.Resource;
import railo.commons.lang.StringUtil;
import railo.commons.lang.font.FontUtil;
import railo.runtime.PageContext;
import railo.runtime.dump.DumpData;
import railo.runtime.dump.DumpProperties;
import railo.runtime.dump.DumpTable;
import railo.runtime.exp.CasterException;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.exp.PageRuntimeException;
import railo.runtime.img.filter.QuantizeFilter;
import railo.runtime.img.gif.GifEncoder;
import railo.runtime.op.Caster;
import railo.runtime.op.Constants;
import railo.runtime.op.Decision;
import railo.runtime.text.xml.XMLUtil;
import railo.runtime.type.Array;
import railo.runtime.type.ArrayImpl;
import railo.runtime.type.Collection;
import railo.runtime.type.List;
import railo.runtime.type.ObjectWrap;
import railo.runtime.type.Struct;
import railo.runtime.type.StructImpl;
import railo.runtime.type.dt.DateTime;
import railo.runtime.type.util.ArrayUtil;
import railo.runtime.type.util.StructSupport;
public class Image extends StructSupport implements Cloneable,Struct {
public static final int BORDER_TYPE_CONSTANT=-1;
public static final int INTERPOLATION_NONE=0;
public static final int INTERPOLATION_NEAREST=1;
public static final int INTERPOLATION_BILINEAR=2;
public static final int INTERPOLATION_BICUBIC=3;
public static final int IP_NONE=0;
public static final int IPC_NEAREST=1;
public static final int IPC_BILINEAR=2;
public static final int IPC_BICUBIC=3;
public static final int IPC_MAX=3;
public static final int IP_HIGHESTQUALITY=100;
public static final int IP_HIGHQUALITY=101;
public static final int IP_MEDIUMQUALITY=102;
public static final int IP_HIGHESTPERFORMANCE=103;
public static final int IP_HIGHPERFORMANCE=104;
public static final int IP_MEDIUMPERFORMANCE=105;
public static final int IP_BESSEL=109;
public static final int IP_BLACKMAN=110;
public static final int IP_HAMMING=111;
public static final int IP_HANNING=112;
public static final int IP_HERMITE=113;
public static final int IP_LANCZOS=114;
public static final int IP_MITCHELL=115;
public static final int IP_QUADRATIC=116;
public static final int IP_TRIANGLE=117;
private static final int ANTI_ALIAS_NONE=0;
private static final int ANTI_ALIAS_ON=1;
private static final int ANTI_ALIAS_OFF=2;
private BufferedImage _image;
private Resource source=null;
private String format;
private Graphics2D graphics;
private Color bgColor;
private Color fgColor;
private Color xmColor;
private float tranparency=-1;
private int antiAlias=ANTI_ALIAS_NONE;
private Stroke stroke;
private Struct sctInfo;
private float alpha=1;
private Composite composite;
private static Object sync=new Object();
static {
ImageIO.scanForPlugins();
}
public Image(byte[] binary) throws IOException {
this(binary, ImageUtil.getFormat(binary));
}
public Image(byte[] binary, String format) throws IOException {
checkRestriction();
this.format=format;
_image=ImageUtil.toBufferedImage(binary,format);
if(_image==null) throw new IOException("can not read in image");
}
public Image(Resource res) throws IOException {
checkRestriction();
format=ImageUtil.getFormat(res);
_image=ImageUtil.toBufferedImage(res,format);
this.source=res;
if(_image==null) throw new IOException("can not read in file "+res);
}
public Image(BufferedImage image) {
checkRestriction();
this._image=image;
}
public Image(String b64str) throws IOException, ExpressionException {
this(ImageUtil.readBase64(b64str));
}
public Image(int width, int height, int imageType, Color canvasColor) throws ExpressionException {
checkRestriction();
_image = new BufferedImage(width, height, imageType);
if(!StringUtil.isEmpty(canvasColor)){
setBackground(canvasColor);
clearRect(0, 0, width, height);
}
}
public Image() {
checkRestriction();
}
/**
* add a border to image
* @param thickness
* @param color
* @param borderType
*/
public void addBorder(int thickness, Color color, int borderType) throws ExpressionException{
double colorArray[] = {color.getRed(), color.getGreen(), color.getBlue()};
BorderExtender borderExtender = new BorderExtenderConstant(colorArray);
ParameterBlock params = new ParameterBlock();
params.addSource(image());
params.add(thickness);
params.add(thickness);
params.add(thickness);
params.add(thickness);
if(BORDER_TYPE_CONSTANT==borderType) params.add(borderExtender);
else params.add(BorderExtender.createInstance(borderType));
//else if(BORDER_TYPE_WRAP==borderType)params.add(BorderExtender.createInstance(BorderExtender.BORDER_REFLECT));
image((JAI.create("border", params)).getAsBufferedImage());
}
public void blur(int blurFactor) throws ExpressionException{
ParameterBlock params = new ParameterBlock();
params.addSource(image());
params.add(blurFactor);
RenderingHints hint= new RenderingHints(JAI.KEY_BORDER_EXTENDER,BorderExtender.createInstance(1));
image(JAI.create("boxfilter", params, hint).getAsBufferedImage());
}
public void clearRect(int x, int y, int width, int height) throws ExpressionException{
getGraphics().clearRect(x, y, width, height);
}
public Struct info() throws ExpressionException{
if(sctInfo!=null) return sctInfo;
Struct sctInfo=new StructImpl();
Struct sctCM=new StructImpl();
sctInfo.setEL("height",new Double(getHeight()));
sctInfo.setEL("width",new Double(getWidth()));
sctInfo.setEL("source",source==null?"":source.getAbsolutePath());
//sct.setEL("mime_type",getMimeType());
sctInfo.setEL("colormodel",sctCM);
ColorModel cm = image().getColorModel();
sctCM.setEL("alpha_channel_support",Caster.toBoolean(cm.hasAlpha()));
sctCM.setEL("alpha_premultiplied",Caster.toBoolean(cm.isAlphaPremultiplied()));
sctCM.setEL("transparency",toStringTransparency(cm.getTransparency()));
sctCM.setEL("pixel_size",Caster.toDouble(cm.getPixelSize()));
sctCM.setEL("num_components",Caster.toDouble(cm.getNumComponents()));
sctCM.setEL("num_color_components",Caster.toDouble(cm.getNumColorComponents()));
sctCM.setEL("colorspace",toStringColorSpace(cm.getColorSpace()));
//bits_component
int[] bitspercomponent = cm.getComponentSize();
Array arr=new ArrayImpl();
Double value;
for (int i = 0; i < bitspercomponent.length; i++) {
sctCM.setEL("bits_component_" + (i + 1),value=new Double(bitspercomponent[i]));
arr.appendEL(value);
}
sctCM.setEL("bits_component",arr);
// colormodel_type
if (cm instanceof ComponentColorModel) sctCM.setEL("colormodel_type", "ComponentColorModel");
else if (cm instanceof IndexColorModel) sctCM.setEL("colormodel_type", "IndexColorModel");
else if (cm instanceof PackedColorModel) sctCM.setEL("colormodel_type", "PackedColorModel");
else sctCM.setEL("colormodel_type", List.last(cm.getClass().getName(), '.'));
metadata(sctInfo);
ImageMeta.addInfo(format,source,sctInfo);
this.sctInfo=sctInfo;
return sctInfo;
}
private void metadata(Struct parent) {
if(StringUtil.isEmpty(format)) return;
Iterator<ImageReader> it = ImageIO.getImageReadersBySuffix(format);
while(it.hasNext()) {
ImageReader ir=(ImageReader) it.next();
ImageInputStream iis=null;
try {
IIOMetadata metadata=null;
synchronized (sync) {
if(source instanceof File) { // TODO create ResourceImageInputStream
iis=new FileImageInputStream((File) source);
}
else iis=new MemoryCacheImageInputStream(new ByteArrayInputStream(getImageBytes(format)));
ir.setInput(iis);
metadata=ir.getImageMetadata(0);
ir.reset();
}
String[] formatNames = metadata.getMetadataFormatNames();
for(int i=0;i<formatNames.length;i++) {
Node root = metadata.getAsTree(formatNames[i]);
//print.out(XMLCaster.toString(root));
addMetaddata(parent,"metadata",root);
}
}
catch (Throwable t) {}
finally {
ImageUtil.closeEL(iis);
}
}
}
private void addMetaddata(Struct parent, String name, Node node) {
// attributes
NamedNodeMap attrs = node.getAttributes();
Attr attr;
int len=attrs.getLength();
if(len==1 && "value".equals(attrs.item(0).getNodeName())) {
parent.setEL(name, attrs.item(0).getNodeValue());
}
else {
Struct sct=metaGetChild(parent,name);
for(int i=attrs.getLength()-1;i>=0;i--) {
attr=(Attr) attrs.item(i);
sct.setEL(attr.getName(), attr.getValue());
}
}
// child nodes
NodeList children = XMLUtil.getChildNodes(node, Node.ELEMENT_NODE);
Element el;
for(int i=children.getLength()-1;i>=0;i--) {
el=(Element) children.item(i);
Struct sct = metaGetChild(parent,name);
addMetaddata(sct, el.getNodeName(),children.item(i));
}
}
private Struct metaGetChild(Struct parent, String name) {
Object child=parent.get(name,null);
if(child instanceof Struct) return (Struct) child;
Struct sct=new StructImpl();
parent.setEL(name, sct);
return sct;
}
public void sharpen(float gain) throws ExpressionException{
ParameterBlock params = new ParameterBlock();
params.addSource(image());
params.add((Object) null);
params.add(new Float(gain));
image(JAI.create("unsharpmask", params).getAsBufferedImage());
}
public void setTranparency(float percent) throws ExpressionException{
if(percent==-1)return;
tranparency=percent;
AlphaComposite rule = AlphaComposite.getInstance(3, 1.0F-(percent/100.0F));
getGraphics().setComposite(rule);
}
public void invert() throws ExpressionException{
ParameterBlock params = new ParameterBlock();
params.addSource(image());
image(JAI.create("invert", params).getAsBufferedImage());
}
public Image copy(float x, float y, float width, float height) throws ExpressionException{
ParameterBlock params = new ParameterBlock();
params.addSource(image());
params.add(x);
params.add(y);
params.add(width);
params.add(height);
//image(JAI.create("crop", params).getAsBufferedImage());
return new Image(JAI.create("crop", params).getAsBufferedImage());
}
public Image copy(float x, float y, float width, float height, float dx,float dy) throws ExpressionException{
Image img = copy(x, y, width, height);
img.getGraphics().copyArea((int)x, (int)y, (int)width, (int)height, (int)(dx-x), (int)(dy-y));
return img;
}
public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle, boolean filled) throws ExpressionException{
if (filled)
getGraphics().fillArc(x, y, width, height, startAngle, arcAngle);
else
getGraphics().drawArc(x, y, width, height, startAngle, arcAngle);
}
public void draw3DRect(int x, int y, int width, int height, boolean raised, boolean filled) throws ExpressionException{
if (filled)
getGraphics().fill3DRect(x, y, width+1, height+1, raised);
else
getGraphics().draw3DRect(x, y, width, height, raised);
}
public void drawCubicCurve(double ctrlx1, double ctrly1, double ctrlx2, double ctrly2,double x1, double y1, double x2, double y2) throws ExpressionException{
CubicCurve2D curve = new CubicCurve2D.Double(x1,y1,ctrlx1,ctrly1,ctrlx2,ctrly2,x2,y2);
getGraphics().draw(curve);
}
public void drawPoint(int x, int y) throws ExpressionException {
drawLine(x, y, x + 1, y);
}
public void drawQuadraticCurve(double x1, double y1, double ctrlx, double ctrly, double x2, double y2) throws ExpressionException {
QuadCurve2D curve = new QuadCurve2D.Double(x1, y1, ctrlx, ctrly, x2, y2);
getGraphics().draw(curve);
}
public void drawRect(int x, int y, int width, int height, boolean filled) throws ExpressionException {
if (filled)
getGraphics().fillRect(x, y, width + 1, height + 1);
else
getGraphics().drawRect(x, y, width, height);
}
public void drawRoundRect(int x, int y, int width, int height,int arcWidth, int arcHeight, boolean filled) throws ExpressionException{
if (filled)
getGraphics().fillRoundRect(x, y, width + 1, height + 1, arcWidth,arcHeight);
else
getGraphics().drawRoundRect(x, y, width, height, arcWidth, arcHeight);
}
public void drawLine(int x1, int y1, int x2, int y2) throws ExpressionException{
getGraphics().drawLine(x1, y1, x2, y2);
}
public void drawImage(Image img,int x, int y) throws ExpressionException{
getGraphics().drawImage(img.image(), x, y,null);
}
public void drawImage(Image img,int x, int y, int width, int height) throws ExpressionException{
getGraphics().drawImage(img.image(), x, y,width,height,null);
}
public void drawLines(int[] xcoords, int[] ycoords, boolean isPolygon,boolean filled) throws ExpressionException{
if (isPolygon) {
if (filled) getGraphics().fillPolygon(xcoords, ycoords, xcoords.length);
else getGraphics().drawPolygon(xcoords, ycoords, xcoords.length);
}
else {
getGraphics().drawPolyline(xcoords, ycoords, xcoords.length);
}
}
public void drawOval(int x, int y, int width, int height, boolean filled) throws ExpressionException {
if (filled) getGraphics().fillOval(x, y, width, height);
else getGraphics().drawOval(x, y, width, height);
}
public void drawString(String text, int x, int y, Struct attr) throws PageException {
if (attr != null && attr.size()>0) {
// font
String font=StringUtil.toLowerCase(Caster.toString(attr.get("font",""))).trim();
if(!StringUtil.isEmpty(font)) {
font=FontUtil.getFont(font).getFontName();
}
else font = "Serif";
// alpha
//float alpha=Caster.toFloatValue(attr.get("alpha",null),1F);
// size
int size=Caster.toIntValue(attr.get("size", Constants.INTEGER_10));
// style
int style=Font.PLAIN;
String strStyle=StringUtil.toLowerCase(Caster.toString(attr.get("style","")));
strStyle=StringUtil.removeWhiteSpace(strStyle);
if(!StringUtil.isEmpty(strStyle)) {
if("plain".equals(strStyle)) style=Font.PLAIN;
else if("bold".equals(strStyle)) style=Font.BOLD;
else if("italic".equals(strStyle)) style=Font.ITALIC;
else if("bolditalic".equals(strStyle)) style=Font.BOLD+Font.ITALIC;
else if("bold,italic".equals(strStyle)) style=Font.BOLD+Font.ITALIC;
else if("italicbold".equals(strStyle)) style=Font.BOLD+Font.ITALIC;
else if("italic,bold".equals(strStyle)) style=Font.BOLD+Font.ITALIC;
else throw new ExpressionException(
"key style of argument attributeCollection has a invalid value ["+strStyle+"], valid values are [plain,bold,italic,bolditalic]");
}
// strikethrough
boolean strikethrough = Caster.toBooleanValue(attr.get("strikethrough",Boolean.FALSE));
// underline
boolean underline = Caster.toBooleanValue(attr.get("underline",Boolean.FALSE));
AttributedString as = new AttributedString(text);
as.addAttribute(TextAttribute.FONT, new Font(font, style, size));
if(strikethrough) as.addAttribute(TextAttribute.STRIKETHROUGH,TextAttribute.STRIKETHROUGH_ON);
if(underline) as.addAttribute(TextAttribute.UNDERLINE,TextAttribute.UNDERLINE_ON);
Graphics2D g = getGraphics();
//if(alpha!=1D) setAlpha(g,alpha);
g.drawString(as.getIterator(), x, y);
}
else getGraphics().drawString(text, x, y);
}
/*private void setAlpha(Graphics2D graphics,float alpha) {
//Composite originalComposite = graphics.getComposite();
AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha);
graphics.setComposite(alphaComposite);
//graphics.setComposite(originalComposite);
}*/
public void setDrawingStroke(Struct attr) throws PageException {
// empty
if(attr==null || attr.size()==0) {
setDrawingStroke(new BasicStroke());
return;
}
// width
float width=Caster.toFloatValue(attr.get("width",new Float(1F)));
if(width<0) throw new ExpressionException("key [width] should be a none negativ number");
// endcaps
String strEndcaps=Caster.toString(attr.get("endcaps","square"));
strEndcaps=strEndcaps.trim().toLowerCase();
int endcaps;
if("square".equals(strEndcaps)) endcaps = BasicStroke.CAP_SQUARE;
else if("butt".equals(strEndcaps)) endcaps = BasicStroke.CAP_BUTT;
else if("round".equals(strEndcaps)) endcaps = BasicStroke.CAP_ROUND;
else throw new ExpressionException("key [endcaps] has a invalid value ["+strEndcaps+"], valid values are [square,round,butt]");
// linejoins
String strLinejoins=Caster.toString(attr.get("linejoins","miter"));
strLinejoins=strLinejoins.trim().toLowerCase();
int linejoins;
if("bevel".equals(strLinejoins)) linejoins = BasicStroke.JOIN_BEVEL;
else if("miter".equals(strLinejoins)) linejoins = BasicStroke.JOIN_MITER;
else if("round".equals(strLinejoins)) linejoins = BasicStroke.JOIN_ROUND;
else throw new ExpressionException("key [linejoins] has a invalid value ["+strLinejoins+"], valid values are [bevel,miter,round]");
// miterlimit
float miterlimit = 10.0F;
if(linejoins==BasicStroke.JOIN_MITER) {
miterlimit=Caster.toFloatValue(attr.get("miterlimit",new Float(10F)));
if(miterlimit<1F) throw new ExpressionException("key [miterlimit] should be greater or equal to 1");
}
// dashArray
Object oDashArray=attr.get("dashArray",null);
float[] dashArray=null;
if(oDashArray!=null) {
dashArray=ArrayUtil.toFloatArray(oDashArray);
}
// dash_phase
float dash_phase=Caster.toFloatValue(attr.get("dash_phase",new Float(0F)));
setDrawingStroke(width, endcaps, linejoins, miterlimit, dashArray, dash_phase);
}
public void setDrawingStroke(float width, int endcaps, int linejoins,float miterlimit, float[] dash,float dash_phase) throws ExpressionException {
setDrawingStroke(new BasicStroke(width, endcaps, linejoins, miterlimit, dash, dash_phase));
}
public void setDrawingStroke(Stroke stroke) throws ExpressionException {
if(stroke==null) return;
this.stroke=stroke;
getGraphics().setStroke(stroke);
}
public void flip(TransposeType transpose) throws ExpressionException {
ParameterBlock params = new ParameterBlock();
params.addSource(image());
params.add(transpose);
image(JAI.create("transpose", params).getAsBufferedImage());
}
public void grayscale() throws ExpressionException {
BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics2D graphics = img.createGraphics();
graphics.drawImage(image(),new AffineTransformOp(AffineTransform.getTranslateInstance(0.0, 0.0),1),0, 0);
graphics.dispose();
image(img);
}
public void rgb() throws ExpressionException {
BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_BYTE_INDEXED);
Graphics2D graphics = img.createGraphics();
graphics.drawImage(image(),new AffineTransformOp(AffineTransform.getTranslateInstance(0.0, 0.0),1),0, 0);
graphics.dispose();
image(img);
}
public void threeBBger() throws ExpressionException {
BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR);
Graphics2D graphics = img.createGraphics();
graphics.drawImage(image(),new AffineTransformOp(AffineTransform.getTranslateInstance(0.0, 0.0),1),0, 0);
graphics.dispose();
image(img);
}
public void overlay(Image topImage) throws ExpressionException {
ParameterBlock params = new ParameterBlock();
params.addSource(image());
params.addSource(topImage.image());
image(JAI.create("overlay", params).getAsBufferedImage());
}
public void paste(Image topImage, int x, int y) throws ExpressionException {
RenderingHints interp = new RenderingHints(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);
BorderExtender extender = BorderExtender.createInstance(1);
Graphics2D g = getGraphics();
g.addRenderingHints(new RenderingHints(JAI.KEY_BORDER_EXTENDER,extender));
g.drawImage(topImage.image(), (new AffineTransformOp(AffineTransform.getTranslateInstance(x,y),interp)), 0, 0);
}
public void setXorMode(Color color) throws ExpressionException {
if(color==null) return;
xmColor=color;
getGraphics().setXORMode(color);
}
public void translate(int xtrans, int ytrans, Object interpolation) throws ExpressionException {
RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION,interpolation);
if(interpolation!=RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR) {
hints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, BorderExtender.createInstance(1)));
}
ParameterBlock pb = new ParameterBlock();
pb.addSource(image());
BufferedImage img = JAI.create("translate", pb).getAsBufferedImage();
Graphics2D graphics = img.createGraphics();
graphics.clearRect(0, 0, img.getWidth(), img.getHeight());
AffineTransform at = new AffineTransform();
at.setToIdentity();
graphics.drawImage(image(), new AffineTransformOp(at, hints), xtrans, ytrans);
graphics.dispose();
image(img);
}
public void translateAxis(int x, int y) throws ExpressionException {
getGraphics().translate(x, y);
}
public void rotateAxis(double angle) throws ExpressionException {
getGraphics().rotate(Math.toRadians(angle));
}
public void rotateAxis(double angle, double x, double y) throws ExpressionException {
getGraphics().rotate(Math.toRadians(angle), x, y);
}
public void shearAxis(double shx, double shy) throws ExpressionException {
getGraphics().shear(shx, shy);
}
public void shear(float shear, ShearDir direction, Object interpolation) throws ExpressionException {
ParameterBlock params = new ParameterBlock();
params.addSource(image());
params.add(shear);
params.add(direction);
params.add(0.0F);
params.add(0.0F);
RenderingHints hints = null;
if (interpolation==RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR)
params.add(Interpolation.getInstance(0));
else if (interpolation==RenderingHints.VALUE_INTERPOLATION_BILINEAR) {
params.add(Interpolation.getInstance(1));
BorderExtender extender = BorderExtender.createInstance(1);
hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
}
else if (interpolation==RenderingHints.VALUE_INTERPOLATION_BICUBIC) {
params.add(Interpolation.getInstance(2));
BorderExtender extender = BorderExtender.createInstance(1);
hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
}
// TODO
Color bg = getGraphics().getBackground();
params.add(new double[]{bg.getRed(),bg.getGreen(),bg.getBlue()});
image(JAI.create("shear", params, hints).getAsBufferedImage());
}
public BufferedImage getBufferedImage() throws ExpressionException {
return image();
}
public BufferedImage image() throws ExpressionException {
if(_image==null) throw (new ExpressionException("image is not initalized"));
return _image;
}
public void image(BufferedImage image) {
this._image=image;
graphics=null;
sctInfo=null;
}
private Graphics2D getGraphics() throws ExpressionException {
if(graphics==null) {
graphics=image() .createGraphics();
// reset all properties
if(antiAlias!=ANTI_ALIAS_NONE) setAntiAliasing(antiAlias==ANTI_ALIAS_ON);
if(bgColor!=null) setBackground(bgColor);
if(fgColor!=null) setColor(fgColor);
if(alpha!=1) setAlpha(alpha);
if(tranparency!=-1) setTranparency(tranparency);
if(xmColor!=null) setXorMode(xmColor);
if(stroke!=null) setDrawingStroke(stroke);
}
return graphics;
}
private String toStringColorSpace(ColorSpace colorSpace) {
switch (colorSpace.getType()) {
case 0: return "Any of the family of XYZ color spaces";
case 1: return "Any of the family of Lab color spaces";
case 2: return "Any of the family of Luv color spaces";
case 3: return "Any of the family of YCbCr color spaces";
case 4:return "Any of the family of Yxy color spaces";
case 5: return "Any of the family of RGB color spaces";
case 6: return "Any of the family of GRAY color spaces";
case 7: return "Any of the family of HSV color spaces";
case 8: return "Any of the family of HLS color spaces";
case 9: return "Any of the family of CMYK color spaces";
case 11: return "Any of the family of CMY color spaces";
case 12: return "Generic 2 component color space.";
case 13: return "Generic 3 component color space.";
case 14: return "Generic 4 component color space.";
case 15: return "Generic 5 component color space.";
case 16: return "Generic 6 component color space.";
case 17: return "Generic 7 component color space.";
case 18: return "Generic 8 component color space.";
case 19: return "Generic 9 component color space.";
case 20: return "Generic 10 component color space.";
case 21: return "Generic 11 component color space.";
case 22: return "Generic 12 component color space.";
case 23: return "Generic 13 component color space.";
case 24: return "Generic 14 component color space.";
case 25: return "Generic 15 component color space.";
case 1001: return "CIEXYZ";
case 1003: return "GRAY";
case 1004: return "LINEAR_RGB";
case 1002: return "PYCC";
case 1000: return "sRGB";
}
return "Unknown ColorSpace" + colorSpace;
}
private Object toStringTransparency(int transparency) {
if(Transparency.OPAQUE==transparency) return "OPAQUE";
if(Transparency.BITMASK==transparency) return "BITMASK";
if(Transparency.TRANSLUCENT==transparency) return "TRANSLUCENT";
return "Unknown type of transparency";
}
public String writeBase64(Resource destination, String format, boolean inHTMLFormat) throws PageException, IOException {
// destination
if(destination==null) {
if(source!=null)destination=source;
else throw new IOException("missing destination file");
}
String content = getBase64String(format);
if(inHTMLFormat) content="data:image/" + format + ";base64,"+content;
IOUtil.write(destination, content, null, false);
return content;
}
public String getBase64String(String format) throws PageException {
byte[] imageBytes = getImageBytes(format);
return new String(Base64.encodeBase64(imageBytes));
}
public void writeOut(Resource destination, boolean overwrite, float quality) throws IOException, ExpressionException {
String format = ImageUtil.getFormatFromExtension(destination,null);
writeOut(destination, format, overwrite, quality);
}
public void writeOut(Resource destination, String format,boolean overwrite, float quality) throws IOException, ExpressionException {
if(destination==null) {
if(source!=null)destination=source;
else throw new IOException("missing destination file");
}
if(destination.exists()) {
if(!overwrite)throw new IOException("can't overwrite existing image");
}
OutputStream os=null;
ImageOutputStream ios = null;
try {
os=destination.getOutputStream();
ios = ImageIO.createImageOutputStream(os);
writeOut(ios, format, quality);
}
finally {
IOUtil.closeEL(ios);
IOUtil.closeEL(os);
}
}
public static void writeOutGif(BufferedImage src, OutputStream os) throws IOException {
BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(), BufferedImage.TYPE_INT_ARGB);
QuantizeFilter filter=new QuantizeFilter();
filter.setSerpentine(true);
filter.setDither(true);
//filter.setNumColors(8);
filter.filter(src, dst);
//image(Quantizer.quantize(image(), 8));
try {
GifEncoder enc = new GifEncoder(dst);
enc.Write(os);
os.flush();
} catch (AWTException e) {
throw new IOException(e.getMessage());
}
}
public void writeOut(OutputStream os, String format,float quality, boolean closeStream) throws IOException, ExpressionException {
ImageOutputStream ios = ImageIO.createImageOutputStream(os);
try{
writeOut(ios, format, quality);
}
finally{
IOUtil.closeEL(ios);
}
}
public void writeOut(ImageOutputStream ios, String format,float quality) throws IOException, ExpressionException {
if(quality<0 || quality>1)
throw new IOException("quality has a invalid value ["+quality+"], value has to be between 0 and 1");
if(StringUtil.isEmpty(format)) format=this.format;
if(StringUtil.isEmpty(format)) throw new IOException("missing format");
BufferedImage im = image();
ImageWriter writer = null;
ImageTypeSpecifier type =ImageTypeSpecifier.createFromRenderedImage(im);
Iterator<ImageWriter> iter = ImageIO.getImageWriters(type, format);
if (iter.hasNext()) {
writer = (ImageWriter)iter.next();
}
if (writer == null) throw new IOException("no writer for format ["+format+"] available, available writer formats are ["+List.arrayToList(ImageUtil.getWriterFormatNames(), ",")+"]");
ImageWriteParam iwp=null;
if("jpg".equalsIgnoreCase(format)) {
ColorModel cm = im.getColorModel();
if(cm.hasAlpha())im=jpgImage(im);
JPEGImageWriteParam jiwp = new JPEGImageWriteParam(Locale.getDefault());
jiwp.setOptimizeHuffmanTables(true);
iwp=jiwp;
}
else iwp = writer.getDefaultWriteParam();
setCompressionModeEL(iwp,ImageWriteParam.MODE_EXPLICIT);
setCompressionQualityEL(iwp,quality);
writer.setOutput(ios);
try {
writer.write(null, new IIOImage(im, null, null), iwp);
//writer.write(im);
} finally {
writer.dispose();
ios.flush();
}
}
private BufferedImage jpgImage(BufferedImage src)
{
int w = src.getWidth();
int h = src.getHeight();
SampleModel srcSM = src.getSampleModel();
WritableRaster srcWR = src.getRaster();
java.awt.image.DataBuffer srcDB = srcWR.getDataBuffer();
ColorModel rgb = new DirectColorModel(32, 0xff0000, 65280, 255);
int[] bitMasks = new int[]{0xff0000, 65280, 255};
SampleModel csm = new SinglePixelPackedSampleModel(3, w, h, bitMasks);
int data[] = new int[w * h];
for(int i = 0; i < h; i++) {
for(int j = 0; j < w; j++) {
int pix[] = null;
int sample[] = srcSM.getPixel(j, i, pix, srcDB);
if(sample[3] == 0 && sample[2] == 0 && sample[1] == 0 && sample[0] == 0)
data[i * w + j] = 0xffffff;
else
data[i * w + j] = sample[0] << 16 | sample[1] << 8 | sample[2];
}
}
java.awt.image.DataBuffer db = new DataBufferInt(data, w * h * 3);
WritableRaster wr = Raster.createWritableRaster(csm, db, new Point(0, 0));
return new BufferedImage(rgb, wr, false, null);
}
private void setCompressionModeEL(ImageWriteParam iwp, int mode) {
try {
iwp.setCompressionMode(mode);
}
catch(Throwable t) {}
}
private void setCompressionQualityEL(ImageWriteParam iwp, float quality) {
try {
iwp.setCompressionQuality(quality);
}
catch(Throwable t) {}
}
public void convert(String format) {
this.format=format;
}
public static String[] getReaderFormatNames() {
return ImageIO.getReaderFormatNames();
}
public static String[] getWriterFormatNames() {
return ImageIO.getWriterFormatNames();
}
public void scaleToFit(String fitWidth, String fitHeight,String interpolation, double blurFactor) throws PageException {
if (StringUtil.isEmpty(fitWidth) || StringUtil.isEmpty(fitHeight))
resize(fitWidth, fitHeight, interpolation, blurFactor);
else {
float width = Caster.toFloatValue(fitWidth) / getWidth();
float height= Caster.toFloatValue(fitHeight) / getHeight();
if (width < height) resize(fitWidth, "", interpolation, blurFactor);
else resize("", fitHeight, interpolation, blurFactor);
}
}
/**
* Convenience method that returns a scaled instance of the
* provided {@code BufferedImage}.
*
* @param img the original image to be scaled
* @param targetWidth the desired width of the scaled instance,
* in pixels
* @param targetHeight the desired height of the scaled instance,
* in pixels
* @param hint one of the rendering hints that corresponds to
* {@code RenderingHints.KEY_INTERPOLATION} (e.g.
* {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
* {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
* {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
* @param higherQuality if true, this method will use a multi-step
* scaling technique that provides higher quality than the usual