package util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.AbstractView;
public class ImageView extends AbstractView {
private static final String CONTENT_TYPE = "image/jpeg";
private byte[] content;
public ImageView(ByteArrayOutputStream outputStream) {
content = outputStream.toByteArray();
}
public ImageView(InputStream inputStream) {
try {
int size = inputStream.available();
byte[] buffer = new byte[size];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(size);
int position = 0;
while (true) {
position = inputStream.read(buffer);
if (position == -1) {
break;
}
outputStream.write(buffer, 0, position);
}
content = outputStream.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
closeInputStream(inputStream);
}
}
private void closeInputStream(InputStream inputStream) {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
if (content == null) {
return;
}
response.setContentType(CONTENT_TYPE);
response.setContentLength(content.length);
response.setHeader("Cache-Control", "No-cache");
response.setDateHeader("Expires", 0);
response.getOutputStream().write(content);
}
}
时间: 2024-11-07 09:41:14