我正在尝试通过 db 调整图像的大小。下面是我从数据库中获取 blob 并尝试使用 UtilImage 调整其大小的 webservlet。
问题:我尝试调整大小的图像未显示在浏览器中,并且我的控制台未列出任何堆栈跟踪。在UtilImage.resize()
返回一个新的 BufferedImage 的调用之后,imageType 已从 5 更改为 1。
@WebServlet("/images")
public class BildService extends HttpServlet {
private static final long serialVersionUID = 1L;
@EJB
private LesenService lesenService;
private Veranstaltung veranstaltung;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer veranstaltungId = Integer.parseInt(request.getParameter("id"));
veranstaltung = lesenService.getVeranstaltungByVeranstaltungId(veranstaltungId);
if (veranstaltung == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType(veranstaltung.getFormat());
OutputStream os = response.getOutputStream();
byte[] img = UtilImage.resizeScalr(veranstaltung.getBild(), veranstaltung.getFormat());
os.write(img);
}
}
This is my UtilImage class:
public class UtilImage {
public static final byte[] resizeScalr(byte[] img, String type) {
if (img != null) {
BufferedImage bImage = getBufferedImage(img);
double scaleFactor = getScaleFactor(bImage.getWidth(), UtilKonstanten.PICTURE_WIDTH);
int targetWidth = (int) (scaleFactor * bImage.getWidth());
int targetHeight = (int) (scaleFactor * bImage.getHeight());
// return getByteArray(Scalr.resize(bImage, targetWidth,
// targetHeight), type);
return getByteArray(Scalr.resize(bImage, Scalr.Method.BALANCED, targetWidth, targetHeight), type);
}
return null;
}
private static final double getScaleFactor(int width, int wishwidth) {
return (double) wishwidth / width;
}
private static final BufferedImage getBufferedImage(byte[] array) {
InputStream is = new ByteArrayInputStream(array);
BufferedImage img;
try {
img = ImageIO.read(is);
return img;
} catch (IOException e) {
// TODO
e.printStackTrace();
}
return null;
}
private static final byte[] getByteArray(BufferedImage img, String type) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, type, os);
byte[] byteArray = os.toByteArray();
os.close();
return byteArray;
} catch (IOException e) {
// TODO
e.printStackTrace();
}
return null;
}
}
非常感谢你的帮助!