是否可以通过逐字节创建 BufferedImage 来防止 BufferedImage 引发 OutOfMemoryError 异常?
我正在使用这种方法来裁剪图像:
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);
}
}
我的 MaxPermSize 为 512m,如果有人上传 16000x10000 图像,我将收到 OutOfMemoryError:BufferedImage source = ImageIO.read(originalImage);