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.
package com.artcore.web;
import javax.servlet.http.*;
import javax.servlet.*;
import javax.media.jai.*;
import java.io.*;
import java.awt.image.renderable.*;
import com.sun.media.jai.codec.*;
public class ArtImageServlet extends HttpServlet {
private String imagesDir;
private String[] commands = {
"crop",
"scale",
"rotate",
"grayscale"
};
private Class [] commandMethodParams = {
HttpServletRequest. class ,
HttpServletResponse. class ,
File. class
};
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
loadInitParameters();
// get image file name
String imageName = request.getParameter("image");
File sourceImageFile = getSourceImageFile(imageName);
if (sourceImageFile == null ) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return ;
}
// file exists, detect mime-type
String mimeType = getServletContext().getMimeType(sourceImageFile.getName());
// now get some command for image processing
String command = request.getParameter("command");
if (isValidCommand(command)) {
// process image
// reflect command to method
String methodName = detectMethodName(command);
try {
Object[] params = new Object[ 3 ];
params[ 0 ] = request;
params[ 1 ] = response;
params[ 2 ] = sourceImageFile;
getClass().getMethod(methodName, commandMethodParams).invoke( this , params);
} catch (Exception e) {
e.printStackTrace();
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
// no any command or bad identifier of command
// try get sizex or sizey request param
String sizex = request.getParameter("sizex");
String sizey = request.getParameter("sizey");
byte [] data;
if (isEmpty(sizex) && isEmpty(sizey)) {
// raw image (without resize)
data = getRawBytes(sourceImageFile);
} else {
// resize by X
data = resizeByXY(sourceImageFile, sizex, sizey);
}
writeResponse(response, mimeType, sourceImageFile.getName(), data);
}
}
private byte [] resizeByXY(File sourceImageFile, String sizex, String sizey) throws IOException {
int sx = getIntFromString(sizex);
int sy = getIntFromString(sizey);
FileInputStream is = new FileInputStream(sourceImageFile);
SeekableStream s = SeekableStream.wrapInputStream(is, true);
RenderedOp image = JAI.create("stream", s);
((OpImage) image.getRendering()).setTileCache( null );
int ww = image.getWidth();
int hh = image.getHeight();
if (sx == - 1 ) {
sx = ( int ) (ww * (( double ) sy / hh));
}
if (sy == - 1 ) {
sy = ( int ) (hh * (( double ) sx / ww));
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image = scaleToPix(image, sx, sy);
JAI.create("encode", image, baos, "PNG", null );
return baos.toByteArray();
}
private RenderedOp scaleToPix(RenderedOp image, double width, double height) {
if (image == null )
return null ;
int ww = image.getWidth();
int hh = image.getHeight();
float fattX = ( float ) (width / ww);
float fattY = ( float ) (height / hh);
Interpolation interp = Interpolation.getInstance(Interpolation.INTERP_BICUBIC_2);
ParameterBlock parSC = new ParameterBlock();
parSC.addSource(image);
parSC.add(fattX); // x trans
parSC.add(fattY); // x trans
parSC.add( 0 .0f); // x trans
parSC.add( 0 .0f); // x trans
parSC.add(interp);
try {
return JAI.create("scale", parSC);
} catch (Exception e) {
e.printStackTrace();
return null ;
}
}
private byte [] getRawBytes(File sourceImageFile) throws IOException {
InputStream is = new FileInputStream(sourceImageFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte [] buf = new byte [ 1024 ];
int readed;
while ((readed = is.read(buf)) != - 1 ) {
baos.write(buf, 0 , readed);
}
is.close();
return baos.toByteArray();
}
private void writeResponse(HttpServletResponse response, String mimeType, String contentName, byte [] data) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
if (isEmpty(mimeType)) {
response.setContentType("application/octet-stream");
} else {
response.setContentType(mimeType);
}
response.setContentLength(data.length);
response.setHeader("Content-Name", contentName);
response.setHeader("Content-Disposition", "filename=" + contentName);
response.setHeader("Connection", "close");
OutputStream out = response.getOutputStream();
out.write(data);
out.close();
}
public void doImageScale(HttpServletRequest request, HttpServletResponse response, File sourceImageFile) throws IOException {
// get parameters for scale
String sz = request.getParameter("z");
float z = getFloatFromString(sz);
// z - scale factor, 2 is 200%, 0.5 is 50%
if (z < 0 ) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return ;
}
FileInputStream is = new FileInputStream(sourceImageFile);
SeekableStream s = SeekableStream.wrapInputStream(is, true);
RenderedOp image = JAI.create("stream", s);
((OpImage) image.getRendering()).setTileCache( null );
image = scaleToPix(image, image.getWidth() * z, image.getHeight() * z);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JAI.create("encode", image, baos, "PNG", null );
String mimeType = getServletContext().getMimeType(sourceImageFile.getName());
writeResponse(response, mimeType, sourceImageFile.getName(), baos.toByteArray());
}
public void doImageGrayscale(HttpServletRequest request, HttpServletResponse response, File sourceImageFile) throws IOException {
// no input parameters
// typical weights for converting RGB to Grayscale
// gray = 0.3*red + 0.59*green + 0.11*blue
PlanarImage image = JAI.create("fileload", sourceImageFile.getAbsolutePath());
double [][] matrix = {{ 0 .3D, 0 .59D, 0 .11D, 0D}};
// double[][] matrix = {{0.114D, 0.587D, 0.299D, 0D}};
ParameterBlock pb = new ParameterBlock();
pb.addSource(image);
pb.add(matrix);
PlanarImage temp = JAI.create("bandcombine", pb, null );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JAI.create("encode", temp, baos, "PNG", null );
String mimeType = getServletContext().getMimeType(sourceImageFile.getName());
writeResponse(response, mimeType, sourceImageFile.getName(), baos.toByteArray());
}
public void doImageRotate(HttpServletRequest request, HttpServletResponse response, File sourceImageFile) throws IOException {
// get angle
String sa = request.getParameter("a");
int a = getIntFromString(sa);
if (a == - 1 || a > 360 ) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return ;
}
float angle = ( float ) Math.toRadians(a);
PlanarImage image = JAI.create("fileload", sourceImageFile.getAbsolutePath());
float centerx = image.getWidth() / 2f;
float centery = image.getHeight() / 2f;
ParameterBlock pb = new ParameterBlock();
pb.addSource(image);
pb.add(centerx);
pb.add(centery);
pb.add(angle);
pb.add( new InterpolationBilinear());
PlanarImage temp = JAI.create("rotate", pb);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JAI.create("encode", temp, baos, "PNG", null );
String mimeType = getServletContext().getMimeType(sourceImageFile.getName());
writeResponse(response, mimeType, sourceImageFile.getName(), baos.toByteArray());
}
public void doImageCrop(HttpServletRequest request, HttpServletResponse response, File sourceImageFile) throws IOException {
// get additional parameters for crop
String cx = request.getParameter("x");
String cy = request.getParameter("y");
String cw = request.getParameter("w");
String ch = request.getParameter("h");
int x = getIntFromString(cx);
int y = getIntFromString(cy);
int w = getIntFromString(cw);
int h = getIntFromString(ch);
if (x == - 1 || y == - 1 ) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return ;
}
PlanarImage image = JAI.create("fileload", sourceImageFile.getAbsolutePath());
if (w == - 1 ) {
w = image.getWidth() - x;
}
if (h == - 1 ) {
h = image.getHeight() - y;
}
// Create a ParameterBlock with information for the cropping.
ParameterBlock pb = new ParameterBlock();
pb.addSource(image);
pb.add(( float ) x);
pb.add(( float ) y);
pb.add(( float ) w);
pb.add(( float ) h);
// crop
PlanarImage temp = JAI.create("crop", pb, null );
// a cropped image will have its origin set to the (x,y) coordinates, and
// with the display method we use it will cause bands on the top and left
// borders. a simple way to solve this is to shift or translate the image
// by (-x,-y) pixels.
pb = new ParameterBlock();
pb.addSource(temp);
pb.add(( float ) -x);
pb.add(( float ) -y);
// create the output image by translating itself
temp = JAI.create("translate", pb, null );
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JAI.create("encode", temp, baos, "PNG", null );
String mimeType = getServletContext().getMimeType(sourceImageFile.getName());
writeResponse(response, mimeType, sourceImageFile.getName(), baos.toByteArray());
}
private float getFloatFromString(String value) {
try {
return Float .parseFloat(value);
} catch (Exception e) {
return - 1 .0f;
}
}
private int getIntFromString(String value) {
try {
return Integer.parseInt(value);
} catch (Exception e) {
return - 1 ;
}
}
private String detectMethodName(String command) {
String comId = command.trim();
String methodPrefix = "doImage";
char c = Character.toUpperCase(comId.charAt( 0 ));
return methodPrefix + c + comId.substring( 1 );
}
private boolean isValidCommand(String command) {
if (isEmpty(command)) {
return false;
}
for ( int i = 0 , n = commands.length; i < n; i++) {
String s = commands[i];
if (s.equals(command.trim())) {
return true;
}
}
return false;
}
private void loadInitParameters() {
if (imagesDir == null ) {
// get real path to images directory
imagesDir = getServletConfig().getInitParameter("images-dir");
imagesDir = getServletContext().getRealPath(imagesDir);
}
// load other init-params
// ...
}
private File getSourceImageFile(String imageName) {
if (isEmpty(imageName)) {
return null ;
}
File file = new File(imagesDir, imageName.trim());
return file.exists() ? file : null ;
}
private boolean isEmpty(String value) {
return value == null || value.trim().length() == 0 ;
}
}