是否有可能通过逐字节地创建一个BufferedImage来防止BufferedImage抛出OutOfMemoryError异常?防止BufferedImage抛出OutMemoryError
我使用这个方法来裁剪图像:
public static void cropImage(File originalImage, File to, int x1, int y1, int x2, int y2) {
try {
BufferedImage source = ImageIO.read(originalImage);
String mimeType = "image/jpeg";
if (to.getName().endsWith(".png")) {
mimeType = "image/png";
}
if (to.getName().endsWith(".gif")) {
mimeType = "image/gif";
}
int width = x2 - x1;
int height = y2 - y1;
// out
BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Image croppedImage = source.getSubimage(x1, y1, width, height);
Graphics graphics = dest.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, width, height);
graphics.drawImage(croppedImage, 0, 0, null);
ImageWriter writer = ImageIO.getImageWritersByMIMEType(mimeType).next();
ImageWriteParam params = writer.getDefaultWriteParam();
writer.setOutput(new FileImageOutputStream(to));
IIOImage image = new IIOImage(dest, null, null);
writer.write(null, image, params);
writer.dispose();
source = null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
我有512M的一个MaxPermSize参数,如果有人上传16000x10000的图像,我会得到一个OutOfMemoryError:BufferedImage source = ImageIO.read(originalImage);
PS:PermGen大小通常与您看到的OOME无关。图像数据分配在堆上,因此您需要增加堆大小(例如-Xmx512m)。 – haraldK