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 package fr.paris.lutece.plugins.avatarserver.service;
35
36 import fr.paris.lutece.portal.service.util.AppLogService;
37
38 import org.imgscalr.Scalr;
39
40 import java.awt.image.BufferedImage;
41 import java.awt.Color;
42
43 import java.io.ByteArrayInputStream;
44 import java.io.ByteArrayOutputStream;
45 import java.io.IOException;
46
47 import javax.imageio.IIOImage;
48 import javax.imageio.ImageIO;
49 import javax.imageio.ImageWriteParam;
50 import javax.imageio.ImageWriter;
51 import javax.imageio.stream.MemoryCacheImageOutputStream;
52
53
54
55
56 public final class ImageService
57 {
58
59 private static final String PARAMETER_JPG = "jpg";
60
61
62 private ImageService( )
63 {
64 }
65
66
67
68
69
70
71
72
73
74
75 public static byte [ ] resizeImage( byte [ ] byteArray, int width )
76 {
77 return resizeImage( byteArray, width, AvatarService.getQuality( ) );
78 }
79
80
81
82
83
84
85
86
87
88
89
90
91 public static byte [ ] resizeImage( byte [ ] byteArray, int width, float quality )
92 {
93 try
94 {
95
96 ByteArrayInputStream in = new ByteArrayInputStream( byteArray );
97 ByteArrayOutputStream out = new ByteArrayOutputStream( );
98 BufferedImage image = ImageIO.read( in );
99
100
101
102 if ( image.getColorModel( ).hasAlpha( ) )
103 {
104 BufferedImage newImage = new BufferedImage( image.getWidth( ), image.getHeight( ), BufferedImage.TYPE_INT_RGB );
105 newImage.createGraphics( ).drawImage( image, 0, 0, Color.WHITE, null );
106 image = newImage;
107 }
108
109 BufferedImage resizedImage;
110 resizedImage = Scalr.resize( image, Scalr.Mode.FIT_TO_WIDTH, width );
111
112
113 ImageWriter jpgWriter = ImageIO.getImageWritersByFormatName( PARAMETER_JPG ).next( );
114 ImageWriteParam jpgWriteParam = jpgWriter.getDefaultWriteParam( );
115 jpgWriteParam.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
116 jpgWriteParam.setCompressionQuality( quality );
117 jpgWriter.setOutput( new MemoryCacheImageOutputStream( out ) );
118 IIOImage outputImage = new IIOImage( resizedImage, null, null );
119 jpgWriter.write( null, outputImage, jpgWriteParam );
120 jpgWriter.dispose( );
121 out.flush( );
122
123 return out.toByteArray( );
124 }
125 catch( IOException ex )
126 {
127 AppLogService.error( "Avatar - Image Service - Error resizing image : " + ex.getMessage( ), ex );
128 }
129
130 return byteArray;
131 }
132 }