使用ImageIO打开图像后的Java文件操作

时间:2013-10-08 14:48:21

标签: java file javax.imageio

我正在使用Java并组合两个图像。我保存组合图像并想要删除叠加层,但似乎仍有流打开。我不知道关闭它们的方式和方式。

f_overlayf_image都是文件。

  // load source images
    BufferedImage image = null;
    BufferedImage overlay = null;
    try {
        log.debug(f_image.getAbsolutePath());
        log.debug(f_overlay.getAbsolutePath());
        image = ImageIO.read(f_image);
        overlay = ImageIO.read(f_overlay);
    } catch (IOException e) {
        log.error(e.getMessage());
    }

     // create the new image, canvas size is the max. of both image sizes
    int w = Math.max(image.getWidth(), overlay.getWidth());
    int h = Math.max(image.getHeight(), overlay.getHeight());
    BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

    // paint both images, preserving the alpha channels
    Graphics g = combined.getGraphics();
    g.drawImage(image, 0, 0, null);
    g.drawImage(overlay, 0, 0, null);

    // Save as new image
    try {
        ImageIO.write(combined, "PNG", f_image);
    } catch (IOException e) {
        log.error(e.getMessage());
    }

    // we can delete the overlay now
    log.debug("Delete overlay: " + f_overlay.delete());

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我的代码中没有任何错误。

但是,如果读取成功,我只会删除文件f_overlay。重要的是,在对文件对象调用delete()之后,不能将该对象用于其他任何内容,因此最好分配f_overlay = null

boolean state = f_overlay.delete();
f_overlay=null;
log.debug("Delete ... "+state);