是这样最近在接触一个需求是根据样式生成一批照片并上传到服务器上,但我在使用ImageIO.write(image, "jpeg", mfile);这个方法的时候就一直有内存泄漏 怎么看也无法找到原因愿大神或经验者帮忙看下😭
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class TestImageIo {
// 辅助类实现自动资源管理
static class AutoClosableBufferedImage extends BufferedImage implements AutoCloseable {
public AutoClosableBufferedImage(int width, int height, int type) {
super(width, height, type);
}
@Override
public void close() {
// 强制提示垃圾回收
getGraphics().dispose();
this.flush(); // 释放本地资源
}
}
private void saveResizedImage(AutoClosableBufferedImage image, int index) throws IOException {
File mfile = new File("/tmp/certPhoto/" + index + "12.jpg");
ImageIO.write(image, "jpeg", mfile);
}
public void getTestPhoto() throws Exception {
for (int i = 0; i < 100; i++) {
try (AutoClosableBufferedImage targetImg = new AutoClosableBufferedImage(2480, 3508, BufferedImage.TYPE_INT_RGB);) {
saveResizedImage(targetImg, i);
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("Failed to save resized image", e);
}
}
System.out.println("end");
}
}