是否有可能通過逐字節地創建一個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